阿里云通过API 创建ECS主机示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阿里云通过API 创建ECS主机示例相关的知识,希望对你有一定的参考价值。

SDK

aliyun-python-sdk-core-v3==2.9.1
aliyun-python-sdk-ecs==4.10.1

脚本

AccessKeyId = ‘xxxxxxxxxxxxx‘
AccessKeySecret = ‘xxxxxxxxxxxxxxxx‘
City = ‘cn-beijing‘

import time
import re
import logging
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest, DescribeRegionsRequest,     DescribeAvailableResourceRequest, DescribeImagesRequest, DescribeSecurityGroupsRequest, DescribeVpcsRequest,     DescribeVSwitchesRequest,CreateInstanceRequest,AllocatePublicIpAddre***equest,StartInstanceRequest
import json

logger = logging.getLogger(‘test‘)

class AliyunEcsCreate(object):

    def __init__(self, AccessKeyId, AccessKeySecret, City):
        self.AccessKeyId = AccessKeyId
        self.AccessKeySecret = AccessKeySecret
        self.City = City

    def DescribeRegions(self):
        """
        地域
        :return: {‘cn-qingdao‘: ‘华北 1‘}
        """
        regionsclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret)
        regionsreq = DescribeRegionsRequest.DescribeRegionsRequest()

        regionsreq.set_accept_format(‘json‘)
        regionsre = json.loads(regionsclt.do_action_with_exception(regionsreq), encoding=‘utf-8‘)
        regions = {}
        for i in regionsre[‘Regions‘][‘Region‘]:
            regions[i[‘RegionId‘]] = i[‘LocalName‘]
        return regions

    def DescribeAvailableResource(self, InstanceChargeType, region_id, DestinationResource, ZoneId=None):
        """
         可用资源查询接口
        :param region_id:  地域
        :param DestinationResource: 查询的资源类型
        :return:
        """
        resourceclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        resourcereq = DescribeAvailableResourceRequest.DescribeAvailableResourceRequest()
        if DestinationResource == ‘InstanceType‘:
            resourcereq.set_ZoneId(ZoneId)
            resourcereq.set_IoOptimized(‘optimized‘)
        resourcereq.set_InstanceChargeType(InstanceChargeType)
        resourcereq.set_DestinationResource(DestinationResource)
        resourcereq.set_accept_format(‘json‘)
        resourcere = json.loads(resourceclt.do_action_with_exception(resourcereq), encoding=‘utf-8‘)
        return resourcere

    def AvailableZones(self, InstanceChargeType, region_id):
        """
        可用区
        :param region_id:  计费方式  地域
        :return:  [‘cn-huhehaote-a‘, ‘cn-huhehaote-b‘]
        """
        zonesre = self.DescribeAvailableResource(InstanceChargeType, region_id, ‘Zone‘)
        zones = []
        for i in zonesre[‘AvailableZones‘][‘AvailableZone‘]:
            zones.append(i[‘ZoneId‘])
        return zones

    def AvailableInstanceType(self, InstanceChargeType, region_id, ZoneId):
        """
        可用实例规格
        :param region_id: 计费方式 地域    可用区
        :return:     计算型 ecs.c5  商用       入门级 ecs.t5  测试 预发布
        """
        instanceres = self.DescribeAvailableResource(InstanceChargeType, region_id, ‘InstanceType‘, ZoneId)
        instance = []
        for i in instanceres[‘AvailableZones‘][‘AvailableZone‘][0][‘AvailableResources‘][‘AvailableResource‘][0][‘SupportedResources‘][‘SupportedResource‘]:
            if re.match(‘ecs.t5‘, i[‘Value‘]) or re.match(‘ecs.c5‘, i[‘Value‘]):
                instance.append(i[‘Value‘])
        c5 = {‘ecs.c5.large‘: ‘2*4‘, ‘ecs.c5.xlarge‘: ‘4*8‘, ‘ecs.c5.2xlarge‘: ‘8*16‘}
        t5 = {‘ecs.t5-lc2m1.nano‘:‘1*0.5‘,‘ecs.t5-lc1m2.small‘: ‘1*2‘, ‘ecs.t5-c1m2.large‘: ‘2*4‘, ‘ecs.t5-lc1m4.large‘: ‘2*8‘}
        for k in list(c5.keys()):
            if k not in instance:
                del c5[k]

        for k in list(t5.keys()):
            if k not in instance:
                del t5[k]
        return c5, t5

    def DescribeImages(self, region_id):
        """

        :param region_id:  地域
        :return:  镜像列表 {‘centos_6_09_64_20G_alibase_20180326.vhd‘: ‘CentOS  6.9 64位‘,}
        """
        imagesclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        imagesreq = DescribeImagesRequest.DescribeImagesRequest()
        imagesreq.set_ActionType(‘DescribeImages‘)
        imagesreq.set_accept_format(‘json‘)
        imagesreq.set_PageSize(100)
        imagesre = json.loads(imagesclt.do_action_with_exception(imagesreq), encoding=‘utf-8‘)
        images = {}
        for i in imagesre[‘Images‘][‘Image‘]:
            if i[‘Platform‘] == ‘CentOS‘:
                images[i[‘ImageId‘]] = i[‘OSName‘]
        return images

    def DescribeVpcs(self, region_id):
        """
        VPC
        :param region_id:  地域
        :return: {‘vpc-hp33ep5m55q5vdebkjpxk‘: ‘华北5预发布VPC‘, ‘vpc-hp3xfrxc78pgc0rianhge‘: ‘华北5测试‘}
        """
        vpcsclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        vpcsreq = DescribeVpcsRequest.DescribeVpcsRequest()
        vpcsreq.set_action_name(‘DescribeVpcs‘)
        vpcsreq.set_accept_format(‘json‘)
        vpcsreq.set_PageSize(50)
        vpcsre = json.loads(vpcsclt.do_action_with_exception(vpcsreq), encoding=‘utf-8‘)
        vpcs = {}
        for i in vpcsre[‘Vpcs‘][‘Vpc‘]:
            vpcs[i[‘VpcId‘]] = i[‘VpcName‘]
        return vpcs

    def DescribeVSwitches(self, region_id, zone_id, vpc_id):
        """

        :param region_id:  地域
        :param zone_id:   可用区
        :param vpc_id:  vpc
        :return: {‘vsw-hp3ffb8524tt1gqp22utj‘: ‘华北5测试B交换机‘}
        """
        vswitchesclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        vswitchesreq = DescribeVSwitchesRequest.DescribeVSwitchesRequest()
        vswitchesreq.set_action_name(‘DescribeVSwitches‘)
        vswitchesreq.set_VpcId(vpc_id)
        vswitchesreq.set_accept_format(‘json‘)
        vswitchesreq.set_PageSize(50)
        vswitchesreq.set_ZoneId(zone_id)
        vswitchesre = json.loads(vswitchesclt.do_action_with_exception(vswitchesreq), encoding=‘utf-8‘)
        vswitches = {}
        for i in vswitchesre[‘VSwitches‘][‘VSwitch‘]:
            vswitches[i[‘VSwitchId‘]] = i[‘VSwitchName‘]
        return vswitches

    def DescribeSecurityGroups(self,region_id,vpc_id,):
        """
        安全组
        :param region_id:  地域
        :param vpc_id:  vpc
        :return: {‘sg-hp3738k45fqqbfja11fl‘: ‘华北5测试2‘, ‘sg-hp3hzvhrr2gk8skyo3ul‘: ‘华北5测试1‘}
        """
        groupsclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        groupsreq = DescribeSecurityGroupsRequest.DescribeSecurityGroupsRequest()
        groupsreq.set_action_name(‘DescribeSecurityGroups‘)
        groupsreq.set_VpcId(vpc_id)
        groupsreq.set_accept_format(‘json‘)
        groupsreq.set_PageSize(50)
        groupsre = json.loads(groupsclt.do_action_with_exception(groupsreq), encoding=‘utf-8‘)
        groups = {}
        for i in  groupsre[‘SecurityGroups‘][‘SecurityGroup‘]:
            groups[i[‘SecurityGroupId‘]]=i[‘SecurityGroupName‘]
        return groups

    def CreateInstance(self,region_id,ZoneId,ImageId,InstanceType,InstanceName,InstanceChargeType,InternetChargeType,
                       InternetMaxBandwidthOut,HostName,Password,VSwitchId,SecurityGroupId,Size):
        """
        创建 实例
        :param region_id:   地域
        :param ZoneId:  可用区
        :param ImageId: 镜像
        :param InstanceType:  实例模板
        :param InstanceName:  实例名字
        :param InstanceChargeType:  计费方式
        :param InternetChargeType:  网络计费方式
        :param InternetMaxBandwidthOut:  出网带宽
        :param HostName:  主机名字
        :param Password:  密码
        :param VSwitchId: 交换机
        :param SecurityGroupId:  安全组
        :param Size:   数据盘  默认为None  20
        :return: {‘InstanceId‘: ‘i-2ze210z0uiwyadm1m7x6‘}
        """
        createclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        createreq = CreateInstanceRequest.CreateInstanceRequest()
        createreq.set_action_name(‘CreateInstance‘)
        createreq.set_accept_format(‘json‘)
        createreq.set_ZoneId(ZoneId)
        createreq.set_ImageId(ImageId)
        createreq.set_InstanceType(InstanceType)
        createreq.set_InstanceName(InstanceName)
        createreq.set_InstanceChargeType(InstanceChargeType)
        if InstanceChargeType == ‘PrePaid‘:
            createreq.set_Period(‘1‘)
        if InternetChargeType:
            createreq.set_InternetChargeType(InternetChargeType)
            createreq.set_InternetMaxBandwidthOut(InternetMaxBandwidthOut)
        createreq.set_HostName(HostName)
        createreq.set_Password(Password)
        createreq.set_VSwitchId(VSwitchId)
        createreq.set_SecurityGroupId(SecurityGroupId)
        if Size != 0:
            createreq.set_DataDisks([{‘Size‘:Size,‘Category‘:‘cloud_efficiency‘}])

        createre = json.loads(createclt.do_action_with_exception(createreq), encoding=‘utf-8‘)
        return createre

    def AllocatePublicIpAddress(self,region_id,InstanceId):
        """
        绑定外网IP
        :param region_id:  地域
        :param InstanceId: 实例ID
        :return: {‘IpAddress‘: ‘39.106.176.130‘}
        """
        ipclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        ipreq = AllocatePublicIpAddre***equest.AllocatePublicIpAddre***equest()
        ipreq.set_action_name(‘AllocatePublicIpAddress‘)
        ipreq.set_accept_format(‘json‘)
        ipreq.set_InstanceId(InstanceId)
        ipre = json.loads(ipclt.do_action_with_exception(ipreq), encoding=‘utf-8‘)
        return ipre

    def StartInstance(self,region_id,InstanceId):
        """
        启动实例
        :param region_id: 地域
        :param InstanceId:  实例ID
        :return:
        """
        startclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        startreq = StartInstanceRequest.StartInstanceRequest()
        startreq.set_action_name(‘StartInstance‘)
        startreq.set_accept_format(‘json‘)
        startreq.set_InstanceId(InstanceId)
        start = json.loads(startclt.do_action_with_exception(startreq), encoding=‘utf-8‘)
        return start

