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

原文地址:http://blog.51cto.com/hequan/2317341

时间: 2024-10-09 19:40:44

python3.6 批量创建 多台阿里云ECS主机 示例的相关文章

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

注意:阿里云ECS主机多个网站配置,是有先后顺序的: 进入路径:/alidata/server/httpd-2.4.2/conf/vhosts/  注意这个2.4.2是自己的版本不一样,但是找到 server / httpd/ conf /vhosts目录下即可

阿里云ECS主机内核调优

#阿里云内核调优 cat /etc/sysctl.conf vm.swappiness = 0net.ipv4.neigh.default.gc_stale_time=120 # see details in https://help.aliyun.com/knowledge_detail/39428.htmlnet.ipv4.conf.all.rp_filter=0net.ipv4.conf.default.rp_filter=0net.ipv4.conf.default.arp_announ

记录一次在阿里云ECS服务器部署验证RocketMQ的经历

==背景== 购买了3台阿里云ECS服务器,上面部署了RocketMQ,用来作为业务后台与平台之间的数据通讯中间件. 部署倒是异常顺利,不过在本地写程序,测试生产和消费数据的时候,出现了一些问题. 耗费了将近1天的时间,终于解决了,记录一下本次排查的经历. ==环境== Linux:CentOS8(阿里云ECS服务器) RocketMQ:4.6.1 ==集群== 节点数:3个 节点1:broker-a(master) 节点2:broker-a(slave),broker-b(master) 节点

阿里云ECS服务器部署HADOOP集群(五):Pig 安装

本篇将在阿里云ECS服务器部署HADOOP集群(一):Hadoop完全分布式集群环境搭建的基础上搭建. 1 环境介绍 一台阿里云ECS服务器:master 操作系统:CentOS 7.3 Hadoop:hadoop-2.7.3.tar.gz Java: jdk-8u77-linux-x64.tar.gz Pig: pig-0.17.0.tar.gz 2 Pig 下载 下载 pig-0.17.0.tar.gz 并在合适的位置解压缩,笔者这里解压缩的路径为: /usr/local 将解压得到的目录改

阿里云ECS服务器部署HADOOP集群(四):Hive本地模式的安装

本篇将在阿里云ECS服务器部署HADOOP集群(一):Hadoop完全分布式集群环境搭建的基础上搭建. 本地模式需要采用MySQL数据库存储数据. 1 环境介绍 一台阿里云ECS服务器:master 操作系统:CentOS 7.3 Hadoop:hadoop-2.7.3.tar.gz Java: jdk-8u77-linux-x64.tar.gz Hive:apache-hive-2.3.6-bin.tar.gz Mysql: Mysql 5.7 MySQL Connector-J:mysql-

阿里云ECS服务器部署HADOOP集群(七):Sqoop 安装

本篇将在 阿里云ECS服务器部署HADOOP集群(一):Hadoop完全分布式集群环境搭建 阿里云ECS服务器部署HADOOP集群(二):HBase完全分布式集群搭建(使用外置ZooKeeper) 阿里云ECS服务器部署HADOOP集群(三):ZooKeeper 完全分布式集群搭建 阿里云ECS服务器部署HADOOP集群(四):Hive本地模式的安装 的基础上搭建. 1 环境介绍 一台阿里云ECS服务器:master 操作系统:CentOS 7.3 Hadoop:hadoop-2.7.3.tar

阿里云ECS服务器部署HADOOP集群(六):Flume 安装

本篇将在阿里云ECS服务器部署HADOOP集群(一):Hadoop完全分布式集群环境搭建的基础上搭建. 1 环境介绍 一台阿里云ECS服务器:master 操作系统:CentOS 7.3 Hadoop:hadoop-2.7.3.tar.gz Java: jdk-8u77-linux-x64.tar.gz Flume:apache-flume-1.8.0-bin.tar.gz 2 Flume 下载 下载 apache-flume-1.8.0-bin.tar.gz 并在合适的位置解压缩,笔者这里解压

为阿里云ECS(Windows 2012)创建IPv6隧道地址

云友"学渣王 "在帖子里提到需要为阿里云ECS配置IP6地址,根据网上的一些信息,写此例.  如果要求是FQDN地址,请登录到您的域名控制面板,设置一条AAAA记录到新设置的IPv6隧道地址.  在阿里云的将域名解析到IPv6地址,操作方法请参考:https://help.aliyun.com/knowledge_detail/6555875.html  环境:ECS"经典网络"类型(网友"ifaceparty"提醒:如果是"专有网络&

阿里云ecs自动创建快照教程

最近在一个博客联盟的微信群里面看到经常有朋友问阿里云的ecs服务器怎么设置自动创建快照,也不知道最近是怎么了,看到问这个问题的朋友有有四五个左右了,今天就特意到博客里来费大家分享设置自动创建快照的方法. 首先进入正题,我们登录阿里云控制台,然后在控制台的点击ecs服务器,在点击需要设置自动创建快照的服务器,然后在界面上点击本实例磁盘,在右边就能看到设置自动快照策略的按钮了.在快照设置界面上我们可以给快照取个名字,然后在快照的创建时间和保留天数就可以了. 总结:进入到ecs服务器控制台,然后点击需