Exemple #1
0
    def run_instances(self):
        """
        调用创建实例的API,得到实例ID后继续查询实例状态
        :return:instance_ids 需要检查的实例ID
        """
        request = RunInstancesRequest()

        request.set_DryRun(self.dry_run)

        request.set_InstanceType(self.instance_type)
        request.set_InstanceChargeType(self.instance_charge_type)
        request.set_ImageId(self.image_id)
        request.set_SecurityGroupId(self.security_group_id)
        request.set_Period(self.period)
        request.set_PeriodUnit(self.period_unit)
        request.set_ZoneId(self.zone_id)
        request.set_InternetChargeType(self.internet_charge_type)
        request.set_VSwitchId(self.vswitch_id)
        request.set_InstanceName(self.instance_name)
        request.set_Amount(self.amount)
        request.set_InternetMaxBandwidthOut(self.internet_max_bandwidth_out)
        request.set_HostName(self.host_name)
        request.set_IoOptimized(self.io_optimized)
        request.set_KeyPairName(self.key_pair_name)
        request.set_SecurityEnhancementStrategy(
            self.security_enhancement_strategy)
        request.set_SystemDiskSize(self.system_disk_size)
        request.set_SystemDiskCategory(self.system_disk_category)

        body = self.client.do_action_with_exception(request)
        data = json.loads(body)
        instance_ids = data['InstanceIdSets']['InstanceIdSet']
        print('Success. Instance creation succeed. InstanceIds: {}'.format(
            ', '.join(instance_ids)))
        return instance_ids
Exemple #2
0
    def run_instances(self):
        """
        调用ECS API
        instance_id得出的是列表
        :return:
        """
        request = RunInstancesRequest()
        request.set_DryRun(self.dry_run)

        request.set_InstanceType(self.instance_type)
        request.set_InstanceChargeType(self.instance_charge_type)
        request.set_ImageId(self.image_id)
        request.set_SecurityGroupId(self.security_group_id)
        request.set_ZoneId(self.zone_id)
        request.set_InternetChargeType(self.internet_charge_type)
        request.set_VSwitchId(self.vswitch_id)
        request.set_InstanceName(self.instance_name)
        request.set_Password(self.password)
        request.set_Amount(self.amount)
        request.set_InternetMaxBandwidthOut(self.internet_max_bandwidth_out)
        request.set_SystemDiskSize(self.system_disk_size)
        request.set_SystemDiskCategory(self.system_disk_category)
        request.set_DataDisks(self.data_disks)
        request.set_Tags(self.tags)

        body = self.client.do_action_with_exception(request)
        data = json.loads(body)
        instance_id = data['InstanceIdSets']['InstanceIdSet']
        print('Success Instance Create. InstanceId: {}'.format(' '.join(instance_id)))
        return instance_id
Exemple #3
0
    def run_instances(self):
        """
        调用创建实例的API,得到实例ID后继续查询实例状态
        :return:instance_ids 需要检查的实例ID
        """
        request = RunInstancesRequest()

        request.set_DryRun(self.dry_run)

        request.set_InstanceChargeType(self.instance_charge_type)
        request.set_Period(self.period)
        request.set_PeriodUnit(self.period_unit)
        request.set_ZoneId(self.zone_id)
        request.set_InternetChargeType(self.internet_charge_type)
        request.set_ImageId(self.image_id)
        request.set_SecurityGroupId(self.security_group_id)
        request.set_InstanceName(self.instance_name)
        request.set_PasswordInherit(self.password_inherit)
        request.set_Amount(self.amount)
        request.set_InternetMaxBandwidthOut(self.internet_max_bandwidth_out)
        request.set_UniqueSuffix(self.unique_suffix)
        request.set_IoOptimized(self.io_optimized)
        request.set_SecurityEnhancementStrategy(
            self.security_enhancement_strategy)
        request.set_InstanceType(self.instance_type)
        request.set_SystemDiskSize(self.system_disk_size)
        request.set_SystemDiskCategory(self.system_disk_category)
        request.set_DataDisks(self.data_disks)

        body = self.client.do_action_with_exception(request)
        data = json.loads(body)
        instance_ids = data["InstanceIdSets"]["InstanceIdSet"]
        print("Success. Instance creation succeed. InstanceIds: {}".format(
            ", ".join(instance_ids)))
        return instance_ids
Exemple #4
0
def build_request():
    request = RunInstancesRequest()
    request.set_ImageId(image_id)
    request.set_VSwitchId(vswitch_id)
    request.set_SecurityGroupId(security_group_id)
    request.set_InstanceName("Instance12-04")
    request.set_InstanceType(instance_type)
    return request
