"RunInstances" を使用して一括で複数の ECS インスタンスを作成できます。 アプリケーションの開発と展開を迅速に行うのに役立ちます。

CreateInstanceと比較して、RunInstancesには次のような利点があります。

  • "RunInstances" には、一度のリクエストで、最大 100 個のインスタンスまたは プリエンプティブインスタンスを作成し、自動的に実行するための "Amount" が含まれています 。
  • 一つのインスタンスを作成した際に、そのインスタンスのステータスは自動的に "Starting" に変わり、その後 "Running" に変わります。 "StartInstance" 操作を呼び出す必要はありません。
  • "InternetMaxBandwidthOut" の値を 0 より大きく設定した場合は、インスタンスにインターネット IP が割り当てられます。
  • すべてのリクエストを満たすため、 100 個の「プリエンプティブインスタンス」を一度に作成することもできます。
  • "AutoReleaseTime" の設定で、リリースプランをスケジュールすることができ、作成したパラメーターの数を "Amount" で設定できます。 エラーコードと "RunInstances" の使用可能なパラメーターは、"CreateInstance" と完全に互換性があります。
  • "InstanceIdSets" はリクエスト後に、すべての "InstanceIds" をリスト化するため、「作成されたインスタンスのステータスポーリング」が許可されます。

前提条件

"AccessKey" が作成されていること。

重要 プライマリアカウントの "AccessKey" を使用しないでください。 ライマリアカウントの "AccessKey" が開示されている場合、すべてのリソースが安全でない可能性があります。 RAM ユーザーアカウントの "AccessKey" を使用すれば、"AccessKey" が漏洩するリスクを軽減できます。

ECS Python SDK のインストール

Python のランタイムを所有していることをご確認ください。 ここでは、Python 2.7 以降のバージョンを例として取り上げております。

SDK のバージョンは 4.4.3 です。

pip install aliyun-python-sdk-ecs

操作許可がないことを示すメッセージを受け取った場合は、"sudo" に切り替えます。

sudo pip install aliyun-python-sdk-ecs

本説明で使用している SDK のバージョンは 4.4.3 です。 旧バージョンをお使いの場合、更新することを推奨します。

インスタンスの作成

"RunInstancesRequest" オブジェクトを作成し、関連パラメーターを入力します。

この例では、2 つのインスタンスを作成し、10 秒ごとにインスタンスのステータスを自動的にチェックするよう指定します。 インスタンスのステータスが "Running" に変わると、作成は完了します。

# your access key Id
ak_id = "YOU_ACCESS_KEY_ID"
# your access key secret
ak_secret = "YOU_ACCESS_SECRET"
region_id = "cn-beijing"
# your expected instance type
instance_type = "ecs.n4.small"
# The selected vswitchId
vswitch_id = "vws-xxxxx"
# The selected image info
image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
# The selected security group of VPC network
security_group_id = "sg-xxxxx"
# instance number to launch, support 1-100, default value is 100
amount = 2;
# The auto release time is in accordance with ISO8601 and must be UTC. The format is `yyyy-MM-ddTHH:mm:ssZ`. The release time must be at least 30 minutes later than the current time and less than 3 years from the current time.
auto_release_time = "2017-12-05T22:40:00Z"
clt = client.AcsClient(ak_id, ak_secret, 'cn-beijing')
# create instance automatic running
def batch_create_instance():
    request = build_request()
    request.set_Amount(amount)
    _execute_request(request)
def _execute_request(request):
    response = _send_request(request)
    if response.get('Code') is None:
        instance_ids = response.get('InstanceIdSets').get('InstanceIdSet')
        running_amount = 0
        while running_amount < amount:
            time.sleep(10)
            running_amount = check_instance_running(instance_ids)
    print("ecs instance %s is running", instance_ids)
