我已经编写了一个python-boto3脚本来从帐户和区域获取所有aws实例列表。脚本运行正常,并按预期获得csv格式的输出(仅获得一个预留编号下的一个实例,因此剩余实例将丢失)问题是无法正确获取所有aws实例列表。例如,我在aws账户中总共有5个实例
Instance-1 and Instance-2 are with Reservation1 number Instance-3 and Instance-4 are with Reservation2 number Instance-5 is with Reservation3 number I am getting only 3 instances list in csv format instead of 5 instances. please look at the below script , please help me how can I get all aws instances list irrespective of reservation number.output = "Prod.csv"
ec = boto3.client('ec2', config=config, region_name=rg)
def get_tags():
tag_list = []
resp = ec.describe_instances()
tag_result = [['Name','InstanceId','State','bt:product','bt:environment-type','bt:environment-name']]
for ec2 in resp['Reservations']:
tag_list = []
try:
ecName = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'Name')['Value']
tag_list.append(ecName)
except:
ecName = 'Null'
tag_list.append(ecName)
insId = ec2['Instances'][0]['InstanceId']
instanceID = str(insId)
tag_list.append(instanceID)
state = ec2['Instances'][0]['State']['Name']
tag_list.append(state)
try:
btprod = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'bt:product')['Value']
tag_list.append(btprod)
except:
btprod = 'Null'
tag_list.append(btprod)
try:
btenvtype = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'b1:environment-type')['Value']
tag_list.append(btenvtype)
except:
btenvtype = 'Null'
tag_list.append(btenvtype)
try:
btenvname = next(item for item in ec2['Instances'][0]['Tags'] if item['Key'] == 'b1:environment-name')['Value']
tag_list.append(btenvname)
except:
btenvname = 'Null'
tag_list.append(btenvname)
tag_result.append(tag_list)
return tag_result
def main():
tag = get_tags()
with open(output,'w') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
wr.writerows(tag)
log = open(output, 'r').read()发布于 2020-05-31 09:37:19
以下是基于我在your other question中提供的答案的程序的更新版本
import boto3
import csv
output = "Prod.csv"
ec2_client = boto3.client('ec2')
def get_tag(instance, tag_name):
# Find tag on instance
if 'Tags' in instance:
for tag in instance['Tags']:
if tag['Key'] == tag_name:
return tag['Value']
# Not found
return 'Null'
def get_all_tags():
# Add header row
tag_result = [['Name','InstanceId','State','bt:product','bt:environment-type','bt:environment-name']]
response = ec2_client.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
tag_list = []
tag_list.append(get_tag(instance, 'Name'))
tag_list.append(instance['InstanceId'])
tag_list.append(instance['State']['Name'])
for tag in ['bt:product','bt:environment-type','bt:environment-name']:
tag_list.append(get_tag(instance, tag))
tag_result.append(tag_list)
return tag_result
def main():
all_tags = get_all_tags()
with open('output.csv','w') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
wr.writerows(all_tags)
main()https://stackoverflow.com/questions/62104106
复制相似问题