Bootstrap FreeKB - Ansible - End a play for certain hosts using meta end_host
Ansible - End a play for certain hosts using meta end_host

Updated:   |  Ansible articles

end_play and end_host are similar, but not exactly the same.

  • end_play will end a play for all hosts
  • end_host will end a play for certain hosts (this article)

end_host can be used to end a play in a playbook for certain hosts in the play. Take for example the following playbook which has 2 plays. In the first play, if the /tmp/foo.txt file does not exist on the host, the play will end for the host.

---
- name: first play
  hosts: all
  tasks:
  - name: use "stat" to determine if /tmp/foo.txt exists on the host
    ansible.builtin.stat:
      path: /tmp/foo.txt
    register: out

  - name: end_host if /tmp/foo.txt does not exist on the host
    meta: end_host
    when: out.stat.exists == False 

  - ansible.builtin.debug:
      msg: "/tmp/foo.txt exists"

- name: second play
  hosts: all
  tasks:
  - ansible.builtin.debug:
      msg: "second play"
...

 

Running this playbook could output something like this, where the play was ended for server2 because /tmp/foo.txt did not exist on server2.

PLAY [first play]

TASK [use "stat" to determine if /tmp/foo.txt exists on the host]
ok: [server1.example.com]
ok: [server2.example.com]

TASK [end_host if /tmp/foo.txt does not exist on the host]
skipping: [server1.example.com]

TASK [debug]
ok: [server1.example.com] => {
    "msg": "/tmp/foo.txt exists"
}

PLAY [second play]

TASK [debug]
ok: [server1.example.com] => {
    "msg": "second play"
}
ok: [server1.example.com] => {
    "msg": "second play"
}

PLAY RECAP
server1.example.com : ok=5   changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
server2.example.com : ok=4   changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1fd6ab in the box below so that we can be sure you are a human.