# Running a play on hosts identified by a preceding play

**URL:** <https://forum.ansible.com/t/running-a-play-on-hosts-identified-by-a-preceding-play/20354>\
**Category:** Ansible Project\
**Created:** [January 26, 2016, 6:47pm UTC](https://forum.ansible.com/t/running-a-play-on-hosts-identified-by-a-preceding-play/20354 "2016-01-26T18:47:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Abhishek\_R](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Abhishek\_R](https://forum.ansible.com/u/Abhishek_R)\
**Post date:** [January 26, 2016, 6:47pm UTC](https://forum.ansible.com/t/running-a-play-on-hosts-identified-by-a-preceding-play/20354/1 "2016-01-26T18:47:43Z")

</div>

Hi,

Lets say I have a playbook with two plays and the first one determines the hosts on which the second play should run. For instance, lets assume the first play is a local play that has one task. The task runs a script and its output provides the server(s) that the next play should run in.

#Play 1  
hosts: 127.0.0.1  
remote\_user: some\_user  
tasks:

- name: host identifying task  
script: scripts/find\_my\_hosts.sh  
register: second\_play\_hosts

- debug: var=second\_play\_hosts

Lets assume the script output is properly formatted, with multiple hosts colon-separated. All hosts are accounted for in the inventory.

Question is, how do I use the value registered in “ **second\_play\_hosts** ” to run my second play on? It appears a hostvars reference does not work for the “ **hosts** ” element, i.e -

#Play 2  
hosts: “{{ hostvars[‘127.0.0.1’][‘second\_play\_hosts’].stdout }}”

remote\_user: some\_user  
tasks:

- name: random task  
shell: echo “Hi”

- doesn’t appear to work. The execution merely skips the second play stating “skipping: no hosts matched”, because its not interpreting the variable reference and is doing a literal comparison.

Any insight into this is appreciated.

Regards

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [January 28, 2016, 10:48pm UTC](https://forum.ansible.com/t/running-a-play-on-hosts-identified-by-a-preceding-play/20354/2 "2016-01-28T22:48:07Z")

</div>

hostvars are not available to the play, only extra vars.

you can do this by using group\_by: to set a new group, which the 2nd  
play references

#Play1  
...

- hosts: all  
&nbsp;&nbsp;gather\_facts: false  
&nbsp;&nbsp;tasks:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- group\_by: key=new\_group  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;when: inventory\_hostname in  
hostvars['127.0.0.1']['second\_play\_hosts'].stdout\_lines

#Play2  
hosts: new\_group  
remote\_user: some\_user  
tasks:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- name: random task  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;shell: echo "Hi"

though the comments might be off by 1 now.
