jorfus
jorfus

Reputation: 3098

How can I get the value of the EC2 instance tag "Name" with boto?

I'm working from the instance id. I can get the tags, but I can't figure out how filter on both the instance id and the tag "Name" or index in and return the value of the tag called "Name"

I ended up grabbing all tags and iterating over them till I find the one I want, which can't possibly be right.

 tags = conn.get_all_tags({'resource-id': instance_id})
  for tag in tags:
    if 'Name' in tag.name:
      name = tag.value

Upvotes: 2

Views: 2124

Answers (2)

Yonatan Kiron
Yonatan Kiron

Reputation: 2818

You do have a better way:

conn.get_all_tags(filters={'tag-key': 'Name', 'resource-id': instance_id})

Upvotes: 4

Will
Will

Reputation: 24739

I think the way you're doing it is fine. You could always wrap it in a function call as an abstraction:

def get_instance_tag(all_tags, tag_name):
  for tag in all_tags:
    if tag_name == tag.name:
      return tag.value

  return None

name = get_instance_tag(conn.get_all_tags({'resource-id': instance_id}), 'Name')

Note that if tag_name == tag.name: is more accurate than if tag_name in tag.name:.

Upvotes: 0

Related Questions