Exemple #5
0
def create_ali_ecs_PrePaid(ImageId, InstanceType,
                   SecurityGroupIds, VSwitchId,
                   InstanceName, Description,
                   HostName, ZoneId,
                   regionId, service_name, PeriodUnit, *args, **kwargs):

    print(args)
    print(kwargs)

    client = AcsClient(accessKeyId, accessSecret, regionId)
    request = RunInstancesRequest()
    request.set_accept_format('json')

    password = '******'

    request.set_ImageId(ImageId)
    request.set_InstanceType(InstanceType)
    request.set_SecurityGroupIdss(SecurityGroupIds)
    request.set_VSwitchId(VSwitchId)
    request.set_InstanceName(InstanceName)
    request.set_Description(Description)
    request.set_HostName(HostName)
    request.set_Password(password)
    request.set_ZoneId(ZoneId)
    request.set_Amount(1)
    request.set_SecurityEnhancementStrategy("Active")

    request.set_Tags([
      {
        "Key": "group",
        "Value": service_name
      }
    ])

    for kwarg in kwargs:
        # 判断数据盘指定与否
        if 'datadisk' in kwarg:
            DataDisk = kwargs['datadisk']
            request.set_DataDisks([
                {
                    "Size": DataDisk,
                    "Category": "cloud_ssd"
                }
            ])

    request.set_Period(1)
    request.set_PeriodUnit(PeriodUnit)
    request.set_AutoRenew(True)
    request.set_AutoRenewPeriod(1)
    request.set_InstanceChargeType("PrePaid")

    response = client.do_action_with_exception(request)
    res = json.loads(str(response, encoding='utf-8'))
    return res
Exemple #6
0
    def run_instance(self):
        """
        调用创建实例的API,得到实例ID后继续查询实例状态
        :return:instance_ids 需要检查的实例ID
        """
        request = RunInstancesRequest()
       
        request.set_DryRun(self.dry_run)
        
        request.set_InstanceType(self.instance_type)
        request.set_InstanceChargeType(self.instance_charge_type)
        request.set_ImageId(self.image_id)
        request.set_SecurityGroupId(self.security_group_id)
        request.set_Period(self.period)
        request.set_PeriodUnit(self.period_unit)
        request.set_ZoneId(self.zone_id)
        request.set_InternetChargeType(self.internet_charge_type)
        request.set_VSwitchId(self.vswitch_id)
        request.set_Amount(self.amount)
        request.set_InternetMaxBandwidthOut(self.internet_max_bandwidth_out)
        request.set_IoOptimized(self.io_optimized)
        request.set_KeyPairName(self.key_pair_name)
        request.set_SecurityEnhancementStrategy(self.security_enhancement_strategy)
        request.set_SystemDiskSize(self.system_disk_size)
        request.set_SystemDiskCategory(self.system_disk_category)

#         shellScript = """#!/bin/bash
# echo "{}" > {}
# chmod 777 {}
# """.format(flag, targetFile, targetFile)
#         print(shellScript)

        # userData = base64.b64encode(bytes(shellScript, encoding = "utf-8"))
        # userData = userData.decode(encoding='utf-8')
        # print(userData)

        # request.set_UserData(userData)

        body = self.client.do_action_with_exception(request)
        data = json.loads(body)
        instance_ids = data['InstanceIdSets']['InstanceIdSet']
        # print('Success. Instance creation succeed. InstanceIds: {}'.format(', '.join(instance_ids)))
        return instance_ids
    def run_instances(self):
        """
        调用创建实例的API,得到实例ID后继续查询实例状态
        :return:instance_ids 需要检查的实例ID
        """
        request = RunInstancesRequest()

        # true:发送检查请求,不会创建实例。检查项包括是否填写了必需参数、请求格式、业务限制和ECS库存。如果检查不通过,则返回对应错误。如果检查通过,则返回错误码DryRunOperation
        # false(默认):发送正常请求,通过检查后直接创建实例。
        request.set_DryRun(self.dry_run)

        request.set_InstanceType(self.instance_type)
        request.set_InstanceChargeType(self.instance_charge_type)
        request.set_ImageId(self.image_id)
        request.set_SecurityGroupId(self.security_group_id)
        request.set_Period(self.period)
        request.set_PeriodUnit(self.period_unit)
        request.set_ZoneId(self.zone_id)
        request.set_InternetChargeType(self.internet_charge_type)
        request.set_VSwitchId(self.vswitch_id)
        request.set_InstanceName(self.instance_name)
        request.set_Password(self.password)
        request.set_Amount(self.amount)
        request.set_InternetMaxBandwidthOut(self.internet_max_bandwidth_out)
        request.set_UniqueSuffix(self.unique_suffix)
        request.set_IoOptimized(self.io_optimized)
        request.set_SecurityEnhancementStrategy(
            self.security_enhancement_strategy)
        if self.auto_release_time:
            request.set_AutoReleaseTime(self.auto_release_time)
        request.set_SystemDiskSize(self.system_disk_size)
        request.set_SystemDiskCategory(self.system_disk_category)
        request.set_DataDisks(self.data_disks)
        request.set_Tags(self.tags)

        body = self.client.do_action_with_exception(request)
        data = json.loads(body)
        instance_ids = data['InstanceIdSets']['InstanceIdSet']
        print('Success. Instance creation succeed. InstanceIds: {}'.format(
            ', '.join(instance_ids)))

        # instance_ids 输出为一个list
        return instance_ids
