Running a play on hosts identified by a preceding play

33 views
Skip to first unread message

Abhishek R.

unread,
Jan 26, 2016, 1:47:43 PM1/26/16
to Ansible Project
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

Brian Coca

unread,
Jan 28, 2016, 5:48:12 PM1/28/16
to Ansible Project
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
gather_facts: false
tasks:
- group_by: key=new_group
when: inventory_hostname in
hostvars['127.0.0.1']['second_play_hosts'].stdout_lines

#Play2
hosts: new_group
remote_user: some_user
tasks:
- name: random task
shell: echo "Hi"


though the comments might be off by 1 now.
--
Brian Coca
Reply all
Reply to author
Forward
0 new messages