# How to get hostvars in dynamically matched playbook?

**URL:** <https://forum.ansible.com/t/how-to-get-hostvars-in-dynamically-matched-playbook/19807>\
**Category:** Ansible Project\
**Created:** [November 19, 2015, 11:29am UTC](https://forum.ansible.com/t/how-to-get-hostvars-in-dynamically-matched-playbook/19807 "2015-11-19T11:29:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nicolas\_Neubauer](https://avatars.discourse-cdn.com/v4/letter/n/ed655f/32.png) [@Nicolas\_Neubauer](https://forum.ansible.com/u/Nicolas_Neubauer)\
**Post date:** [November 19, 2015, 11:29am UTC](https://forum.ansible.com/t/how-to-get-hostvars-in-dynamically-matched-playbook/19807/1 "2015-11-19T11:29:57Z")

</div>

Hi,

I have a dynamic inventory of ec2 hosts that have tags to declare how those should be provisioned. My use-case is as follows:

- 1 EC2 host has a tag “tomcat” and “use”
- 2 EC2 hosts have a tag “mysql”

one of them has a tag “use”  
on of them has a tag “dont-use”

I’d like to provision only the “use” hosts. The challenge is that the tomcat host needs a variable with the ip address of the mysql host. I currently have a playbook that matches on all hosts in the “use” group. Then I apply the roles using when: ‘mysql’ in group\_names, ‘tomcat’ respectively.

roles:

- {  
role: ‘my\_tomcat\_role’,  
mysql\_ip: “WHAT TO PUT HERE?”,  
when: “‘tomcat’ in group\_names”,  
sudo: yes  
}

I have played around with various techniques. Eg. try to dynamically group\_by in the pre tasks to create temp groups of all hosts that have been matched by the playbook but that does not work, because group\_by seems to implicitly only run\_once and thus can not use the group\_names:

- group\_by: key=current\_{{ item }}  
with\_items: “{{ group\_names }}”

The above does not work.

I can not register variables because those will only be available per host, so that does not work either because I don’t know the hostname of the mysql-tagged instance.

Any ideas? Maybe this is a feature request to allow to select hostvars/hosts by the same pattern syntax that is available in the playbook hosts: directive.

Thanks,  
Nicolas
