华为云 通过SDK 创建弹性主机

模块

SDK 下载地址 https://github.com/huaweicloud/huaweicloud-sdk-python

cd  
pip install -r requirements.txt
python3.6  setup.py  install

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#自己测试使用


import sys
import base64
from openstack import connection
from openstack import utils

utils.enable_logging(debug=False, stream=sys.stdout)

# create connection
username = "hequan"
password = "xxxxxxxxxx"
projectId = "xxxxxxxxxxxxxxxxx"           ##我的凭证   项目ID
userDomainId = "xxxxxxxxxxxxxxx"        ##我的凭证   账号ID
auth_url = "https://iam.cn-north-1.myhuaweicloud.com"    ##我的凭证   项目 不同地区 要写不同地址 
conn = connection.Connection(auth_url=auth_url,
                             user_domain_id=userDomainId,
                             project_id=projectId,
                             username=username,
                             password=password)

TIMES = 60
INTERVAL = 10


def availability_zones():
    """
    可用区
    :return:  ['cn-north-1a', 'cn-north-1b', 'cn-north-1c']
    """
    name = []
    azs = conn.compute.availability_zones()
    for az in azs:
        if az.state['available'] == True:
            name.append(az.name)
    return name


def list_router():
    """
    vpc 虚拟私有云
    :return: {'0d2f14a4-6d59-4393-b08f-6f03c2afa8da': 'hequan'}
    """
    n = conn.network.routers()
    routers = {}
    for i in n :
        if i.status == 'ACTIVE' :
            routers[i.id]=i.name
    print(routers)
    return  routers

def list_network():
    """
    子网列表
    :return: {'0d2f14a4-6d59-4393-b08f-6f03c2afa8da': ['77b0107d-25ee-4c5b-a176-3c78ed39742c', '4d4a6559-0f25-426d-a955-38e8236b3ebe']}
    """
    networks={}
    n = conn.network.networks()
    for j in n:
        if j.status == 'ACTIVE' and j.is_shared == False:
            if j.name in  networks.keys():
                networks[j.name]=[j.id,]+ [networks[j.name],]
            else:
                networks[j.name]=j.id
    print(networks)
    return networks


def list_subnet():
    """
    子网  详情
    :return:{'4d4a6559-0f25-426d-a955-38e8236b3ebe': 'hequan-subnet1 192.168.1.0/24', '77b0107d-25ee-4c5b-a176-3c78ed39742c': 'hequan-subnet2 192.168.2.0/24'}
    """
    subnets={}
    n = conn.network.subnets()
    for j in n:
        subnets[j.network_id]=f"{j.name} {j.cidr}"
    print(subnets)
    return subnets

flavors = {
    "s3.large.2":"2*4",        ##通用计算
    "s3.large.4": "2*8",
    "s3.xlarge.2 ":"4*8",
    "c3.large.2":"2*4",         ##通用计算增强型号
    "c3.large.4":"2*8",
    "c3.xlarge.2":"4*8"
}



def list_images():
    """
    镜像 CentOS
    :return:  ID  名字

    """
    images = conn.compute.images()
    i = {}
    for image in images:
        try:
            if image.metadata['__platform']=='CentOS' and  image.metadata['__imagetype']=='gold' and  image.metadata['__support_kvm']=='true'  and \
                image.metadata['virtual_env_type']=='FusionCompute' and image.status == 'ACTIVE' and image.size == 0  and  image.metadata['__isregistered']== 'true':
                i[image.metadata['__os_version']]=image.id
        except Exception as e:
            pass
    print(i)
    return i


def list_security_groups():
    """
    安全组
    :return: {"id":"名字"}
    """
    group = {}
    server_group = conn.network.security_groups()
    for i in server_group:
        group[i.id]=i.name
    print(group)
    return group



def create_servers_one_time():
    """

    :return: openstack.ecs.v1.server_ext.Servers(availability_zone=cn-north-1c, name=test-sdk-for-Linux-userdata, imageRef=04c6329c-ad97-4b0e-be4d-2d8e2dce8427, flavorRef=s3.small.1, vpcid=0d2f14a4-6d59-4393-b08f-6f03c2afa8da, user_data=IyEvYmluL2Jhc2ggDQogZWNobyAncm9vdDpQQHNzV3IwZDEyMycgfCBjaHBhc3N3ZCA7, nics=[{'subnet_id': '4d4a6559-0f25-426d-a955-38e8236b3ebe'}], security_groups=[{'id': '192445e1-ba8a-43d3-ab26-c99741c9d43c'}], root_volume={'volumetype': 'SAS'}, isAutoRename=true, count=1, extendparam={'chargingMode': 'postPaid', 'isAutoRenew': 'true', 'isAutoPay': 'true'}, job_id=8aaf9ede68ff67a801696babd67a1cce)

    """
    user_date_org = "#!/bin/bash \r\n echo 'root:P@ssWr0d123' | chpasswd ;"
    user_data = str(base64.b64encode(user_date_org.encode("utf-8")), "utf-8")

    data = {
        "availability_zone": "cn-north-1a",
        "name": "test-sdk-for-Linux-userdata",
        "imageRef": "04c6329c-ad97-4b0e-be4d-2d8e2dce8427",
        "flavorRef": "t6.large.2",
        "vpcid": "0d2f14a4-6d59-4393-b08f-6f03c2afa8da",
        "user_data": user_data,
        "nics": [
            {
                "subnet_id": "4d4a6559-0f25-426d-a955-38e8236b3ebe"
            }
        ],
        "security_groups": [
            {
                "id": "192445e1-ba8a-43d3-ab26-c99741c9d43c"
            }
        ],
        "root_volume": {
            "volumetype": "SAS"
        },
		# "data_volumes": [
        #     {
        #         "volumetype": "SATA",
        #         "size": 10,
        #         "multiattach": "false",      ## 共享云硬盘标志位,true为共享盘,false为普通云硬盘。
        #         "hw:passthrough": "false"   ##true表示云硬盘的设备类型为SCSI类型,即允许ECS操作系统直接访问底层存储介质。支持SCSI锁命令。    false表示云硬盘的设备类型为VBD (虚拟块存储设备 , Virtual Block Device)类型,即为默认类型,VBD只能支持简单的SCSI读写命令。
        #     }
        # ],
		"isAutoRename": "true",    ## 云服务器名称是否允许重名。默认为True。
        "count": 1,
		"extendparam": {
            "chargingMode": "postPaid",          ## prePaid  包年包月        postPaid  按量付费
            # "periodType": "month",              ## 订购周期  month   year
            # "periodNum": 1,                     ##           1-9   /   1
            "isAutoRenew": "true",        ##是否自动续订。
            "isAutoPay": "true",          ##下单订购后,是否自动从客户的帐户中支付,而不需要客户手动去支付。
        },
    }

    server = conn.ecs.create_server_ext(**data)
    print(server)
    print(server.job_id)
    return server




if __name__ == "__main__":
    pass

参考


https://support.huaweicloud.com/devg-sdk/zh-cn_topic_0070637158.html


https://developer.huaweicloud.com/endpoint?ECS