Example #1
0
def createInstance(params):
    request = CreateInstanceRequest()
    request.set_accept_format('json')

    if "SecurityGroupId" in params:
        request.set_SecurityGroupId(params["SecurityGroupId"])
    if "ZoneId" in params:
        request.set_ZoneId(params["ZoneId"])
    if "VSwitchId" in params:
        request.set_VSwitchId(params["VSwitchId"])

    request.set_ImageId(params["ImageId"])
    request.set_InstanceType(params["InstanceType"])

    request.set_InstanceName(params["InstanceName"])
    request.set_InternetChargeType(params["InternetChargeType"])
    request.set_AutoRenew(params["AutoRenew"])
    request.set_InternetMaxBandwidthOut(params["InternetMaxBandwidthOut"])
    request.set_Password(params["Password"])

    request.set_SystemDiskSize(params["SystemDiskSize"])
    request.set_SystemDiskCategory(params["SystemDiskCategory"])

    request.set_IoOptimized(params["IoOptimized"])
    request.set_InstanceChargeType(params["InstanceChargeType"])

    response = client.do_action_with_exception(request)
    response = json.loads(str(response, encoding='utf-8'))

    return response["InstanceId"]
Example #2
0
def CreateInstance(ak, sk, region_tag, instance_name, security_id, vpc_id, instance_type, bandout):
    global instance_id
    client = AcsClient(ak, sk, region_tag)
    request = CreateInstanceRequest()
    request.set_accept_format('json')
    request.set_InstanceName(instance_name)
    request.set_SecurityGroupId(security_id)    #安全组
    request.set_InstanceType(instance_type)    #型号
    request.set_ImageId("m-bp1a8si7x4swoetbhtgn")    #统一镜像
    request.set_VSwitchId(vpc_id)  #指定VPC的交换机
    request.set_KeyPairName("电商平台秘钥")    #秘钥
    request.set_InstanceChargeType("PrePaid")    #预付费
    request.set_IoOptimized("optimized")    #IO强化
    request.set_SystemDiskSize(40)        #磁盘容量
    request.set_SystemDiskCategory("cloud_ssd")    #高效云盘
    request.set_PasswordInherit(True)
    request.set_InternetMaxBandwidthOut(bandout)    #出网带宽1M
    request.set_Period(1)	#购买资源的时长
    request.set_AutoRenewPeriod(1)    #按月续费
    request.set_InternetChargeType("PayByTraffic")    #按流量计费
    request.set_AutoRenew(True)        #自动计费
    response = client.do_action_with_exception(request)
    result = str(response, encoding='utf-8')
    data = json.loads(result)
    instance_id = data["InstanceId"]
    print("生成新的ECS的ID号是=======>" + str(instance_id))
    return instance_id		#返回ID给下面使用
Example #3
0
class ECSClientBuilder(object):
    def __init__(self):
        self.request = CreateInstanceRequest()
        self.keyPairName = None

    def instance_type(self, value):
        self.request.set_InstanceType(value)
        return self

    def image_id(self, value):
        self.request.set_ImageId(value)
        return self

    def security_group(self, value):
        self.request.set_SecurityGroupId(value)
        return self

    def key_pair_name(self, value):
        self.request.set_KeyPairName(value)
        self.keyPairName = value
        return self

    def internet_max_bandwidth_out(self, value):
        self.request.set_InternetMaxBandwidthOut(value)
        return self

    def build(self):
        if not self.keyPairName:
            raise ValueError("key_pair_name should be set")
        client = ECSClient(self.keyPairName,
                           create_instance_request=self.request)
        return client
Example #4
0
    def CreateInstance(self, region_id, ZoneId, ImageId, InstanceType, InstanceName, InstanceChargeType,
                       InternetChargeType,
                       InternetMaxBandwidthOut, HostName, DataDisk, Password, VSwitchId, SecurityGroupId,
                       UserData):
        """
        创建 实例
        :param region_id:   地域
        :param ZoneId:  可用区
        :param ImageId: 镜像
        :param InstanceType:  实例模板
        :param InstanceName:  实例名字
        :param InstanceChargeType:  计费方式
        :param InternetChargeType:  网络计费方式
        :param InternetMaxBandwidthOut:  出网带宽
        :param HostName:  主机名字
        :param DataDisk:  数据盘
        :param Password:  密码
        :param VSwitchId: 交换机
        :param SecurityGroupId:  安全组
        :param UserData: 机器初始化cloud_init加载脚本
        :return: {'InstanceId': 'i-2ze210z0uiwyadm1m7x6'}
        """
        createclt = AcsClient(self.AccessKeyId, self.AccessKeySecret, region_id)
        createreq = 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)
        createreq.set_InstanceChargeType(InstanceChargeType)
        if InstanceChargeType == 'PrePaid':
            createreq.set_Period('1')
        if InternetChargeType:
            createreq.set_InternetChargeType(InternetChargeType)
            createreq.set_InternetMaxBandwidthOut(InternetMaxBandwidthOut)
        createreq.set_HostName(HostName)
        createreq.set_Password(Password)
        createreq.set_VSwitchId(VSwitchId)
        createreq.set_SecurityGroupId(SecurityGroupId)

        '''通用配置 以下配固定不变配置'''
        createreq.set_KeyPairName('twl-vpc-ecs-key')  # 初始化key
        createreq.set_SecurityEnhancementStrategy('Active')  # 安全加固
        createreq.set_IoOptimized('optimized')  # IO优化

        createreq.set_DataDisks(DataDisk)  # 数据盘

        ''' 通用配置  系统盘 '''
        createreq.set_SystemDiskCategory('cloud_efficiency')  # 高效云盘
        createreq.set_SystemDiskSize(40)  # 系统盘大小40G
        createreq.set_SystemDiskDiskName(HostName + "-sysdisk")  # 系统盘命名

        ''' 初始化要执行的脚本'''
        createreq.set_UserData(UserData)  # 传入UserData数据,进行开机初始化
        createre = json.loads(createclt.do_action_with_exception(createreq), encoding='utf-8')
        return createre
