J Balrog J Balrog - 3 months ago 14
Python Question

Do ec2 tag numbers change?

Below is some simple code. What SHOULD pull the key:name tag. However when I add a second tag, it seems to change the order, so 0 isn't always the name???

instances = ec2.instances.filter(Filters=[{'Name':'instance-state-name','Values':['running']}])
for instance in instances:
for tag in instance.tags:
if 'Name'in tag['Key']:
name = tag['Value']
print "Pulling all instance info..."
for instance in instances:
print(instance.id, instance.instance_type,instance.private_ip_address, instance.tags[0].get("Value"))

Answer

Yes. instance.tags is a list and your tag can appear anywhere in the list. If you are trying to get the 'Name', you have to loop through the list. Each element in the list is a dictionary. Check if the key is 'Name' before getting the value.

It sounds complex, but very simple to code. You cannot blindly do instance.tags[0].get("Value")

Comments