def create_instance(self, regionid, imageid, instancetype, securitygroupid, instancename, vswitchid, datadisk1size, datadisk1category): """ 创建机器 --- :return: """ # 设置参数 request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.add_query_param('RegionId', regionid) request.add_query_param('ImageId', imageid) request.add_query_param('SystemDisk.Category', 'cloud_efficiency') # request.add_query_param('ZoneId', 'cn-beijing-c') # follow vswitch request.add_query_param('InstanceType', instancetype) request.add_query_param('SecurityGroupId', securitygroupid) request.add_query_param('InstanceName', instancename) request.add_query_param('InternetChargeType', 'PayByTraffic') request.add_query_param('AutoRenew', True) request.add_query_param('AutoRenewPeriod', 1) request.add_query_param('InternetMaxBandwidthIn', 100) request.add_query_param('InternetMaxBandwidthOut', 50) request.add_query_param('Password', '8ql6,yhY') request.add_query_param('SystemDisk.Size', 40) request.add_query_param('DataDisk.1.Size', datadisk1size) request.add_query_param('DataDisk.1.Category', datadisk1category) request.add_query_param('VSwitchId', vswitchid) request.add_query_param('Period', 1) request.add_query_param('InstanceChargeType', 'PrePaid') # TODO 发起请求 创建机器 先注释掉 response = self.cli.do_action_with_exception(request) return response
def create(self): request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId(ctx.node.properties['image_id']) request.set_InstanceType(ctx.node.properties['instance_type']) if self._VSwitchid: request.set_VSwitchId(self._VSwitchid) # todo: SecurityGroupId, not support multi when create # process in relation? if len(self._security_group_ids) > 0: request.set_SecurityGroupId(self._security_group_ids[0]) if 'name' in ctx.node.properties: request.set_InstanceName(ctx.node.properties['name']) # other properties in parameters if 'parameters' in ctx.node.properties: for key, value in ctx.node.properties['parameters'].items(): set_function = getattr( request, 'set_' + key.replace('.', ''), None) if set_function: set_function(value) instance = self.execute(request, raise_on_falsy=True) # Note: it is unicode string, such as u'i-25b2erpyd' # it will has error in ecs sdk list params: [u'i-25b2erpyd'] # so encode as non-unicode, utf-8 or ansi is ok: self.resource_id = instance['InstanceId'].encode('utf-8') return True
def __createInstance(self): request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId(self.__imageId) request.set_InstanceType(self.__InstanceType) request.set_SecurityGroupId(self.__SecurityGroupId) request.set_InstanceName(self.__InstanceName) request.set_InternetChargeType(self.__InternetChargeType) request.set_InternetMaxBandwidthOut(self.__InternetMaxBandwidthOut) request.set_HostName(self.__HostName) request.set_Password(self.__Password) request.set_SystemDiskCategory(self.__SystemDiskCategory) request.set_InstanceChargeType(self.__InstanceChargeType) request.set_IoOptimized(self.__IoOptimized) request.set_ZoneId(self.__ZoneId) request.set_accept_format(u'json') try: result = self.__client.do_action(request) result_data = json.loads(result) except Exception as e: print "exception arised " print e return None if result_data.has_key(u'InstanceId'): print 'createInstance successful with InstanceId %s' % result_data[u'InstanceId'] return result_data[u'InstanceId'] else: print 'createInstance failed ' print result_data return None
def prepare_instance_create_request(self, zone, instance): c = instance.config request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.add_query_param('RegionId', self.region) for k, v in c.items(): request.add_query_param(k, v) check_system_disk_categories(zone, instance.is_io_optimized, instance.system_disk.category) request.add_query_param('SystemDisk.Category', instance.system_disk.category) request.add_query_param('SystemDisk.Size', instance.system_disk.size) index = 1 for disk in instance.data_disks: check_data_disk_categories(zone, instance.is_io_optimized, disk.category) request.add_query_param('DataDisk.%d.Category' % index, disk.category) request.add_query_param('DataDisk.%d.Size' % index, disk.size) index += 1 index = 1 for tag in instance.tags: request.add_query_param('Tag.%d.Key' % index, tag.key) request.add_query_param('Tag.%d.Value' % index, tag.value) index += 1 return request
def createInstance(self, instance_type='ecs.n1.tiny', image_id = 'ubuntu1404_64_40G_cloudinit_20160727.raw'): req = CreateInstanceRequest.CreateInstanceRequest() req.set_accept_format('json') req.set_InstanceType(instance_type) req.set_ImageId(image_id) req.set_SystemDiskCategory('cloud_efficiency') res = self.client.do_action(req) return json.loads(res)
def create_ecs(self, **kwargs): """ :return: ECS创建实例ID """ request = CreateInstanceRequest.CreateInstanceRequest() for k, v in kwargs.items(): request.add_query_param(k, v) result = self.client.do_action(request) return result
def __createSingleInstance(self, build_spec): request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.set_InstanceName(build_spec['instance_name']) request.set_InstanceType(build_spec['instance_type']) request.set_SecurityGroupId(build_spec['SecurityGroupId']) request.set_ImageId(build_spec['image_id']) result = self.__clt.do_action(request) return 'Code' not in json.loads(result)
def CreateInstance(self): request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.set_ImageId('centos_7_3_64_40G_base_20170322.vhd') request.set_Password('cnp200@HW') request.set_InstanceType('ecs.xn4.small') result = self.client.do_action_with_exception(request) self.instance_id = result.get('InstanceId') return result
def createECS(self, zoneId, imageId, instanceType, vSwitchId, securityGroupId, internetChargeType, instanceChargeType): request = CreateInstanceRequest.CreateInstanceRequest() request.set_ZoneId(zoneId) request.set_ImageId(imageId) request.set_InstanceType(instanceType) request.set_SecurityGroupId(securityGroupId) request.set_InternetChargeType(internetChargeType) request.set_InstanceChargeType(instanceChargeType) request.set_SystemDiskCategory()
def create_instance(client, image_id, security_group_id): mylogger.info("trying to create instance...", ) request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format("JSON") request.set_ImageId(image_id) request.set_InstanceName('SdkIntegrationTestInstance' + str(int(time.time()))) request.set_SecurityGroupId(security_group_id) request.set_InstanceType('ecs.t1.small') content = client.do_action_with_exception(request) response = json.loads(content) mylogger.info("success") return response.get('InstanceId')
def create_instance(): req = CreateInstanceRequest.CreateInstanceRequest() req.set_accept_format('json') req.add_query_param('RegionId', region_id) req.add_query_param('ImageId', image_id) req.add_query_param('InstanceType', 'ecs.t5-lc2m1.nano') req.add_query_param('SecurityGroupId', '[security_group_id]') req.add_query_param('InstanceName', '[instance_name]') req.add_query_param('InternetMaxBandwidthIn', '50') req.add_query_param('InternetMaxBandwidthOut', '50') req.add_query_param('VSwitchId', '[vswitch_id]') req.add_query_param('SystemDisk.Size', '20') req.add_query_param('KeyPairName', '[key_pair_name]') status, body = request_cli(req)
def create_instance(self, name, index, instance_type='ecs.c5.large'): # 2cpu 4 g ecs.c5.large 4c9g ecs.c5.xlarge """未完成接口,通过阿里弹性伸缩api实现自动扩容""" request = CreateInstanceRequest.CreateInstanceRequest() request.set_InstanceName('{}_{}_{}'.format(name, day(), index)) image = self.get_image(name='{}_{}'.format(name, day()))['Images']['Image'] if not image: raise AttributeError('the image is not exist') image_id = image[0]['Image_id'] request.set_ImageId(image_id) request.set_InstanceChargeType('PayByTraffic') # 默认 PayByTraffic request.set_InternetMaxBandwidthIn(100) # 默认 100 request.set_InstanceType(instance_type) request.set_SecurityGroupId('sg-2319o94a4') # 安全组id request.set_ZoneId()
def createInstance(clt): request = CreateInstanceRequest.CreateInstanceRequest() f = open("./config/createconf.yaml") config = yaml.load(f) request.set_ImageId(config['ImageId']) request.set_SecurityGroupId(config['SecurityGroupId']) request.set_HostName(config['HostName']) request.set_Password(config['Password']) request.set_InstanceType(config['InstanceType']) request.set_InternetMaxBandwidthOut(config['InternetMaxBandwidthOut']) request.set_accept_format('json') result = clt.do_action(request) print "createInstance=="+result return json.loads(result);
def create_instance(config): click.echo(click.style("正在创建实例 ...", fg="green")) client = config.create_api_client() req = CreateInstanceRequest.CreateInstanceRequest() create_params = config.get('CreateInstanceParams') if create_params: for param_name, param_value in create_params.items(): setter = getattr(req, 'set_' + param_name) setter(param_value) result = do_action(client, req) instance_id = result['InstanceId'] config.set('InstanceId', instance_id) config.save() return instance_id
def main(): # 创建 request,并设置参数 request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId(image_id) request.set_InstanceType(instance_type) request.set_SecurityGroupId(security_group_id) request.set_VSwitchId(vswitch_id) request.set_InstanceName(instance_name) request.set_KeyPairName(key_pair_name) request.set_InstanceChargeType(instance_charge_type) # 获取授权信息 client = auth.auth() # 发起 API 请求并打印返回 response = client.do_action_with_exception(request) ret = response.decode('utf-8') print(ret)
def create_vm(name, region, zone, flavor, image, secur_group, **kwargs): client = create_acs_client(region) request = CreateInstanceRequest.CreateInstanceRequest() request.add_query_param('RegionId', region) request.set_ZoneId(zone) request.set_ImageId(image) request.set_InstanceName(name) request.set_SecurityGroupId(secur_group) request.set_InstanceType(flavor) for k, v in kwargs.items(): request.add_query_param(k, v) # request.set_ClientToken("<uuid>") response = client.do_action_with_exception(request) log.debug(response) r = json.loads(response.decode()) return r
def create_instance(zone_id,accesskey_id,accesskey_secret,region_id,image_ID): clt = client.AcsClient(accesskey_id, accesskey_secret, region_id) request=CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.set_ZoneId(zone_id) request.set_ImageId(image_ID) describe_instance_type(accesskey_id,accesskey_secret,region_id) intance_type=raw_input("Please select ECS instance type:") request.set_InstanceType(intance_type) instance_name=raw_input("Please input ECS instance name:") instance_description=raw_input("Please input ECS instance description:") print("Please seelction instance pay charge type:") instance_charge=raw_input("PrePaid/PostPaid:") if instance_charge not in ['PrePaid','PostPaid']: print("Instance pay charge type is wrong! "+instance_charge) instance_charge=raw_input("Please input correct pay charge type: PrePaid or PostPaid") elif instance_charge == "PrePaid": request.set_Period("1") sys_hdd_size = raw_input("Please input the system driver size,default is 400G:") print("Do you want to add a DATA DISK?") disk_choice = raw_input("y/n:") if disk_choice in ['y', 'Y']: data_hdd_size = raw_input("Please input the data driver size,default is 400G:") request.set_InstanceName(instance_name) request.set_Description(instance_description) request.set_InternetChargeType('PayByTraffic') request.set_InternetMaxBandwidthOut('100') request.set_InstanceChargeType(instance_charge) request.set_SystemDiskCategory('cloud_efficiency') request.set_SystemDiskSize(sys_hdd_size) request.set_DataDisks(({'DataDisk': '1'}, {'Size': data_hdd_size}, {'Category': 'cloud_efficiency'})) vpc_id=describe_switch(accesskey_id, accesskey_secret, region_id) switch_id=raw_input("Please select the vSwitch_ID:") request.set_VSwitchId(switch_id) describe_sg(vpc_id,accesskey_id,accesskey_secret,region_id) sg_id=raw_input("Please select ECS's safe group:") request.set_SecurityGroupId(sg_id) result = clt.do_action(request) print result js_str=json.loads(result) instance_id=js_str["InstanceId"] return instance_id
def create_server(self,servername, imageid , securitygroupid ,password , flavor, period ,vswitchid ,hostname,diskcatalog,disksize ,bandsize, useoutip =False, instancechargetype = 'PrePaid'): client = AcsClient(access_key_id, access_key_secret,region_id) request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId(imageid) request.set_InstanceName(servername) request.set_SecurityGroupId(securitygroupid) request.set_InstanceType(flavor) request.set_Password(password) request.set_VSwitchId(vswitchid) request.set_HostName(hostname) request.set_Period(period) # request.set_InstanceType() request.set_SystemDiskSize(disksize) request.set_SystemDiskCategory(diskcatalog) # 是否自动续费 request.set_AutoRenew(True) # 自动续费1个月 request.set_AutoRenewPeriod(1) request.set_InternetMaxBandwidthOut(bandsize) request.set_InstanceChargeType(instancechargetype) response = client.do_action_with_exception(request) json_result = json.loads(response) serverid = json_result['InstanceId'] i = 0 while i < 600: serverstatus = self.get_server_status_by_serverid(serverid) if serverstatus['status'] == 'Running': break if serverstatus['status'] == 'Stopped': break time.sleep(1) i = i + 1 if i == 600: raise Exception('create instance timeout') if useoutip: print ("xxxxxxxxxx") self.allocate_public_ip(serverid) time.sleep(2) #默认按照流量 # self.modify_public_network(serverid, 'PayByTraffic') return self.get_server_status_by_serverid(serverid)
def create_instance(self, authentication="publickey"): request = CreateInstanceRequest.CreateInstanceRequest() key_list = [ "InstanceChargeType", "ImageId", "InstanceType", "InternetChargeType", "SecurityGroupId", "VSwitchId", "SystemDiskCategory", "HostName", "InstanceName", "InternetMaxBandwidthOut", "InternetMaxBandwidthIn", "RegionId", "ZoneId" ] self.vm_params.setdefault("InstanceChargeType", "PostPaid") self.vm_params.setdefault("InternetChargeType", "PayByTraffic") self.vm_params.setdefault("SystemDiskCategory", "cloud_efficiency") self.vm_params.setdefault("InternetMaxBandwidthIn", "5") self.vm_params.setdefault("InternetMaxBandwidthOut", "5") if authentication == "publickey": key_list.append("KeyPairName") elif authentication == "password": key_list.append("Password") request = self._add_params(request, key_list, self.vm_params) return self._send_request(request)
def create_instances(self, image, instance_name, security_group_id, instance_type): request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId(image) request.set_InstanceName(instance_name) request.set_SecurityGroupId(security_group_id) request.set_InstanceType(instance_type) # request.set_ClientToken() request.set_protocol_type("https") request.set_accept_format('json') # 发起API请求并显示返回值 try: response = self.client.do_action_with_exception(request) print(str(response, encoding='utf-8')) # 服务端错误信息打印 except ServerException as e: print(e) # sdk端错误信息打印 except ClientException as e: print(e)
def create_instance(client): req = CreateInstanceRequest.CreateInstanceRequest() req.set_ZoneId(ZONE_ID) req.set_SecurityGroupId(SECURITY_GROUP_ID) req.set_ImageId(IMAGE_ID) req.set_VSwitchId(V_SWITCH_ID) req.set_InstanceType(INSTANCE_TYPE) req.set_IoOptimized(IO_OPTIMIZED) req.set_SystemDiskCategory(SYSTEM_DISK_CATEGORY) req.set_SystemDiskSize(SYSTEM_DISK_SIZE) req.set_InternetChargeType('PayByTraffic') req.set_InternetMaxBandwidthIn(UPLOAD_BAND_WIDTH) req.set_InternetMaxBandwidthOut(DOWNLOAD_BAND_WIDTH) req.set_SpotStrategy('SpotWithPriceLimit') req.set_SpotPriceLimit(STOP_PRICE_LIMIT) req.set_accept_format('json') return loads(client.do_action(req))
def create(*, instance_name: str, instance_type: str, image_id: str, sgid: str, internet_charge_type: ICT = InternetChargeType.PayByTraffic, host_name: str = '', password: str = '', key_pair_name: str = '', userdata: bytes = b'', vswitch_id: str = '') -> Dict: """Create new ecs instance. params: instance_type """ request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId(image_id) request.set_InstanceType(instance_type) request.set_SecurityGroupId(sgid) request.set_InstanceName(instance_name) request.set_InternetChargeType(internet_charge_type) if not host_name: host_name = instance_name request.set_HostName(host_name) # Optional if password: request.set_Password(password) # Optional if key_pair_name: request.set_KeyPairName(key_pair_name) if userdata: base64_bytes = base64.encodebytes(userdata) request.set_UserData(base64_bytes) if vswitch_id: request.set_VSwitchId(vswitch_id) return alisdk.do_action_with_exception(request)
def create_instance_request(zone_id, instance_type, instance_name, password, security_group_id, image_id, price_limit=0.02, sys_disk_size=20): create_request = CreateInstanceRequest.CreateInstanceRequest() create_request.set_ZoneId(zone_id) create_request.set_SecurityGroupId(security_group_id) create_request.set_InstanceType(instance_type) create_request.set_ImageId(image_id) create_request.set_SecurityEnhancementStrategy("Active") create_request.set_SpotStrategy("SpotWithPriceLimit") create_request.set_SpotPriceLimit(price_limit) create_request.set_IoOptimized('optimized') create_request.set_InternetMaxBandwidthOut(100) create_request.set_InstanceName(instance_name) create_request.set_SystemDiskCategory('cloud_efficiency') create_request.set_SystemDiskSize(sys_disk_size) create_request.set_Password(password) return create_request
def create_instance(config): click.echo( click.style("Creating instance with following params ...", fg="green")) client = config.create_api_client() req = CreateInstanceRequest.CreateInstanceRequest() create_params = config.get('CreateInstanceParams') if create_params: for param_name, param_value in create_params.items(): setter = getattr(req, 'set_' + param_name) setter(param_value) click.echo(click.style(f"Region-ID: {client.get_region_id()}", fg="green")) click.echo( click.style(f"InstanceName: {req.get_InstanceName()}", fg="green")) for param_name, param_value in create_params.items(): click.echo(click.style(f"{param_name} : {param_value}", fg="green")) result = do_action(client, req) instance_id = result['InstanceId'] config.set('InstanceId', instance_id) config.save() return instance_id
request.set_accept_format('json') request.set_PageSize(100) result = clt.do_action(request) result = json.loads(result) for i in result['Images']['Image']: #print i['ImageId'], i['Description'], i['OSType'], i['OSName'] if i['OSName'].strip() == u'Ubuntu 14.04 64位': image_id = i['ImageId'] print u"Ubuntu 14.04 64位 : %s" % image_id print "###########CreateInstance##########" request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.set_ImageId('ubuntu1404_64_40G_cloudinit_20160427.raw') request.set_InstanceType('ecs.t1.small') request.set_Password('123456') #result = clt.do_action(request) #print json.loads(result) ## {u'InstanceId': u'i-62pepv5ke', u'RequestId': u'0CF4B16A-EEE3-4C6A-A6AC-352630688D58'} print "##########AllocatePublicIpAddress###########" request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest() request.set_accept_format('json') request.set_InstanceId('i-62wpk9e7e')
def buy_instance(): clt = client.AcsClient('xxxxxx', 'xxxxxxxxxxxxx', 'cn-hangzhou') # 设置参数 request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.add_query_param('RegionId', 'cn-hangzhou') request.add_query_param('SecurityGroupId', 'Gxxxxxxxxxxxxxxx') request.add_query_param('InternetMaxBandwidthIn', 1) request.add_query_param('InternetMaxBandwidthOut', 1) request.add_query_param('Password', 'cqmyg.123') # 自定义镜像 #request.add_query_param('ImageId', 'm-xxxxxxxxxx') request.add_query_param('ImageId', 'm-xxxxxxxxxxxxxx') # 阿里云默认镜像 # request.add_query_param('ImageId', 'ubuntu_16_0402_64_20G_alibase_20180409.vhd') request.add_query_param('InstanceType', 'ecs.sn1.medium') request.add_query_param('SystemDisk.Size', '100') request.add_query_param('InstanceName', 'tmp_validate_web_db') # 购买实例 print("购买实例中...") response_buy = clt.do_action(request) print(response_buy) instance_id = json.loads(response_buy)["InstanceId"] # 分配公网IP time.sleep(3) print("分配公网ip中...") request_ip = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest( ) request_ip.set_accept_format('json') request_ip.add_query_param('InstanceId', instance_id) response_ip = clt.do_action(request_ip) print("已分配IP", response_ip) # 启动实例 print("启动实例中...") request_start = StartInstanceRequest.StartInstanceRequest() request_start.set_accept_format('json') #request_start.add_query_param('InstanceId', "i-bp15xf4ylewns1qav4q3") request_start.add_query_param('InstanceId', instance_id) response_start = clt.do_action(request_start) print(response_start) ## 设置自动释放时间 time.sleep(70) request_release = CommonRequest() request_release.set_accept_format('json') request_release.set_domain('ecs.aliyuncs.com') request_release.set_method('POST') request_release.set_version('2014-05-26') request_release.set_action_name('ModifyInstanceAutoReleaseTime') request_release.add_query_param('InstanceId', instance_id) # 设置3个小时后自动释放服务器 release_time_date = commands.getstatusoutput('date -u "+%Y-%m-%dT"')[1] tmp_hour = commands.getstatusoutput('date -u "+%H"')[1] release_time_hour = str(int(tmp_hour) + 4) # 如果小时小于10点,转为数字后会少个0 if len(release_time_hour) == 1: release_time_hour = "0" + release_time_hour # 分钟要求是UTC时间并精确到分钟,时间比当前时间至少多2分钟,不然会接口调用失败 tmp_minute = commands.getstatusoutput('date -u "+%M"')[1] release_time_minute = str(int(tmp_minute) + 3) # 如果遇到加了3分钟后大于59分的则直接设置分钟为3分钟,小时则加一小时 if int(release_time_minute) > 59: release_time_minute = "03" release_time_hour = str(int(release_time_hour) + 1) if len(release_time_minute) == 1: release_time_minute = "0" + release_time_minute if len(release_time_hour) == 1: release_time_hour = "0" + release_time_hour if len(release_time_minute) == 1: release_time_minute = "0" + release_time_minute release_time = str(release_time_date) + str(release_time_hour) + ":" + str( release_time_minute) + ":00Z" print(release_time) # 发送请求 request_release.add_query_param('AutoReleaseTime', release_time) response_release = clt.do_action_with_exception(request_release) print response_release
def my_create_instance(clt, imageid, instancetype, securitygroupid, hostname, etcname, bandout, vswitchid, keyname='puppet-imou', myopti='optimized'): createInstanceRequest = CreateInstanceRequest.CreateInstanceRequest() createInstanceRequest.set_accept_format('json') createInstanceRequest.set_ImageId(imageid) createInstanceRequest.set_InstanceType(instancetype) createInstanceRequest.set_SecurityGroupId(securitygroupid) createInstanceRequest.set_InstanceName(hostname) # PayByBandwidth PayByTraffic,默认使用按带宽付费 createInstanceRequest.set_InternetChargeType('PayByBandwidth') # 出网带宽,0-100(Mbps),带宽的设置主要是出网的带宽 createInstanceRequest.set_InternetMaxBandwidthOut(bandout) createInstanceRequest.set_HostName(etcname) #createInstanceRequest.set_Password(passwd) createInstanceRequest.set_IoOptimized(myopti) #I/O优化实例 createInstanceRequest.set_KeyPairName("puppet-imou") #密钥对 if vswitchid != '': createInstanceRequest.set_VSwitchId(vswitchid) #交换虚拟机 # PrePaid(包年包月) PostPaid(按量付费) createInstanceRequest.set_InstanceChargeType('PrePaid') # 买一个月 createInstanceRequest.set_Period(1) # 设置ip # createInstanceRequest.set_PrivateIpAddress(ip) createInstanceResponse = clt.do_action_with_exception( createInstanceRequest) instanceId = json.loads(createInstanceResponse)['InstanceId'] #print "instanceId is %s" % (instanceId) time.sleep(7) if int(bandout) > 0: allowPublicIpAddressRequest = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest( ) allowPublicIpAddressRequest.set_accept_format('json') allowPublicIpAddressRequest.set_InstanceId(instanceId) allowPublicIpAddressResponse = clt.do_action_with_exception( allowPublicIpAddressRequest) #print(allowPublicIpAddressResponse) startInstanceRequest = StartInstanceRequest.StartInstanceRequest() #添加外网IP print "start instances..." startInstanceRequest.set_accept_format('json') startInstanceRequest.set_InstanceId(instanceId) #启动实例 startInstanceResponse = clt.do_action_with_exception(startInstanceRequest) #print(startInstanceResponse) time.sleep(7) import_alito_dbandzabbix(clt, hostname) return instanceId
def copyInstanceConfigCreateInstance(host=None, oldname=None, newname=None): conn = pymongo.MongoClient(host).aly.instance result = conn.find({ 'InstanceName': oldname }).sort('_id', pymongo.DESCENDING) if result.count() == 0: print '>> Not Find %s' % oldname sys.exit(1) params = {} params['RegionId'] = result[0]['RegionId'] params['ZoneId'] = result[0]['ZoneId'] params['ImageId'] = [ x['ImageId'] for x in result[0]['images'] if x['Type'] == 'system' ][0] params['InstanceType'] = result[0]['InstanceType'] params['SecurityGroupId'] = result[0]['SecurityGroupIds'][ 'SecurityGroupId'][0] params['InstanceName'] = newname params['Description'] = newname params['InternetChargeType'] = result[0]['InternetChargeType'] params['InternetMaxBandwidthOut'] = result[0]['InternetMaxBandwidthOut'] params['HostName'] = newname params['IoOptimized'] = result[0]['IoOptimized'] and 'optimized' or 'none' params['SystemDisk.Category'] = [ x['Category'] for x in result[0]['images'] if x['Type'] == 'system' ][0] params['SystemDisk.Size'] = [ x['Size'] for x in result[0]['images'] if x['Type'] == 'system' ][0] params['DataDisk.1.Category'] = 'cloud' params['DataDisk.1.Size'] = 100 params['InstanceChargeType'] = result[0]['InstanceChargeType'] params['Period'] = 1 clt = client.AcsClient(access_key_id, access_key_secret, params['RegionId']) request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.set_query_params(params) #c_r = json.loads(clt.do_action(request)) c_r = json.loads( '{"InstanceId":"i-234hs2qwx","RequestId":"D3209274-D317-4041-8304-80D19F2ABB78"}' ) if c_r.get('InstanceId', None) == None: print '>> Create Instance %s' % c_r['Message'] sys.exit(1) if result[0]['PublicIpAddress']['IpAddress']: request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest( ) request.set_accept_format('json') request.set_query_params({'InstanceId': c_r['InstanceId']}) #p_r = json.loads(clt.do_action(request)) p_r = json.loads( '{"RequestId": "080A06E3-75C5-4256-910B-23278063C38F", "IpAddress": "114.55.149.208"}' ) if p_r.get('IpAddress', None) == None: print '>> Create Network %s' % c_r['Message'] sys.exit(1) request = DescribeInstancesRequest.DescribeInstancesRequest() request.set_accept_format('json') request.set_query_params({'InstanceIds': '["%s"]' % c_r['InstanceId']}) d_r = json.loads(clt.do_action(request)) innerIpAddress = d_r['Instances']['Instance'][0]['InnerIpAddress'][ 'IpAddress'][0] request = StartInstanceRequest.StartInstanceRequest() request.set_accept_format('json') request.set_query_params({'InstanceId': c_r['InstanceId']}) s_r = json.loads(clt.do_action(request)) while 1: request = DescribeInstancesRequest.DescribeInstancesRequest() request.set_accept_format('json') request.set_query_params({'InstanceIds': '["%s"]' % c_r['InstanceId']}) d_r = json.loads(clt.do_action(request)) if d_r['Instances']['Instance'][0]['Status'] == 'Running': break time.sleep(10) print os.popen('echo /home/easemob/zhaoyufeng/autoinitserver.sh %s %s' % (innerIpAddress, newname)).read()
def create(): """ :return: InstanceId """ # 创建新实例 request = CreateInstanceRequest.CreateInstanceRequest() request.set_ImageId("m-hp30yonwqwwz5tqwlhaq") # 镜像ID request.set_InstanceName("aliyun") # 设置实例名称, 显示在控制台 request.set_InstanceType( "ecs.gn5-c8g1.2xlarge" ) # 实例资源规格: tesla p100, 内存: 60G, 硬盘(2个): 40G, 400G 2.6一小时 request.set_SecurityGroupId("sg-hp3f3jpmruir2y5qtscs") # 安全组ID, 比默认多开了8888 # 实例规格族 https://www.alibabacloud.com/help/zh/doc-detail/25378.htm?spm=a3c0i.o25620zh.a3.1.2a2915d8lmwOC0 # ================== 网络 ================== # 参数 InternetChargeType InternetMaxBandwidthOut # PayByBandwidth 按固定带宽付费。 # 参数取值 为所选的固定带宽值。 # PayByTraffic 按使用流量付费。 # 带宽的上限设置,计费以实际使用的网络流量为依据。 request.set_InternetChargeType( "PayByTraffic") # 网络计费类型, 按使用流量配置, PayByTraffic为默认值 # todo 申请公网ip必须要设置大于0的值, 默认值为0 # 公网出带宽最大值, 单位 Mbit/s, 范围: 按带宽计费:[0, 100]; 按流量计费:[0, 100] request.set_InternetMaxBandwidthOut( "5") # InternetMaxBandwidthIn 的值在任何情况下都与计费无关,实例的入数据流量是免费的。 # ================== 网络 ================== request.set_HostName("aliyun") # 服务器主机名 request.set_SystemDiskCategory("cloud_efficiency") # 系统盘类型: 高效云盘 request.set_SystemDiskSize("40") # 系统盘大小, 默认值: max{40, ImageSize} # PrePaid:预付费,即包年包月。选择该类付费方式的用户必须确认自己的账号支持余额支付/信用支付,否则将返回 InvalidPayMethod 的错误提示。 # PostPaid:后付费,即按量付费。 request.set_InstanceChargeType("PostPaid") # 实例付费类型, 默认值:PostPaid 后付费 # NoSpot:正常按量付费实例 # SpotWithPriceLimit:设置上限价格的竞价实例 # SpotAsPriceGo:系统自动出价,最高按量付费价格。 request.set_SpotStrategy( "NoSpot" ) # 后付费的竞价策略, 当参数 InstanceChargeType 取值为 PostPaid 时为生效, 默认值:NoSpot # 通过提供ClientToken参数保证请求的幂等性。ClientToken是一个由客户端生成的唯一的、大小写敏感、不超过64个ASCII字符的字符串。 # 1、如果用户使用同一个ClientToken值调用创建实例接口,则服务端会返回相同的请求结果,包含相同的InstanceId。 # 因此用户在遇到错误进行重试的时候,可以通过提供相同的ClientToken值,来确保ECS只创建一个实例,并得到这个实例的InstanceId。 # 2、如果用户提供了一个已经使用过的ClientToken,但其他请求参数不同,则ECS会返回IdempotentParameterMismatch的错误代码。 # 但需要注意的是,SignatureNonce、Timestamp和Signature参数在重试时是需要变化的,因为ECS使用SignatureNonce来防止重放攻击,使用Timestamp来标记每次请求时间,所以再次请求必须提供不同的SignatureNonce和Timestamp参数值,这同时也会导致Signature值的变化。 # 3、通常,客户端只需要在500(InternalErrorInternalError)或503(ServiceUnavailable)错误、或者无法得到响应结果的情况下进行重试操作。 # 返回结果是200时,重试可以得到上次相同的结果,但不会对服务端状态带来任何影响。而对4xx的返回错误,除非提示信息里明确出现“try it later”,通常重试也是不能成功的。 timestamp = time.time() # 防止请求超时或服务器内部错误时,等原因, 客户端重试请求, 创建比预期要多的实例 request.set_ClientToken("skskskskskkffffffg" + str(timestamp)) # 发起请求, 返回json = { RequestId,InstanceId } response = client.do_action_with_exception(request) print("创建实例: {}".format(response)) # 创建的实例id instance_id = json.loads(response).get("InstanceId") # 保存instance_id, 启动后追加公网ip等信息 with open(file_name, "w") as f: f.write(instance_id) # save(instance_id) # todo 此时应该获取不到公网ip while True: # 检测实例状态, 可能实例还没创建好 instance_status = desc_instance_status([instance_id]) if instance_status == "Stopped": # 刚开始是 Pending, 初始化后为Stopped print("实例已创建, 申请公网ip...") # 为实例申请公网ip allocate_public_address(instance_id) print("公网ip已申请, 启动实例...") # 启动实例 start(instance_id) # 追加公网ip等信息 # save(instance_id, title=title, filename=file_name) elif instance_status == "Running": # 保存日志, 运行中才看到公网ip save(instance_id) break return instance_id
def main(instance_name, instance_type, disk_size, security_group=None): """ 开通阿里云ECS :param instance_name: 实例NAME,多台用半角逗号隔开,如:OPS-ALY-01-web01,OPS-ALY-01-web02 :param instance_type: 实例类型, 如: ecs.c5.large :param disk_size: 磁盘大小,建议不要小于50G, :param security_group:安全组ID,不输入则默认安全组 :return: """ # 这里前端传过来的,后续等前端完善,进行修改,目前假数据 data = { 'SecretId': 'xxxxxxxxxxx', 'SecretKey': 'xxxxxxxxxxx', 'region': 'cn-shanghai', 'ami_id': 'centos_7_06_64_20G_alibase_20181212.vhd', 'switch_id': 'vsw-uf6ocgoom79ceyvzdyls4', } for instance in instance_name.split(','): print('[INFO]: Instance: {}'.format(instance)) obj = ECS_API(data) # 检测实例名称是否已经存在 obj.check_instance(instance) # 随机密码 password = GenPassword(16) # 基础参数 request = CreateInstanceRequest.CreateInstanceRequest() request.set_accept_format('json') request.add_query_param('RegionId', data.get('region')) request.add_query_param('ImageId', data.get('ami_id')) request.add_query_param('InstanceType', instance_type) request.add_query_param('InstanceName', instance) request.add_query_param('InstanceChargeType', 'PostPaid') request.add_query_param('SystemDisk.Category', 'cloud_ssd') request.add_query_param('SystemDisk.Size', disk_size) request.add_query_param('VSwitchId', data.get('switch_id')) request.add_query_param('Password', password) # 判断是否输入了安全组ID if security_group != None: request.add_query_param('SecurityGroupId', security_group) # 创建实例 instance_id = obj.create_instance(request) # 绑定EIP eip_id, eip_ip = obj.creat_eip() obj.union_eip(eip_id, instance_id) # print(bool(instance_id)) # 启动实例 time.sleep(5) obj.start_instance(instance_id) host_info = obj.get_ecs_info(instance) data_info = {} if host_info: host = host_info.get('hostname') public_ip = host_info.get('public_ip') private_ip = host_info.get('private_ip') data_info[host] = { 'hostname': host, 'public_ip': public_ip, 'private_ip': private_ip, 'username': '******', 'password': password } # print(data_info) data_save(data_info)