I have written the python boto3 code to take the ec2 inventory in AWS and in that same code, I am modifying to take multiple AWS accounts ec2 inventory list into csv but in that I am getting the ec2 output details only for last value. someone help me with the below script to generate multiple AWS ec2 inventory to csv.
import boto3
import csv
profiles = ['dev','stag']
for name in profiles:
aws_mag_con=boto3.session.Session(profile_name=name)
ec2_con_re=aws_mag_con.resource(service_name="ec2",region_name="ap-southeast-1")
cnt=1
csv_ob=open("inventory_info.csv","w",newline='')
csv_w=csv.writer(csv_ob)
csv_w.writerow(["S_NO","Instance_Id",'Instance_Type','Architecture','LaunchTime','Privat_Ip'])
for each in ec2_con_re.instances.all():
print(cnt,each,each.instance_id,each.instance_type,each.architecture,each.launch_time.strftime("%Y-%m-%d"),each.private_ip_address)
csv_w.writerow([cnt,each.instance_id,each.instance_type,each.architecture,each.launch_time.strftime("%Y-%m-%d"),each.private_ip_address])
cnt =1
csv_ob.close()
above script I am getting the output of stag aws account only.
CodePudding user response:
This is because your indentation is incorrect. The loop only accounts for the first line and everything else will be executed for the last element of profiles
(when the for loop finishes). It should be:
import boto3
import csv
profiles = ['dev','stag']
for name in profiles:
aws_mag_con=boto3.session.Session(profile_name=name)
ec2_con_re=aws_mag_con.resource(service_name="ec2",region_name="ap-southeast-1")
cnt=1
csv_ob=open("inventory_info.csv","w",newline='')
csv_w=csv.writer(csv_ob)
csv_w.writerow(["S_NO","Instance_Id",'Instance_Type','Architecture','LaunchTime','Privat_Ip'])
for each in ec2_con_re.instances.all():
print(cnt,each,each.instance_id,each.instance_type,each.architecture,each.launch_time.strftime("%Y-%m-%d"),each.private_ip_address)
csv_w.writerow([cnt,each.instance_id,each.instance_type,each.architecture,each.launch_time.strftime("%Y-%m-%d"),each.private_ip_address])
cnt =1
csv_ob.close()