Ejemplo n.º 1
0
def allocate_public_ip_address(client, instance_id):
    req = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
    req.set_InstanceId(instance_id)
    req.set_accept_format('json')

    resp = loads(client.do_action(req))
    return resp['IpAddress']
Ejemplo n.º 2
0
    def __allocPublicAddress(self):
        if self.__InstanceId is None:
            print ' instanceId is none exit'
            return 1

        request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
        request.set_InstanceId(self.__InstanceId)

        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 2

        if result_data.has_key(u"Code"):
            print 'alloc Public Address instance failed Code %s with instanceid %s' % (result_data[u'Code'], self.__InstanceId)
            print result_data[u'Message']
            return 1

        else:
            print 'allow public  instance %s successful  ' % instance
            return 0
Ejemplo n.º 3
0
 def allocate_public_ip(self, instanceid ):
     client = AcsClient(access_key_id, access_key_secret,region_id)
     request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
     request.set_InstanceId(instanceid)
     response = client.do_action_with_exception(request)
     print (response)
     return response
Ejemplo n.º 4
0
def allocatePublicIpAddress(clt,instanceId):
    request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()

    request.set_accept_format('json')
    request.set_InstanceId(instanceId)
    result = clt.do_action(request)
    print "allocatePublicIpAddress=="+result
    return  json.loads(result);
Ejemplo n.º 5
0
 def associate_public_ip(self, instance_id):
     request = PublicIp.AllocatePublicIpAddressRequest()
     request.set_InstanceId(instance_id)
     response = self.execute(request, raise_on_falsy=True)
     ip_address = response['IpAddress']
     utils.set_external_resource_id(ip_address, ctx.target.instance, False)
     set_eip_runtime_properties(ctx.target.instance, ip_address)
     return True
Ejemplo n.º 6
0
def create_instance_ip(instance_id,accesskey_id,accesskey_secret,region_id):
    clt = client.AcsClient(accesskey_id, accesskey_secret, region_id)
    request=AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
    request.set_accept_format('json')
    request.set_InstanceId(instance_id)
    result = clt.do_action_with_exception(request)
    js_str=json.loads(result)
    print result
    print ("The public IP assigned to the ECS is "+js_str["IpAddress"])
    return
Ejemplo n.º 7
0
 def allocate_pub_ip(self, **kwargs):
     """
     :params: ECS实例ID
     """
     request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest(
     )
     for k, v in kwargs.items():
         request.add_query_param(k, v)
     result = self.client.do_action(request)
     return result
def allocate_public_address(instance_id):
    """
    为实例申请公网ip, 异常如下
    1、只有运行中和已停止可以申请
    2、当VPC类型实例已经绑定了 EIP,则无法再分配公网 IP。
    3、一台实例只能分配一个公网 IP 地址。如果实例已经拥有一个公网 IP 地址,将报错 AllocatedAlready。
    4、重启实例(RebootInstance)或者启动实例(StartInstance)后,新的公网 IP 地址生效。
    5、被 安全控制 的实例的 OperationLocks 中标记了 "LockReason" : "security" 时,不能分配公网 IP 地址。
    :return:
    """
    request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
    request.set_InstanceId(instance_id)
    # 发起请求, 返回json = { RequestId,InstanceId }
    response = client.do_action_with_exception(request)
    IpAddress = json.loads(response)["IpAddress"]
    print("为实例申请公网ip: {}".format(IpAddress))
    return response
Ejemplo n.º 9
0
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()
Ejemplo n.º 10
0
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')

#print clt.do_action(request)
## {"RequestId":"3993EC47-222B-48EE-ABA1-246CEB40B2FC","IpAddress":"49.213.8.1"}

print "##########StartInstance###########"

request = StartInstanceRequest.StartInstanceRequest()
request.set_accept_format('json')
request.set_InstanceId('i-62wpk9e7e')

#print clt.do_action(request)

print "##########ModifyInstanceNetworkSpec###########"
Ejemplo n.º 11
0
def allocate_public_ip(config):
    click.echo(click.style("正在分配公网 IP ...", fg="green"))
    client = config.create_api_client()
    req = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest()
    req.set_InstanceId(config.get('InstanceId'))
    result = do_action(client, req)
Ejemplo n.º 12
0
 def allocate_public_ip(self, instance_id):
     request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest(
     )
     request.set_InstanceId(instance_id)
     response = self.client.do_action_with_exception(request)
     return json.loads(response.decode('utf-8'))['IpAddress']
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
 def AllocatePublicIpAddress(self, instance_id):
     request = AllocatePublicIpAddressRequest.AllocatePublicIpAddressRequest(
     )
     request.set_InstanceId(instance_id)
     result = self.client.do_action_with_exception(request)
     print result