> For the complete documentation index, see [llms.txt](https://docs.verge.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verge.io/knowledge-base/zh/automation-api/vm-creation-api.md).

# 虚拟机创建 API

{% hint style="info" %}
**要点**

* 使用 REST API 以必需的配置参数创建虚拟机
* 支持基于配方的虚拟机创建，可进行复杂配置
* 在虚拟机创建后添加磁盘、设备和网络接口
* 了解不同操作中 VM 键与 Machine 键的区别
  {% endhint %}

本指南介绍如何在 VergeOS 中创建虚拟机，从基础 VM 创建到添加磁盘、设备和网络接口。VergeOS API 为 VM 创建和硬件配置提供了全面的端点。

**阶段**：VM 创建（第 1 部分，共 4 部分） **输入**：API 凭据、集群信息、VM 规格 **输出**：VM 键（42）+ Machine 键（54） **下一步**：使用键进行电源管理 **常见下一步**:

* 启动 VM → [`VM 电源管理`](/knowledge-base/zh/automation-api/vm-power-management.md)
* 配置设置 → [`VM 配置`](/knowledge-base/zh/automation-api/vm-configuration.md)
* 高级操作 → [`VM 高级操作`](/knowledge-base/zh/automation-api/vm-advanced-operations.md)

## 本文档适用于

* “如何通过 API 创建 VM”
* “在 VM 设置期间添加磁盘”
* “将 GPU/PCI 设备连接到 VM”
* “使用 cloud-init 创建 VM”
* “理解 VM 与机器键”
* “为新 VM 设置网络接口”
* “基于配方的 VM 部署”
* “批量 VM 创建自动化”
* “以代码形式管理基础设施的 VM 部署”

## 快速参考

### 主要端点

* **创建 VM**: `POST /api/v4/vms`
* **添加磁盘**: `POST /api/v4/machine_drives`
* **添加设备**: `POST /api/v4/machine_devices`
* **添加 NIC**: `POST /api/v4/machine_nics`

### 关键参数

* `name`：VM 标识符（必填）
* `cluster`：目标集群 ID
* `machine`：VM 创建时返回的 Machine ID（用于添加硬件）
* `resource_group`：设备直通的 UUID

### 身份验证

```bash
-H "Authorization: Bearer YOUR_API_KEY"
-H "Content-Type: application/json"
```

### 下一步

VM 创建后 → 电源管理（[`VM 电源管理`](/knowledge-base/zh/automation-api/vm-power-management.md))

## API 快速参考

| 操作     | 方法   | 端点                            | 键类型       | 用途         |
| ------ | ---- | ----------------------------- | --------- | ---------- |
| 创建 VM  | POST | `/api/v4/vms`                 | 返回两者      | 初始创建       |
| 添加磁盘   | POST | `/api/v4/machine_drives`      | Machine 键 | 硬件         |
| 添加设备   | POST | `/api/v4/machine_devices`     | Machine 键 | GPU/PCI 直通 |
| 添加 NIC | POST | `/api/v4/machine_nics`        | Machine 键 | 网络接口       |
| 开机     | POST | `/api/v4/vm_actions`          | VM 键      | 控制         |
| 检查状态   | GET  | `/api/v4/machine_status/{id}` | Machine 键 | 监控         |

## 故障排查索引

* **409 冲突**：VM 名称已存在、已在运行、权限被拒绝
* **400 错误请求**：参数无效、缺少必需字段、JSON 无效
* **507 存储空间不足**：层已满、减小大小、选择其他层
* **403 禁止访问**：API 密钥权限不足、集群访问被拒绝
* **404 未找到**：集群 ID 无效、缺少媒体源、资源组无效
* **422 无法处理的实体**：磁盘接口无效、不支持的媒体类型

## 前提条件

* 具有 VM 管理权限的有效 VergeOS API 凭据
* 了解 VergeOS 概念：集群、vnet、媒体源和资源组
* 具备 REST API 原理和 JSON 格式的基础知识

## 身份验证

所有 VM 创建操作都需要使用以下任一方式进行身份验证：

* **API 密钥**：包含在 `Authorization` 标头中，作为 `Bearer YOUR_API_KEY`
* **基本身份验证**：交互式会话的用户名和密码
* **会话令牌**：用于基于 Web 的集成

```bash
# 使用 API 密钥
curl -H "Authorization: Bearer YOUR_API_KEY" \\
     -H "Content-Type: application/json" \\
     https://your-vergeos.example.com/api/v4/vms
```

## 基础 VM 创建

### POST /api/v4/vms

**说明**：使用指定配置创建新的虚拟机。

**请求参数**:

| 名称                  | 类型  | 必需 | 说明                             |
| ------------------- | --- | -- | ------------------------------ |
| name                | 字符串 | 是  | 唯一的 VM 名称                      |
| description         | 字符串 | 否  | VM 描述                          |
| cluster             | 字符串 | 否  | 目标集群 ID（数字字符串）                 |
| ram                 | 整数  | 否  | RAM（MB，默认值：1024）               |
| cpu\_cores          | 整数  | 否  | CPU 核心数（默认值：1）                 |
| guest\_agent        | 字符串 | 否  | 启用 guest agent（"true"/"false"） |
| console\_pass\_hash | 字符串 | 否  | 控制台密码哈希（未使用时为空字符串）             |
| video               | 字符串 | 否  | 视频适配器类型（virtio、std、cirrus 等）   |
| rtc\_base           | 字符串 | 否  | RTC 基准设置（utc、localtime）        |
| uefi                | 字符串 | 否  | 启用 UEFI 启动（"true"/"false"）     |

**请求体示例**:

```json
{
  "name": "web-server-01",
  "description": "生产 Web 服务器",
  "cluster": "1",
  "ram": 8192,
  "cpu_cores": 4,
  "guest_agent": "true",
  "console_pass_hash": "",
  "video": "virtio",
  "rtc_base": "utc",
  "uefi": "true"
}
```

**响应示例**:

```json
{
  "location": "/v4/vms/42",
  "dbpath": "vms/42",
  "$row": 42,
  "$key": "42",
  "response": {
    "machine": "54"
  }
}
```

**响应字段**:

| 字段               | 类型  | 说明                      |
| ---------------- | --- | ----------------------- |
| location         | 字符串 | 已创建 VM 的 API 端点         |
| dbpath           | 字符串 | VM 记录的数据库路径             |
| $row             | 整数  | 数据库行号                   |
| $key             | 字符串 | VM ID（用于后续 API 调用）      |
| response.machine | 字符串 | Machine ID（用于磁盘、NIC、设备） |

**错误响应**:

* `400 错误请求`：配置参数无效
* `409 冲突`：VM 名称已存在
* `403 禁止访问`：权限不足

{% hint style="success" %}
**VM 键与 Machine 键**

* **VM 键** （例如“42”）：用于 CPU、RAM、控制台等 VM 设置
* **Machine 键** （例如“54”）：用于磁盘、NIC、设备等硬件
* 在 VM 创建响应中可以同时获得这两个键
  {% endhint %}

## 基于配方的 VM 创建

VergeOS 支持使用包含磁盘、网络接口和设备的配方来创建复杂 VM。

### 使用配方配置的完整 VM

```json
{
  "name": "enterprise-vm",
  "description": "企业应用服务器",
  "cluster": "1",
  "cpu_cores": 8,
  "ram": 16384,
  "guest_agent": "true",
  "video": "virtio",
  "rtc_base": "utc",
  "uefi": "true",
  "secure_boot": "true",
  "console_pass_hash": "",
  "cloudinit_datasource": "nocloud",
  "cloudinit_files": [
    {
      "name": "user-data",
      "contents": "#cloud-config\nusers:\n  - name: admin\n    sudo: ALL=(ALL) NOPASSWD:ALL\n    ssh_authorized_keys:\n      - ssh-rsa AAAAB3NzaC1yc2E..."
    },
    {
      "name": "meta-data",
      "contents": "instance-id: enterprise-vm-001\nlocal-hostname: enterprise-vm"
    }
  ]
}
```

## 添加磁盘

必须在 VM 创建后使用 machine drives 端点单独创建磁盘。

### POST /api/v4/machine\_drives

**请求参数**:

| 名称              | 类型  | 必需 | 说明                                    |
| --------------- | --- | -- | ------------------------------------- |
| machine         | 字符串 | 是  | VM 创建时返回的 Machine ID                  |
| name            | 字符串 | 否  | 磁盘名称                                  |
| media           | 字符串 | 否  | 媒体类型（disk、cdrom、import、clone、efidisk） |
| interface       | 字符串 | 否  | 磁盘接口（virtio-scsi、ide、ahci 等）          |
| disksize        | 整数  | 否  | 磁盘大小（字节，用于新磁盘）                        |
| preferred\_tier | 字符串 | 否  | 存储层（1-5）                              |
| media\_source   | 字符串 | 否  | 源媒体 ID（用于 import/clone/cdrom）         |
| show\_pt        | 字符串 | 否  | 覆盖首选层（"true"/"false"）- 覆盖媒体源的默认层      |

### 创建启动磁盘

```json
{
  "machine": "54",
  "name": "OS Drive",
  "media": "disk",
  "interface": "virtio-scsi",
  "disksize": 2199023255552,
  "preferred_tier": "1"
}
```

**响应示例**:

```json
{
  "location": "/v4/machine_drives/54",
  "dbpath": "machine_drives/54",
  "$row": 54,
  "$key": "54"
}
```

### 挂载 CDROM/ISO

```json
{
  "machine": "54",
  "media": "cdrom",
  "interface": "ahci",
  "media_source": "7"
}
```

**响应示例**:

```json
{
  "location": "/v4/machine_drives/55",
  "dbpath": "machine_drives/55",
  "$row": 55,
  "$key": "55"
}
```

### 从媒体源导入

```json
{
  "machine": "54",
  "name": "Ubuntu Server",
  "description": "Ubuntu 22.04 LTS",
  "interface": "virtio-scsi",
  "media": "import",
  "media_source": 123,
  "preferred_tier": "3"
}
```

