怎么用代码创建云主机?

HCRM技术_小炮 云主机 2026-02-01 28 1

1.AWS (Amazon EC2) - Python (boto3)

import boto3
def create_ec2_instance():
    ec2 = boto3.resource('ec2', 
                         region_name='us-east-1',
                         aws_access_key_id='YOUR_KEY',
                         aws_secret_access_key='YOUR_SECRET')
    
    # 创建实例
    instances = ec2.create_instances(
        ImageId='ami-0c55b159cbfafe1f0',  # Amazon Linux 2 AMI
        MinCount=1,
        MaxCount=1,
        InstanceType='t2.micro',
        KeyName='your-key-pair',
        SecurityGroupIds=['sg-xxxxxxxx'],
        SubnetId='subnet-xxxxxxxx',
        TagSpecifications=[
            {
                'ResourceType': 'instance',
                'Tags': [
                    {'Key': 'Name', 'Value': 'MyServer'},
                ]
            }
        ]
    )
    
    print(f"实例ID: {instances[0].id}")
    return instances[0].id

2.Azure - Python SDK

from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
import time
def create_azure_vm():
    subscription_id = 'YOUR_SUBSCRIPTION_ID'
    resource_group = 'myResourceGroup'
    location = 'eastus'
    
    credential = DefaultAzureCredential()
    
    # 1. 创建网络接口
    network_client = NetworkManagementClient(credential, subscription_id)
    
    # 创建虚拟网络
    vnet = network_client.virtual_networks.begin_create_or_update(
        resource_group,
        'myVNet',
        {
            'location': location,
            'address_space': {'address_prefixes': ['10.0.0.0/16']}
        }
    ).result()
    
    # 创建子网
    subnet = network_client.subnets.begin_create_or_update(
        resource_group,
        'myVNet',
        'mySubnet',
        {'address_prefix': '10.0.0.0/24'}
    ).result()
    
    # 创建公共IP
    public_ip = network_client.public_ip_addresses.begin_create_or_update(
        resource_group,
        'myPublicIP',
        {
            'location': location,
            'sku': {'name': 'Standard'},
            'public_ip_allocation_method': 'Static',
            'public_ip_address_version': 'IPV4'
        }
    ).result()
    
    # 2. 创建VM
    compute_client = ComputeManagementClient(credential, subscription_id)
    
    vm_parameters = {
        'location': location,
        'hardware_profile': {
            'vm_size': 'Standard_B1s'
        },
        'storage_profile': {
            'image_reference': {
                'publisher': 'Canonical',
                'offer': 'UbuntuServer',
                'sku': '18.04-LTS',
                'version': 'latest'
            },
            'os_disk': {
                'create_option': 'FromImage',
                'managed_disk': {'storage_account_type': 'Standard_LRS'}
            }
        },
        'os_profile': {
            'computer_name': 'myvm',
            'admin_username': 'azureuser',
            'admin_password': 'Password123!'
        },
        'network_profile': {
            'network_interfaces': [{
                'id': '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/networkInterfaces/myNic'.format(
                    subscription_id, resource_group),
                'properties': {'primary': True}
            }]
        }
    }
    
    vm_poller = compute_client.virtual_machines.begin_create_or_update(
        resource_group,
        'myVM',
        vm_parameters
    )
    vm = vm_poller.result()
    
    print(f"VM创建成功: {vm.name}")

3.Google Cloud Platform - Python

from google.cloud import compute_v1
def create_gcp_instance(project_id, zone, instance_name):
    instance_client = compute_v1.InstancesClient()
    
    # 配置实例
    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/n1-standard-1"
    
    # 配置磁盘
    disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = (
        "projects/debian-cloud/global/images/family/debian-11"
    )
    initialize_params.disk_size_gb = 20
    disk.initialize_params = initialize_params
    disk.boot = True
    instance.disks = [disk]
    
    # 配置网络
    network_interface = compute_v1.NetworkInterface()
    network_interface.name = "global/networks/default"
    
    access_config = compute_v1.AccessConfig()
    access_config.name = "External NAT"
    access_config.type_ = "ONE_TO_ONE_NAT"
    network_interface.access_configs = [access_config]
    
    instance.network_interfaces = [network_interface]
    
    # 创建实例
    operation = instance_client.insert(
        project=project_id,
        zone=zone,
        instance_resource=instance
    )
    
    print(f"正在创建实例 {instance_name}...")
    operation.result()  # 等待操作完成
    
    print(f"实例 {instance_name} 创建完成")
    return instance_name

4.使用Terraform(基础设施即代码)

main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}
provider "aws" {
  region = "us-east-1"
}
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  tags = {
    Name = "ExampleInstance"
  }
}
output "instance_id" {
  value = aws_instance.example.id
}
output "public_ip" {
  value = aws_instance.example.public_ip
}
执行命令
terraform init
terraform plan
terraform apply

5.使用Ansible(配置管理)

create_vm.yml
 (YAML下接)

- name: Create EC2 instance
  hosts: localhost
  connection: local
  gather_facts: false
  
  vars:
    region: us-east-1
    instance_type: t2.micro
    ami: ami-0c55b159cbfafe1f0
    key_name: my-key-pair
    security_group: default
    
  tasks:
    - name: Create EC2 instance
      amazon.aws.ec2_instance:
        name: "web-server"
        key_name: "{{ key_name }}"
        instance_type: "{{ instance_type }}"
        security_group: "{{ security_group }}"
        network:
          assign_public_ip: true
        image_id: "{{ ami }}"
        region: "{{ region }}"
        tags:
          Environment: Production
          Application: WebServer
      register: ec2
      
    - name: Print instance info
      debug:
        msg: "Instance created: {{ ec2.instance_ids[0] }}"

6.使用OpenStack SDK(私有云)

import openstack
def create_openstack_instance():
    conn = openstack.connect(
        auth_url='http://controller:5000/v3',
        project_name='admin',
        username='admin',
        password='secret',
        user_domain_name='Default',
        project_domain_name='Default'
    )
    
    # 查找镜像
    image = conn.compute.find_image('cirros-0.5.2')
    
    # 查找flavor
    flavor = conn.compute.find_flavor('m1.tiny')
    
    # 查找网络
    network = conn.network.find_network('private')
    
    # 创建实例
    server = conn.compute.create_server(
        name='test-vm',
        image_id=image.id,
        flavor_id=flavor.id,
        networks=[{"uuid": network.id}],
        key_name='my-keypair'
    )
    
    # 等待实例激活
    server = conn.compute.wait_for_server(server)
    
    print(f"实例创建成功: {server.name}, IP: {server.access_ipv4}")

通用建议:

1、环境变量管理敏感信息

import os
AWS_ACCESS_KEY = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')

2、错误处理

try:
    instance = create_instance()
except Exception as e:
    print(f"创建失败: {str(e)}")
    # 清理资源

3、最佳实践

- 使用IAM角色而非硬编码密钥

- 添加标签便于管理

- 配置监控和告警

- 定期备份重要数据

根据你的具体需求(公有云/私有云、特定平台、自动化程度),选择最适合的方案,对于生产环境,建议使用Terraform或Ansible进行基础设施即代码管理。

文章摘自:https://idc.huochengrm.cn/zj/23369.html

评论

精彩评论
  • 2026-05-01 09:24:36

    这些示例展示了如何在多个云平台和私有云环境中创建实例,使用不同的编程语言和工具,选择合适的工具取决于具体需求、自动化程度和安全性要求。