python3.6 批量创建 多台阿里云ECS主机 示例

Posted

tags:

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

RunInstances

介绍

http://blog.51cto.com/hequan/2174407
上一篇是创建单台,如果想创建多台,需要for循环,比较麻烦,还容易被api限流。

利用RunInstances 可以批量创建多台。

调用该接口时,您需要注意:

单次最多能创建100台实例。
您可以指定参数AutoReleaseTime设置实例自动释放时间。
创建成功后会返回实例ID列表,您可以通过API DescribeInstances查询新建实例状态。
创建实例前,您需要确保您已经有可用的安全组。更多详情,请参阅CreateSecurityGroup。
创建实例时,默认自动启动实例,直到实例状态变成运行中(Running)。
创建专有网络VPC类型实例前,您需要预先在相应的阿里云地域 创建 VPC。
与CreateInstance相比,通过RunInstances创建的实例如果参数InternetMaxBandwidthOut的值大于0,则自动为实例分配公网IP。
提交创建任务后,参数不合法或者库存不足的情况下会报错,具体的报错原因参阅错误码。

SDK

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

方法

主要是 def RunInstances()
import re
import os
import configparser
import logging
import json
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest, DescribeRegionsRequest,     DescribeAvailableResourceRequest, DescribeImagesRequest, DescribeSecurityGroupsRequest, DescribeVpcsRequest,     DescribeVSwitchesRequest, CreateInstanceRequest, AllocatePublicIpAddre***equest, StartInstanceRequest,     RunInstancesRequest

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 ZoneId:
        :param InstanceChargeType:
        :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 InstanceChargeType: 计费方式
        :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 ZoneId:
        :param InstanceChargeType:
        :param region_id: 计费方式 地域    可用区
        :return:    
        """
        instanceres = self.DescribeAvailableResource(InstanceChargeType, region_id, ‘InstanceType‘, ZoneId)
        instance = []
        instance_list = instanceres[‘AvailableZones‘][‘AvailableZone‘][0][‘AvailableResources‘][‘AvailableResource‘][0][
            ‘SupportedResources‘][‘SupportedResource‘]

        return instance_list

    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 = {}
        ubuntu16 = {
            ‘cn-beijing‘: ‘m-2ze6tsxqsldo4qkvjb3u‘,
            ‘cn-zhangjiakou‘: ‘m-8vba9qdqeeca3zpm2sc8‘,
        }

        for i in imagesre[‘Images‘][‘Image‘]:
            if i[‘Platform‘] == ‘CentOS‘:
                images[i[‘ImageId‘]] = i[‘OSName‘]
            if i[‘Platform‘] == ‘Ubuntu‘:
                images[i[‘ImageId‘]] = i[‘OSName‘]
            if i[‘Platform‘] == ‘Windows Server 2008‘:
                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, HostName,
                       Password, VSwitchId, SecurityGroupId, SystemDiskSize, Size, Description):
        """
        创建 实例

        :param region_id:   地域
        :param ZoneId:  可用区
        :param ImageId: 镜像
        :param InstanceType:  实例模板
        :param InstanceName:  实例名字
        :param InstanceChargeType:  实例的付费方式 ,PrePaid PostPaid
        # :param InternetChargeType:  网络计费方式  PayByBandwidth:按固定带宽计费  PayByTraffic:按使用流量计费
        # :param InternetMaxBandwidthOut:  出网带宽
        :param HostName:  主机名字
        :param Password:  密码
        :param VSwitchId: 交换机
        :param SecurityGroupId:  安全组
        :param SystemDiskSize:  系统盘  默认40
        :param Size:   数据盘
        :param Description:   描述
        :return: {‘InstanceId‘: ‘i-2ze210z0uiwyadm1m7x6‘}
        """

        createclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id, timeout=30)
        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)
        if InstanceChargeType == ‘PrePaid‘:
            createreq.set_Period(‘1‘)
        createreq.set_InstanceChargeType(InstanceChargeType)
        createreq.set_InternetChargeType(‘PayByBandwidth‘)
        # if InternetChargeType:
        #     createreq.set_InternetMaxBandwidthOut(InternetMaxBandwidthOut)
        createreq.set_HostName(HostName)
        createreq.set_Password(Password)
        createreq.set_AutoRenew(‘True‘)
        createreq.set_AutoRenewPeriod(‘1‘)
        createreq.set_VSwitchId(VSwitchId)
        createreq.set_SecurityGroupId(SecurityGroupId)
        createreq.set_SystemDiskSize(SystemDiskSize)
        createreq.set_Description(Description)
        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 RunInstances(self, region_id, ZoneId, ImageId, InstanceType, InstanceName, InstanceChargeType, HostName,
                     Password, VSwitchId, SecurityGroupId, SystemDiskSize, Size, Description, Amount):
        """
        一次创建多台 实例

        :param region_id:   地域
        :param ZoneId:  可用区
        :param ImageId: 镜像
        :param InstanceType:  实例模板
        :param InstanceName:  实例名字
        :param InstanceChargeType:  实例的付费方式 ,PrePaid PostPaid
        # :param InternetChargeType:  网络计费方式  PayByBandwidth:按固定带宽计费  PayByTraffic:按使用流量计费
        # :param InternetMaxBandwidthOut:  出网带宽
        :param HostName:  主机名字
        :param Password:  密码
        :param VSwitchId: 交换机
        :param SecurityGroupId:  安全组
        :param SystemDiskSize:  系统盘  默认40
        :param Size:   数据盘
        :param Description:   描述
        :param Amount:   数量
        :return: {‘InstanceId‘: ‘i-2ze210z0uiwyadm1m7x6‘}
        """

        createclt = client.AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id, timeout=30)
        createreq = RunInstancesRequest.RunInstancesRequest()
        createreq.set_action_name(‘RunInstances‘)
        createreq.set_accept_format(‘json‘)
        createreq.set_ZoneId(ZoneId)
        createreq.set_ImageId(ImageId)
        createreq.set_InstanceType(InstanceType)
        createreq.set_InstanceName(InstanceName)
        if InstanceChargeType == ‘PrePaid‘:
            createreq.set_Period(‘1‘)
        createreq.set_InstanceChargeType(InstanceChargeType)
        createreq.set_InternetChargeType(‘PayByBandwidth‘)
        # if InternetChargeType:
        #     createreq.set_InternetMaxBandwidthOut(InternetMaxBandwidthOut)
        createreq.set_HostName(HostName)
        createreq.set_Password(Password)
        createreq.set_AutoRenew(‘True‘)
        createreq.set_VSwitchId(VSwitchId)
        createreq.set_SecurityGroupId(SecurityGroupId)
        createreq.set_SystemDiskSize(SystemDiskSize)
        createreq.set_Description(Description)
        if Size != 0:
            createreq.set_DataDisks([{‘Size‘: Size, ‘Category‘: ‘cloud_efficiency‘}])
        createreq.set_Amount(Amount)
        createreq.set_UniqueSuffix(‘true‘)
        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‘: ‘‘}
        """
        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__‘:
     c = create.RunInstances(传参)
     print(c)

参考

https://help.aliyun.com/document_detail/63440.html?spm=a2c4g.11186623.6.873.7e472386BkvcZq

以上是关于python3.6 批量创建 多台阿里云ECS主机 示例的主要内容,如果未能解决你的问题,请参考以下文章

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

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

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

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

阿里云ECS主机多个网站配置,是有先后顺序的

阿里云CentOS部署小笔记