Example #5
0
    def _boot_image(self, zone_id, image_id, instance_type, vswitch_id,
                    instance_name, ssh_keyname, security_group_id):
        request = CreateInstanceRequest()
        request.set_ImageId(image_id)
        request.set_SecurityGroupId(security_group_id)
        request.set_InstanceType(instance_type)
        request.set_VSwitchId(vswitch_id)
        request.set_ZoneId(zone_id)
        request.set_InstanceChargeType('PostPaid')
        request.set_KeyPairName(ssh_keyname)
        request.set_InternetMaxBandwidthOut(1)
        response = self._send_request(request)
        instance_id = response.get('InstanceId')
        if instance_id is None:
            logger.info(response)
            raise Exception("Instance could not be created.")
        self.instance_id = instance_id
        logger.info("Instance %s created" % instance_id)

        logger.info(
            "Wait for the instance to appear as stopped so we can continue")
        max_tries = 10
        status = None
        while max_tries > 0 and status != 'Stopped':
            max_tries -= 1
            time.sleep(5)
            status = self._get_instance_status_by_id(instance_id)
        if status != 'Stopped':
            raise Exception("VM %s not in desired state" % instance_id)

        logger.info("Allocating public ip for instance %s" % instance_id)
        request = AllocatePublicIpAddressRequest()
        request.set_InstanceId(instance_id)
        ip_address = self._send_request(request)
        logger.info("Public IP address asssigned to instance: %s" % ip_address)
        logger.info(json.dumps(ip_address, indent=4))

        logger.info("Starting instance %s" % instance_id)
        request = StartInstanceRequest()
        request.set_InstanceId(instance_id)
        self._send_request(request)

        # wait for instance to be started
        max_tries = 60
        status = "initial"
        while max_tries > 0 and status != 'Running':
            max_tries -= 1
            time.sleep(10)
            status = self._get_instance_status_by_id(instance_id)
            logger.info("Status is %s" % status)

        if status != 'Running':
            raise Exception("Instance %s status is %s: failed to start." %
                            (instance_id, status))

        return (instance_id, ip_address)
Example #6
0
    def create_instance(
        self,
        instance_type,
        image_id,
        tags,
        key_pair_name,
        optimized="optimized",
        instance_charge_type="PostPaid",
        spot_strategy="SpotWithPriceLimit",
        internet_charge_type="PayByTraffic",
        internet_max_bandwidth_out=5,
    ):
        """ Create a subscription or pay-as-you-go ECS instance.

        :param instance_type: The instance type of the ECS.
        :param image_id: The ID of the image used to create the instance.
        :param tags: The tags of the instance.
        :param key_pair_name: The name of the key pair to be bound to
                              the instance.
        :param optimized: Specifies whether the instance is I/O optimized
        :param instance_charge_type: The billing method of the instance.
                                     Default value: PostPaid.
        :param spot_strategy: The preemption policy for the pay-as-you-go
                              instance.
        :param internet_charge_type: The billing method for network usage.
                                     Default value: PayByTraffic.
        :param internet_max_bandwidth_out: The maximum inbound public
                                           bandwidth. Unit: Mbit/s.
        :return: The created instance ID.
        """
        request = CreateInstanceRequest()
        request.set_InstanceType(instance_type)
        request.set_ImageId(image_id)
        request.set_IoOptimized(optimized)
        request.set_InstanceChargeType(instance_charge_type)
        request.set_SpotStrategy(spot_strategy)
        request.set_InternetChargeType(internet_charge_type)
        request.set_InternetMaxBandwidthOut(internet_max_bandwidth_out)
        request.set_KeyPairName(key_pair_name)
        request.set_Tags(tags)

        response = self._send_request(request)
        if response is not None:
            instance_id = response.get("InstanceId")
            logging.info("instance %s created task submit successfully.",
                         instance_id)
            return instance_id
        logging.error("instance created failed.")
        return None
 def create_after_pay_instance(self, internet_max_bandwidth_out=1, image_id="m-bp19ibpdra8vdltxftbc",
                               instance_type="ecs.ic5.large"):
     request = CreateInstanceRequest()
     request.set_ImageId(image_id)
     request.set_InstanceType(instance_type)
     request.set_IoOptimized('optimized')
     request.set_SystemDiskCategory('cloud_ssd')
     request.set_KeyPairName(self.keyPairName)
     if internet_max_bandwidth_out > 0:
         request.set_InternetMaxBandwidthOut(internet_max_bandwidth_out)
     response = self.execute(request)
     logger.info(response)
     instance_id = response.get('InstanceId')
     logger.info("instance %s created task submit successfully.", instance_id)
     return instance_id
