1. 程式人生 > >阿里雲購買搶佔式伺服器python指令碼

阿里雲購買搶佔式伺服器python指令碼

#!/usr/bin/env python
# coding=utf-8
import json
import time
import traceback

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
from aliyunsdkecs.request.v20140526.RunInstancesRequest import RunInstancesRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest

RUNNING_STATUS = 'Running'
CHECK_INTERVAL = 3
CHECK_TIMEOUT = 180


class AliyunRunInstancesExample(object):

    def __init__(self):
        self.access_id = 'access_id'
        self.access_secret = 'access_secret'

        # 是否只預檢此次請求。true:傳送檢查請求,不會建立例項,也不會產生費用;false:傳送正常請求,通過檢查後直接建立例項,並直接產生費用
        self.dry_run = False
        # 例項所屬的地域ID
        self.region_id = 'cn-qingdao'
        # 例項的計費方式
        self.instance_charge_type = 'PostPaid'
        # 購買資源的時長
        self.period = 1
        # 購買資源的時長單位
        self.period_unit = 'Hourly'
        # 例項所屬的可用區編號
        self.zone_id = 'cn-qingdao-c'
        # 網路計費型別
        self.internet_charge_type = 'PayByTraffic'
        # 映象ID
        self.image_id = 'centos_7_04_64_20G_alibase_201701015.vhd'
        # 指定新建立例項所屬於的安全組ID
        self.security_group_id = 'security_group_id'
        # 虛擬交換機ID
        self.vswitch_id = 'vsw-m5er09pxr0rdhqqakc6yx'
        # 例項名稱
        self.instance_name = 'sethdemo'
        # 例項的密碼
        self.password = 'password'
        # 指定建立ECS例項的數量
        self.amount = 1
        # 公網出頻寬最大值
        self.internet_max_bandwidth_out = 5
        # 是否為I/O優化例項
        self.io_optimized = 'optimized'
        # 後付費例項的搶佔策略
        self.spot_strategy = 'SpotWithPriceLimit'
        # 設定例項的每小時最高價格
        self.spot_price_limit = 0.89
        # 是否開啟安全加固
        self.security_enhancement_strategy = 'Active'
        # 例項的資源規格
        self.instance_type = 'ecs.g5.large'
        # 系統盤大小
        self.system_disk_size = '40'
        # 系統盤的磁碟種類
        self.system_disk_category = 'cloud_efficiency'

        self.client = AcsClient(self.access_id, self.access_secret, self.region_id)

    def run(self):
        try:
            ids = self.run_instances()
            self._check_instances_status(ids)
        except ClientException as e:
            print('Fail. Something with your connection with Aliyun go incorrect.'
                  ' Code: {code}, Message: {msg}'
                  .format(code=e.error_code, msg=e.message))
        except ServerException as e:
            print('Fail. Business error.'
                  ' Code: {code}, Message: {msg}'
                  .format(code=e.error_code, msg=e.message))
        except Exception:
            print('Unhandled error')
            print(traceback.format_exc())

    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_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_IoOptimized(self.io_optimized)
        request.set_SpotStrategy(self.spot_strategy)
        request.set_SpotPriceLimit(self.spot_price_limit)
        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)

        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 _check_instances_status(self, instance_ids):
        """
        每3秒中檢查一次例項的狀態,超時時間設為3分鐘.
        :param instance_ids 需要檢查的例項ID
        :return:
        """
        start = time.time()
        while True:
            request = DescribeInstancesRequest()
            request.set_InstanceIds(json.dumps(instance_ids))
            body = self.client.do_action_with_exception(request)
            data = json.loads(body)
            print(data)
            for instance in data['Instances']['Instance']:
                if RUNNING_STATUS in instance['Status']:
                    instance_ids.remove(instance['InstanceId'])
                    print('Instance boot successfully: {}'.format(instance['InstanceId'],["PublicIpAddress"]["IpAddress"][0]))

            if not instance_ids:
                print('Instances all boot successfully')
                break

            if time.time() - start > CHECK_TIMEOUT:
                print('Instances boot failed within {timeout}s: {ids}'
                      .format(timeout=CHECK_TIMEOUT, ids=', '.join(instance_ids)))
                break

            time.sleep(CHECK_INTERVAL)

if __name__ == '__main__':
    AliyunRunInstancesExample().run()