## 添加设备（GPU、PCI 直通等）

### POST /api/v4/machine\_devices

**说明**：将 GPU、PCI 设备、USB 设备或 TPM 等硬件设备连接到虚拟机。

**请求参数**:

| 名称              | 类型  | 必需 | 说明                |
| --------------- | --- | -- | ----------------- |
| machine         | 字符串 | 是  | Machine ID        |
| resource\_group | 字符串 | 是  | 该设备的资源组 UUID      |
| settings\_args  | 对象  | 否  | 设备特定设置（基本直通时为空对象） |

### PCI 直通 GPU

```json
{
  "machine": "54",
  "resource_group": "1f67f07e-f653-db95-c475-01b8a2ea0ff1",
  "settings_args": {}
}
```

**响应示例**:

```json
{
  "location": "/v4/machine_devices/2",
  "dbpath": "machine_devices/2",
  "$row": 2,
  "$key": "2",
  "response": {
    "uuid": "934e250b-a13c-bd8f-104d-a31995b06eba"
  }
}
```

{% hint style="success" %}
**查找资源组**

该 `resource_group` 参数用于标识要连接的具体硬件设备。使用这些端点查找可用的资源组 UUID：

* `GET /api/v4/resource_groups` - 通用硬件设备（GPU、PCI 设备、USB 等）
* `GET /api/v4/node_nvidia_vgpu_devices` - 专门用于 NVIDIA vGPU 设备
  {% endhint %}

### 查找可用设备

```bash
# 通用硬件设备
curl "https://your-vergeos.example.com/api/v4/resource_groups" \\
  -H "Authorization: Bearer YOUR_API_KEY"

# NVIDIA vGPU 设备
curl "https://your-vergeos.example.com/api/v4/node_nvidia_vgpu_devices" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

## 添加网络接口

### POST /api/v4/machine\_nics

**请求参数**:

| 名称        | 类型  | 必需 | 说明                       |
| --------- | --- | -- | ------------------------ |
| machine   | 字符串 | 是  | Machine ID               |
| vnet      | 字符串 | 是  | 虚拟网络 ID（目标网络的键）          |
| name      | 字符串 | 否  | NIC 名称                   |
| interface | 字符串 | 否  | NIC 接口类型（virtio、e1000 等） |
| enabled   | 布尔值 | 否  | NIC 启用状态                 |

**示例**:

```json
{
  "machine": "54",
  "vnet": "3"
}
```

**响应示例**:

```json
{
  "location": "/v4/machine_nics/78",
  "dbpath": "machine_nics/78",
  "$row": 78,
  "$key": "78"
}
```

{% hint style="info" %}
**虚拟网络键**

该 `vnet` 该参数使用网络的键/ID。例如，vnet “3” 可能是你的外部网络。你可以通过网络 API 端点列出可用网络来查找网络键。
{% endhint %}

## 完整 VM 创建示例

下面是一个创建带有磁盘、设备和网络接口的 VM 的完整工作流：

```bash
# 第 1 步：创建 VM
curl -X POST "https://your-vergeos.example.com/api/v4/vms" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "name": "production-server",
    "description": "生产应用服务器",
    "cluster": "1",
    "ram": 16384,
    "cpu_cores": 8,
    "guest_agent": "true",
    "video": "virtio",
    "uefi": "true"
  }'

# 响应：VM 键 = 42，Machine 键 = 54

# 第 2 步：添加启动磁盘
curl -X POST "https://your-vergeos.example.com/api/v4/machine_drives" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "machine": "54",
    "name": "Boot Drive",
    "media": "disk",
    "interface": "virtio-scsi",
    "disksize": 107374182400,
    "preferred_tier": "1"
  }'

# 第 3 步：添加网络接口
curl -X POST "https://your-vergeos.example.com/api/v4/machine_nics" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "machine": "54",
    "vnet": "3"
  }'

# 第 4 步：添加 GPU（可选）
curl -X POST "https://your-vergeos.example.com/api/v4/machine_devices" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "machine": "54",
    "resource_group": "1f67f07e-f653-db95-c475-01b8a2ea0ff1",
    "settings_args": {}
  }'
```

{% hint style="info" %}
**相关操作**

* **电源管理**：参见 [`VM 电源管理`](/knowledge-base/zh/automation-api/vm-power-management.md) 用于启动/停止 VM
* **配置**：参见 [`VM 配置`](/knowledge-base/zh/automation-api/vm-configuration.md) 用于 CPU/RAM 更改
* **高级操作**：参见 [`VM 高级操作`](/knowledge-base/zh/automation-api/vm-advanced-operations.md) 用于克隆和快照
  {% endhint %}

{% hint style="info" %}
**需要帮助吗？**

如需有关 VM 创建的更多支持：

* 查看 VergeOS 文档门户
* 联系 VergeOS 支持并提供具体的错误信息
* 查看系统日志以获取详细的错误信息
* 查阅 VergeOS 社区论坛
  {% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.verge.io/knowledge-base/zh/automation-api/vm-creation-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