def check_instance_running(instance_ids):
    request = DescribeInstancesRequest()
    request.set_InstanceIds(json.dumps(instance_ids))
    response = _send_request(request)
    if response.get('Code') is None:
        instances_list = response.get('Instances').get('Instance')
        running_count = 0
        for instance_detail in instances_list:
            if instance_detail.get('Status') == "Running":
                running_count += 1
        return running_count
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
# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)

インターネット IP を用いたインスタンスの作成

インスタンスを作成し、属性の行に追加してインターネット帯域幅を指定します。 この例では、各インスタンスに 1 Mbit/s の帯域幅を割り当てます。

# create instance with public ip.
def batch_create_instance_with_public_ip():
    request = build_request()
    request.set_Amount(amount)
    request.set_InternetMaxBandwidthOut(1)
    _execute_request(request)

自動リリース時間を用いたインスタンスの作成

インスタンスを作成」し、インスタンスの自動リリース時間を指定する属性行を追加します。 自動リリース時間は「 ISO8601 」に準拠しており、UTC でなければなりません。 形式は "YYYY-MM-DDTHH:mm:ssZ" です。 リリース時間は、現在の時刻より 30 分早く設定したり、 3 年を超えて設定することはできません。

# create instance with auto release time.
def batch_create_instance_with_auto_release_time():
    request = build_request()
    request.set_Amount(amount)
    request.set_AutoReleaseTime(auto_release_time)
    _execute_request(request)

完成コード例

完成コード例は以下のとおりです。

# coding=utf-8
# if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
# if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
# make sure the sdk version is 4.4.3, you can use command 'pip show aliyun-python-sdk-ecs' to check
import json
import logging
import time
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526. DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526. RunInstancesRequest import RunInstancesRequest
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')
# your access key Id
ak_id = "YOU_ACCESS_KEY_ID"
# your access key secret
ak_secret = "YOU_ACCESS_SECRET"
region_id = "cn-beijing"
# your expected instance type
instance_type = "ecs.n4.small"
# The selected vswitchId.
vswitch_id = "vws-xxxxx"
# The selected image info
image_id = "centos_7_03_64_20G_alibase_20170818.vhd"
# The selected security group of VPC network
security_group_id = "sg-xxxxx"
# instance number to launch, support 1-100, default value is 100
amount = 2;
# The auto release time is in accordance with ISO8601 and must be UTC. The format is `YYYY-MM-DDTHH:mm:ssZ`. The release time must be at least 30 minutes later than the current time and less than 3 years from the current time.
auto_release_time = "2017-12-05T22:40:00Z"
clt = client.AcsClient(ak_id, ak_secret, 'cn-beijing')
# create instance automatic running
def batch_create_instance():
    request = build_request()
    request.set_Amount(amount)
    _execute_request(request)
# create instance with public ip.
def batch_create_instance_with_public_ip():
    request = build_request()
    request.set_Amount(amount)
    request.set_InternetMaxBandwidthOut(1)
    _execute_request(request)
# create instance with auto release time.
def batch_create_instance_with_auto_release_time():
    request = build_request()
    request.set_Amount(amount)
    request.set_AutoReleaseTime(auto_release_time)
    _execute_request(request)
def _execute_request(request):
    response = _send_request(request)
    if response.get('Code') is None:
        instance_ids = response.get('InstanceIdSets').get('InstanceIdSet')
        running_amount = 0
        while running_amount < amount:
            time.sleep(10)
            running_amount = check_instance_running(instance_ids)
    print("ecs instance %s is running", instance_ids)
def check_instance_running(instance_ids):
    request = DescribeInstancesRequest()
    request.set_InstanceIds(json.dumps(instance_ids))
    response = _send_request(request)
    if response.get('Code') is None:
        instances_list = response.get('Instances').get('Instance')
        running_count = 0
        for instance_detail in instances_list:
            if instance_detail.get('Status') == "Running":
                running_count += 1
        return running_count
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
# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)
if __name__ == '__main__':
    print "hello ecs batch create instance"
    # batch_create_instance()
    # batch_create_instance_with_public_ip()
    # batch_create_instance_with_auto_release_time()