Extracting IP of specific EC2 instance from dynamic inventory outside of current hostvars

Hey folks,

Ansible 1.9.3 user here. I’m trying to figure out if there’s a way to obtain the IP of a specific instance from an ec2 dynamic inventory when that instance is NOT part of the current group of hosts being configured. I’m using ec2.py to work with AWS. The way I’m currently identifying an environment and a type of instance in a single AWS account is by the combination of the Environment and Role tags. The assumption is that I’m not hardcoding any of these IPs anywhere.

Let’s say I’m running my applications playbook and those roles need to know the IP of my master database for that specific environment. Right now the only way I can see to obtain that IP is to write a wrapper script around ansible-playbook where I call ec2.py --list and figure out the right intersection of tags. I then pass that IP into ansible-playbook as a global variable through --extra-vars.

Is there a different and less convoluted approach to this? I would be ok with something like (tag_Role_db_master:&tag_Environment_dev)[0].private_ip if that were at all available, but that doesn’t seem to be the case.

Please advise and thank you in advance.

you don't need the host to be in the current list targeted by play,
you can use hostvars['hostanme']['varname'] to access info on ANY host
in the inventory.

as per figuring out the correct hostname you can use
`lookup('inventory_hostname',
'tag_Role_db_master:&tag_Environment_dev')` or
`groups['tag_Role_db_master']|intersection(groups['tag_Environment_dev'])`
to get the lists you want (add [0] for first host in lists)

Thanks for clarifying! The lookup route didn’t work for me, but the groups approach seems to be doing the trick. Here’s what I’m getting from the lookups:

TASK: [debug var=“{{ lookup(‘inventory_hostname’, ‘tag_Role_utilities:&tag_Environment_dev’) }}”] ***
fatal: [172.31.57.124] => Failed to template var=“{{ lookup(‘inventory_hostname’, ‘tag_Role_utilities:&tag_Environment_dev’) }}”: lookup plugin (inventory_hostname) not found

TASK: [debug var=“{{ lookup(‘inventory_hostnames’, ‘tag_Role_utilities:&tag_Environment_dev’) }}”] ***
fatal: [172.31.57.124] => Failed to template var=“{{ lookup(‘inventory_hostnames’, ‘tag_Role_utilities:&tag_Environment_dev’) }}”: inventory_hostnames must be used as a loop. Example: “with_inventory_hostnames: ‘all’”

Cheers.

lookup should work in 2.0 and beyond, but they are both equivalent in the end.