# finding tagged AWS instances

**URL:** <https://forum.ansible.com/t/finding-tagged-aws-instances/27463>\
**Category:** Ansible Project\
**Tags:** aws\
**Created:** [May 5, 2018, 12:32pm UTC](https://forum.ansible.com/t/finding-tagged-aws-instances/27463 "2018-05-05T12:32:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Karl\_Auer](https://avatars.discourse-cdn.com/v4/letter/k/cc9497/32.png) [@Karl\_Auer](https://forum.ansible.com/u/Karl_Auer)\
**Post date:** [May 5, 2018, 12:32pm UTC](https://forum.ansible.com/t/finding-tagged-aws-instances/27463/1 "2018-05-05T12:32:44Z")

</div>

I am going nuts over what seems to be a very simple thing.

I am using ec2.py. I want a list of the EC2 instance IDs, but only of instances that are tagged with a particular name and value, e.g. MyTag:MyValue.

I know that {{ hostvars.XXX.groups.tag\_MyTag\_MyValue }} exists for any host tagged with MyTag:MyValue.

I also know that {{hostvars.XXX.ec2\_id}} will get me the ID of the instance named XXX.

I can get a list of ALL the instance IDs like this:

- set\_fact:  
ids: 

- set\_fact:  
ids: “{{ ids }} + [‘{{ hostvars[item].ec2\_id }}’ ]”  
with\_items: “{{ hostvars |list }}”

I feel I should be able to add a when: clause after the with\_items: clause, something like:

when: item in hostvars.item.groups.tag\_MyTag\_MyValue

… but that causes an error saying that hostvars has no attribute called “item”. If I try to dereference it (“{{ item }}”) Jinja tells me I can’t use curly braces in when: statements.

Any clues?

Regards, K.

PS: ec2.py directly returns what I am after - it returns the tag groups outside the hostvars. Is there some way I can access that from inside Ansible? Those groups seem only to be accessible via the hosts: directive, which is no use to me as I need this list inside a role.
