问题
I have written a python-boto3 script to get all aws instances list from an account and region.
the script is running fine, but not giving all instances.
for example ,if n instances are with same Reservation number then getting only one instance under Reservation.
please look at the below script , please help me how can I get all aws instances list irrespective of reservation number.
rg = 'us-west-2'
config = Config(
retries = dict(
max_attempts = 100
)
)
ec = boto3.client('ec2', config=config, region_name=rg)
def get_tags():
tag_list = []
resp = ec.describe_instances()['Reservations']
#resp = ec.describe_instances()
#print(resp)
tag_result = [['Name','InstanceId','State','t1:product','t1:environment-type','t1:environment-name']]
for ec2 in resp:
#for ec2 in resp["Reservation"]:
#print(InstanceId)
tag_list = []
回答1:
In looking at your code, it's not obvious what you're trying to do, but here's some code that goes through all instances and shows their tags:
import boto3
ec2_client = boto3.client('ec2')
response = ec2_client.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
print(instance['InstanceId'])
for tag in instance['Tags']:
print(tag['Key'], tag['Value'])
Here's the equivalent code using the boto3 resource method:
import boto3
ec2_resource = boto3.resource('ec2')
for instance in ec2_resource.instances.all():
print(instance.id)
for tag in instance.tags:
print(tag['Key'], tag['Value'])
Please note that InstanceId
and State
are available directory on the instances object. They are not Tags.
来源:https://stackoverflow.com/questions/62056422/not-getting-all-aws-instances-using-python-boto3-problem-with-reservation