I am running following script in lambda function to describe ec2 instance using tags. But in response I want only instance ID, whereas it retuns lot of info. please guide or anyother way to find out ec2 insatnce id using tags. Thanks
code is:
import boto3
import json
from collections import defaultdict
region = 'us-east-1'
def lambda_handler(event, context):
client = boto3.client('ec2')
running_instances = client.describe_instances(
Filters=[
{
'Name': 'tag:orgid',
'Values': [
'demoxx',
]
},
],
)
return json.loads(json.dumps(running_instances, default=str))
To get instance ids from describe_instances you have to iterate over Reservations, and then over Instances.
Thus, you code could be:
import boto3
import json
from collections import defaultdict
region = 'us-east-1'
def lambda_handler(event, context):
client = boto3.client('ec2')
running_instances = client.describe_instances(
Filters=[
{
'Name': 'tag:orgid',
'Values': [
'demoxx',
]
},
],
)
instance_ids = []
for reservation in running_instances['Reservations']:
for instance in reservation['Instances']:
instance_ids.append(instance['InstanceId'])
return instance_ids
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With