if __name__ == ‘__main__‘:
    create = AliyunEcsCreate(AccessKeyId, AccessKeySecret, City)
    regions = create.DescribeRegions()
    zones = create.AvailableZones(‘PostPaid‘, ‘cn-beijing‘)
    c5, t5 = create.AvailableInstanceType(‘PostPaid‘, ‘cn-beijing‘, ‘cn-beijing-f‘)
    images = create.DescribeImages(‘cn-beijing‘)
    vpcs= create.DescribeVpcs(‘cn-beijing‘)
    vswitches = create.DescribeVSwitches(‘cn-beijing‘, ‘cn-beijing-f‘,‘vpc-2zetvr99gw5dz5xfeouvo‘)
    groups = create.DescribeSecurityGroups(‘cn-beijing‘,‘vpc-2zetvr99gw5dz5xfeouvo‘)

    print(regions)
    print(zones)
    print(c5,t5)
    print(images)
    print(vpcs)
    print(vswitches)
    print(groups)
    createecs = create.CreateInstance(region_id=‘cn-beijing‘,ZoneId=‘cn-beijing-f‘,ImageId=‘centos_7_04_64_20G_alibase_201701015.vhd‘,
                                      InstanceType=‘ecs.t5-lc2m1.nano‘,InstanceName=‘test.test.com‘,InstanceChargeType=‘PostPaid‘,
                                      InternetChargeType=‘PayByBandwidth‘,InternetMaxBandwidthOut=‘1‘,HostName=‘test.test.com‘,
                                      Password=‘1qaz.2wsx‘,VSwitchId=‘vsw-2ze1c3ty3fj74rr16n1c4‘,SecurityGroupId=‘sg-2zeg2nvydu16ikvppjm7‘,
                                      Size=0)
    time.sleep(20)
    ipaddr = create.AllocatePublicIpAddress(‘cn-beijing‘,createecs[‘InstanceId‘])
    start = create.StartInstance(‘cn-beijing‘,createecs[‘InstanceId‘])

参考官方文档

https://help.aliyun.com/document_detail/25499.html?spm=a2c4e.11153940.blogcont69142.16.3ba53fb4gmW2LU

以上是关于阿里云通过API 创建ECS主机示例的主要内容,如果未能解决你的问题,请参考以下文章

阿里云服务器ECS跟云虚拟主机那个好些?都有啥区别啊?

2018年最新阿里云云主机安装centos从入门到使用视频教程

阿里大牛亲授阿里云主机(ECS)与CentOS7实战

给阿里云ECS主机添加IPV6地址

阿里大牛亲授 阿里云主机(ECS)与CentOS7实战 高清无密

阿里云ECS上APP访问异常或超时