简体   繁体   English

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

[英]AWS Lambda to list EC2 instance id using python boto3

I m trying to list out EC2 instance id using python boto3.我正在尝试使用 python boto3 列出 EC2 实例 ID。 I m new to python.我是python的新手。

Below Code is working fine下面的代码工作正常

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)

Output is输出是

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'}

Now to strip instance id from above output, I have added below code(last 2 lines) and for some reason its not working.现在要从上面的输出中去除实例 ID,我添加了下面的代码(最后 2 行),但由于某种原因它不起作用。

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'])

Error is错误是

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

The loop iteration should be循环迭代应该是

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

since you have a Reservation key at the top level, then an array and objects in the array with the Instances key which itself is yet another array that you then actually iterate.因为您在顶层有一个Reservation键,所以数组和数组中的对象带有Instances键,它本身又是另一个您实际迭代的数组。

Actually instances['Reservations'][0]['Instances'] may not have all instances.实际上instances['Reservations'][0]['Instances']可能不是所有的实例。 Instances are grouped together by security groups.Different security groups means many list elements will be there.实例按安全组分组在一起。不同的安全组意味着将有许多列表元素。 To get every instance in that region, you need to use the code below.要获取该区域中的每个实例,您需要使用以下代码。

Note: ['Reservations'][0]['Instances'] doesn't list all the instances, It only gives you the instances which are grouped by the first security group.注意: ['Reservations'][0]['Instances']没有列出所有的实例,它只给你按第一个安全组分组的实例。 If there are many groups you won't get all 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

I like this approach in case there are multiple reservations:如果有多个保留,我喜欢这种方法:

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

This is the simplest solution I have found to date:这是我迄今为止发现的最简单的解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM