I have 3 aws accounts and I need to list ec2 instances in all of those accounts using a python script.
Here, I need to pass the aws access key id and aws secret access key in the .env
file.
How do I set it up?
I have 3 aws accounts and I need to list ec2 instances in all of those accounts using a python script.
Here, I need to pass the aws access key id and aws secret access key in the .env
file.
How do I set it up?
You would have to pass the list of your profile names in your code
import boto3
available_profiles = [
'your-profile-name'
]
available_regions = [
'us-east-1',
'eu-west-1'
]
# for each account, each region, create a session and then ec2 client.
# You could also go with creation of a session in account and then only client in each region
for profile in available_profiles:
for region in available_regions:
aws_session = boto3.session.Session(profile_name=profile, region_name=region)
ec2_client = aws_session.client(service_name='ec2', region_name=region)
paginator = ec2_client.get_paginator('describe_instances')
ec2_instances = paginator.paginate()
all_instances = list()
for response in ec2_instances:
for reservation in response.get('Reservations', list()):
for instance in reservation.get('Instances', list()):
instance['account_id'] = reservation['OwnerId']
all_instances.append(instance)