Example #8
0
    def createInstance(self):
        ret = {}
        clt = self.createECS_Client()
        request = CreateInstanceRequest()
        request.set_ImageId(self.imageID)
        request.set_InstanceType(self.instanceType)
        request.set_SecurityGroupId(self.groupID)
        request.set_SpotPriceLimit(float(self.price))
        request.set_KeyPairName(self.keyName)
        request.set_InternetMaxBandwidthOut(int(self.bandwidth))
        request.set_IoOptimized('optimized')
        request.set_SystemDiskCategory('cloud_efficiency')
        request.set_InstanceChargeType('PostPaid')
        request.set_SpotStrategy('SpotWithPriceLimit')
        request.set_InternetChargeType('PayByTraffic')
        request.set_VSwitchId(self.vSwitchID)
        """步骤
        1. 创建 ECS
        2. 创建 EIP(暂时废弃)
        3. 启动 ECS
        4. 关联 EIP 到 ECS(暂时废弃)
        """

        response = self._send_request(clt, request)
        if response['code'] != 0:
            logger.warn("create instance failed with %s" % response['msg'])
            return response
        logger.info("create ecs done.")

        instanceID = response['msg'].get('InstanceId')
        associateID = ""
        """ 申请公网 IP
        if self.assoID != "" and self.eip != "":
            logger.debug("use existed eip to asso the ecs.")
            ret['EipAddress'] = self.eip
            associateID = self.assoID
        else:
            response = self.allocEIP(clt)
            if response['code'] != 0:
                logger.warn("alloc EIP failed with %s" % response['msg'])
                return response
            logger.info("alloc EIP response done.")
            ret['EipAddress'] = response['msg']['EipAddress']
            associateID = response['msg']['AllocationId']
        """

        while True:
            response = self.startInstance(clt, instanceID)
            if response['code'] == 0:
                logger.debug("start instance OK, return %s" % response['msg'])
                break
            logger.debug("response code: %s", str(response['code']))
            if response['code'] != 'IncorrectInstanceStatus':
                logger.error("start instance failed with %s" % response['msg'])
                ret['code'] = 1
                ret['msg'] = "start instance failed with" + str(
                    response['msg'])
                return ret
            logger.warn("start instance failed with IncorrectInstanceStatus")
            time.sleep(1)
        logger.debug("start instance done.")
        """关联公网 IP 到 ECS 上
        while True:
            response = self.associateEIP(clt, associateID, instanceID)
            if response['code'] == 0:
                logger.info("associateEIP OK, response: %s" % response['msg'])
                break
            if response['msg']['Code'] != "IncorrectInstanceStatus":
                logger.error("associateEIP failed with %s" % response['msg'])
                return response
            logger.warn("start instance failed with IncorrectInstanceStatus")
            time.sleep(1)
        logger.info("associateEIP done.")
        """

        response = self.getInstanceDetail(clt, instanceID)
        logger.info(response)

        ret['LockReason'] = ''
        lock_reason = response['msg'].get('Instances').get('Instance')[0].get(
            'OperationLocks').get('LockReason')
        if lock_reason is not None:
            for reason in lock_reason:
                if reason == "Recycling":
                    ret['LockReason'] = 'Recycling'
                    break

        ret['InstanceID'] = instanceID
        ret['ExpiredTime'] = response['msg'].get('Instances').get(
            'Instance')[0].get('ExpiredTime')
        ret['EipAddress'] = response['msg'].get('Instances').get(
            'Instance')[0].get('EipAddress').get('IpAddress')
        ret['Hostname'] = response['msg'].get('Instances').get(
            'Instance')[0].get('HostName')
        ret['InnerAddress'] = response['msg'].get('Instances').get('Instance')[
            0].get('VpcAttributes').get('PrivateIpAddress').get('IpAddress')[0]
        ret['msg'] = "Create ECS successfully."
        ret['code'] = 0
        logger.info(ret)
        return ret