使用boto3在多个区域中启动EC2

时间:2019-01-13 12:59:14

标签: amazon-web-services amazon-ec2 boto3

我正在使用以下代码启动EC2实例

     import boto3
     client = boto3.client('ec2',region_name='us-east-1')

     resp = client.run_instances(ImageId='ami-01e3b8c3a51e88954',
                        InstanceType='t2.micro',
                        MinCount=1,MaxCount=1)
     for instance in resp['Instances']:
     print(instance['InstanceId'])

此代码有效。但是我现在的要求是一次在多个区域中启动实例。 有人可以建议如何实现这一目标吗?

1 个答案:

答案 0 :(得分:3)

首先,您需要找到每个区域的ami ID。 AMI不是跨区域的,因此,对于每个区域,您都应该找到AMI ID。

然后您将执行以下操作:

import boto3

regions = {
    'us-east-1': 'ami-01e3b8c3a51e88954',
    'eu-west-1': 'ami-XXXXXXXXXXXXXXXXX',
}

for region in regions:
    region_client = boto3.client('ec2', region_name=region)

    resp = region_client.run_instances(ImageId=regions[region],
                                InstanceType='t2.micro',
                                MinCount=1, MaxCount=1)
    for instance in resp['Instances']:
        print(instance['InstanceId'])