使用 Boto3 启动多个 EC2 实例

Dam*_*men 0 python amazon-ec2 amazon-web-services boto3

我正在使用下面的代码获取实例列表

    def list_instances_by_tag_value(self, tagkey, tagvalue):
    ec2client = boto3.client('ec2')
    response = ec2client.describe_instances(
        Filters=[
            {
                'Name': 'tag:'+tagkey,
                'Values': [tagvalue]
            }
        ]
    )
    instancelist = []
    for reservation in (response["Reservations"]):
        for instance in reservation["Instances"]:
            instancelist.append(instance["InstanceId"])
    return instancelist
Run Code Online (Sandbox Code Playgroud)

现在该方法list_instances_by_tag_value返回一个List. 现在我需要开始EC2 instances. 所以我正在做类似下面的事情

def start_ec_instances(self, instanceids):
    response = ec2client.start_instances(InstanceIds=instanceids)
    return
Run Code Online (Sandbox Code Playgroud)

instanceids从第一个方法返回的列表在哪里。但是ec2client.start_instances只接受String而不是List.

我知道我可以将其转换listString然后解析它。我需要在 instanceID 前面附加 (') 并在每个实例 ID 之间附加逗号 (,)。

问题是,有没有什么简单的方法可以做到这一点,而不是将列表转换为字符串并执行一些append操作?

它需要看起来像 'i-XXXXXX', 'i-XXXXX', 'i-XXXXXXX'

编辑:当我将列表传递给start_instances第一种方法时,它说Invalid type for parameter InstanceIds[0], value: ['i-ssss', 'i-YYYY', 'i-ZZZZ', 'i-KKKK'], type: <class 'list'>, valid types: <class 'str'>

hel*_*loV 5

你更有可能称之为:

response = ec2client.start_instances(InstanceIds=[instanceids])
Run Code Online (Sandbox Code Playgroud)

代替:

response = ec2client.start_instances(InstanceIds=instanceids)
Run Code Online (Sandbox Code Playgroud)