I'm trying to generate an inventory from AWS accounts and write it in a single CSV file.
I have 5 accounts like Dev, Test, DevOps, Prepared, and Prod. Normally I generate using the below bash script, this requires some manual tasks again;
#!/bin/bash
reg="ap-south-1"
input="profile.txt" ##This file contain all the profile name which configured on ~/.aws/credentials file
while IFS= read -r line
do
aws ec2 describe-instances --profile ${line} --region ${reg} --query "Reservations[*].Instances[*].[Tags[?Key=='Name']|[0].Value,InstanceId,InstanceType,PrivateIpAddress,State.Name,Platform,Placement.AvailabilityZone]" --output text >> ec2_inventory.csv
done < "$input"
So, here I have written a python boto3 script to generate ec2 inventory;
It's working as expected for a single AWS profile. script below;
import boto3
session = boto3.Session(profile_name='dev')
ec2 = session.client('ec2', region_name='ap-south-1')
response = ec2.describe_instances()
import datetime
import csv
time = datetime.datetime.now().strftime ('%Y-%m-%d-%H-%M-%S')
filename_describe_instances = ('ec2_inventory_me-south-1_' + time + '.csv')
fieldnames = ['Instance_Name','ImageId', 'InstanceId', 'InstanceType', 'Availability_Zone', 'Platform', 'PrivateIpAddress','PublicIpAddress', 'State', 'SubnetId','VpcId', 'Environment', 'AccountId']
with open(filename_describe_instances, 'w', newline='') as csvFile:
writer = csv.writer(csvFile, dialect='excel')
writer.writerow(fieldnames)
for Reserv in response['Reservations']:
for Insta in Reserv['Instances']:
instance_imageid = Insta.get('ImageId', 'NULL')
instance_InstanceId = Insta.get('InstanceId', 'NULL')
instance_InstanceType = Insta.get('InstanceType', 'NULL')
instance_Availability_Zone = Insta['Placement'].get('AvailabilityZone', 'NULL')
instance_Platform = Insta.get('Platform', 'Linux')
instance_Private_IP = Insta.get('PrivateIpAddress', 'NULL')
instance_Public_IP = Insta.get('PublicIpAddress', 'NULL')
instance_State = Insta['State'].get('Name', 'NULL')
instance_Subnet = Insta.get('SubnetId', 'NULL')
instance_VPCID = Insta.get('VpcId', 'NULL')
instance_OwnerId = Reserv.get('OwnerId', 'NULL')
tags_list = []
for n in Insta.get('Tags', 'NULL'):
if n.get('Key', 'NULL') == 'Name':
instance_Name = n.get('Value', 'NULL')
if n.get('Key', 'NULL') == 'Environment':
instance_Environment = n.get('Value', 'NULL')
raw = [instance_Name,
instance_imageid,
instance_InstanceId,
instance_InstanceType,
instance_Availability_Zone,
instance_Platform,
instance_Private_IP,
instance_Public_IP,
instance_State,
instance_Subnet,
instance_VPCID,
instance_Environment,
instance_OwnerId]
writer.writerow(raw)
for o in raw:
o = 'NULL'
raw = []
csvFile.close()
So, could someone help me with this script to generate inventory from multiple AWS accounts and write it in a single CSV file?