Exemple #8
0
def create(user_data):
    request = RunInstancesRequest()
    request.set_accept_format('json')

    request.set_ImageId("ubuntu_18_04_64_20G_alibase_20190624.vhd")
    request.set_InstanceType("ecs.t5-lc2m1.nano")
    request.set_SecurityGroupId("sg-j6c0z0xdiqgujaby8hu4")
    request.set_VSwitchId("vsw-j6cpqku7fl7zjcej0fj1b")
    request.set_InstanceName("ss-slave")
    request.set_Description("ss-slave")
    request.set_InternetMaxBandwidthOut(100)
    request.set_HostName("ss-slave")
    request.set_UniqueSuffix(True)
    request.set_InternetChargeType("PayByTraffic")
    request.set_UserData(user_data)
    request.set_KeyPairName("ss-slave")
    request.set_Amount(1)

    response = client.do_action_with_exception(request)
    res = json.loads(response)
    return res["InstanceIdSets"]["InstanceIdSet"]
Exemple #9
0
    def _launch_instance(self):
        """Launch an instance of the given image."""
        client = self._connect()
        instance_name = self._generate_instance_name()

        request = RunInstancesRequest()
        request.set_InstanceType(self.instance_type or ALIYUN_DEFAULT_TYPE)
        request.set_InstanceChargeType('PostPaid')
        request.set_ImageId(self.image_id)
        request.set_InstanceName(instance_name)
        request.set_Amount(1)
        request.set_InternetMaxBandwidthOut(5)
        request.set_SystemDiskSize(20)
        request.set_IoOptimized('optimized')
        request.set_SecurityEnhancementStrategy('Active')
        request.set_VSwitchId(self.v_switch_id)
        request.set_SecurityGroupId(self.security_group_id)

        if self.zone:
            request.set_ZoneId(self.zone)

        if self.ssh_key_name:
            request.set_KeyPairName(self.ssh_key_name)
        else:
            request.set_UserData(b64encode(self._get_user_data().encode()))

        try:
            response = json.loads(client.do_action_with_exception(request))
        except Exception as error:
            raise AliyunCloudException(
                'Unable to create instance: {0}.'.format(error))

        self.running_instance_id = \
            response['InstanceIdSets']['InstanceIdSet'][0]
        self.logger.debug('ID of instance: %s' % self.running_instance_id)
        self._wait_on_instance('Running', self.timeout)
Exemple #10
0
    def run_instances(
        self,
        instance_type,
        image_id,
        tags,
        security_group_id,
        vswitch_id,
        key_pair_name,
        amount=1,
        optimized="optimized",
        instance_charge_type="PostPaid",
        spot_strategy="SpotWithPriceLimit",
        internet_charge_type="PayByTraffic",
        internet_max_bandwidth_out=1,
    ):
        """ Create one or more pay-as-you-go or subscription
            Elastic Compute Service (ECS) instances

        :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 security_group_id: The ID of the security group to which to
                                  assign the instance. Instances in the same
                                  security group can communicate with
                                  each other.
        :param vswitch_id: The ID of the vSwitch to which to connect
                           the instance.
        :param key_pair_name: The name of the key pair to be bound to
                              the instance.
        :param amount: The number of instances that you want to create.
        :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 IDs.
        """
        request = RunInstancesRequest()
        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_Tags(tags)
        request.set_Amount(amount)
        request.set_SecurityGroupId(security_group_id)
        request.set_VSwitchId(vswitch_id)
        request.set_KeyPairName(key_pair_name)

        response = self._send_request(request)
        if response is not None:
            instance_ids = response.get("InstanceIdSets").get("InstanceIdSet")
            return instance_ids
        logging.error("instance created failed.")
        return None