简体   繁体   English

使用 boto3 获取多个 aws 帐户 ec2 库存

[英]Get multiple aws account ec2 inventory using boto3

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.我已经编写了 python boto3 代码来获取 AWS 中的 ec2 清单,并且在同一代码中,我正在修改以将多个 AWS 帐户 ec2 清单列表放入 csv,但我得到的 ec2 output 详细信息仅为最后一个值。 someone help me with the below script to generate multiple AWS ec2 inventory to csv.有人帮我用下面的脚本生成多个 AWS ec2 清单到 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.上面的脚本我只得到了 output 的 stag aws帐户。

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).该循环仅考虑第一行,其他所有内容都将针对profiles的最后一个元素执行(当 for 循环完成时)。 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()

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

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