AWS Lambda使用python boto3列出EC2实例ID

时间:2020-11-12 09:47:53

标签: python amazon-web-services aws-lambda boto3

我正在尝试使用python boto3列出EC2实例ID。我是python的新手。

以下代码运行正常

import boto3
region = 'ap-south-1'
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    print('Into DescribeEc2Instance')
    instances = ec2.describe_instances(Filters=[{'Name': 'instance-type', 'Values': ["t2.micro", "t3.micro"]}])
    print(instances)

输出为

START RequestId: bb4e9b27-db8e-49fe-85ef-e26ae53f1308 Version: $LATEST
Into DescribeEc2Instance
{'Reservations': [{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 'ImageId': 'ami-052c08d70def62', 'InstanceId': 'i-0a22a6209740df', 'InstanceType': 't2.micro', 'KeyName': 'testserver', 'LaunchTime': datetime.datetime(2020, 11, 12, 8, 11, 43, tzinfo=tzlocal()), 'Monitoring': {'State': 'disabled'}

现在要从上面的输出中删除实例ID,我在下面的代码(最后两行)中添加了代码,由于某种原因它不起作用。

import boto3
region = 'ap-south-1'
instance = []
ec2 = boto3.client('ec2', region_name=region)

    def lambda_handler(event, context):
        print('Into DescribeEc2Instance')
        instances = ec2.describe_instances(Filters=[{'Name': 'instance-type', 'Values': ["t2.micro", "t3.micro"]}])
        print(instances)
        for ins_id in instances['Instances']:
                print(ins_id['InstanceId'])

错误是

{
  "errorMessage": "'Instances'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n    for ins_id in instances['Instances']:\n"
  ]
}

4 个答案:

答案 0 :(得分:3)

循环迭代应该是

for ins_id in instances['Reservations'][0]['Instances']:

因为您在顶层有一个Reservation键,所以使用Instances键本身又是另一个要实际迭代的数组,因此该数组和该数组中的对象。

答案 1 :(得分:2)

实际上instances['Reservations'][0]['Instances']可能没有所有实例。实例按安全组分组。不同的安全组意味着将有许多列表元素。要获取该区域中的每个实例,您需要使用以下代码。

注意:['Reservations'][0]['Instances']不会列出所有实例,它只为您提供按第一个安全组分组的实例。如果群组很多,您将不会获得所有实例。

import boto3
region = 'ap-south-1'

ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    instance_ids = []
    response = ec2.describe_instances(Filters=[{'Name': 'instance-type', 'Values': ["t2.micro", "t3.micro"]}])
    instances_full_details = response['Reservations']
    for instance_detail in instances_full_details:
        group_instances = instance_detail['Instances']

        for instance in group_instances:
            instance_id = instance['InstanceId']
            instance_ids.append(instance_id)
    return instance_ids

答案 2 :(得分:0)

在有多个保留的情况下,我喜欢这种方法:

response = ec2.describe_instances()
for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        print(instance['InstanceId'])

答案 3 :(得分:0)

这是我迄今为止找到的最简单的解决方案:

ec2 = boto3.resource('ec2')
ids= [instance.id for instance in ec2.instances.all()]