python3.6 批量建立 多臺阿里雲ECS主機 示例
阿新 • • 發佈:2018-11-15
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