FreeBSD 14
Sponsored Link

Ansible : Use Playbook (when)2024/09/11

 

To use [when], [failed_when], it's possible to write branch condition in Ansible Playbook.

[1] For example, create a Playbook which only if it does not exist [/var/www/html/index.html], create it on target hosts.
freebsd@dlp:~ $
vi playbook_sample.yml
# set boolean with [failed_when],
# create [index.html] if result of boolean is [1]

- hosts: target_servers
  become: yes
  become_method: sudo
  tasks:
  - name: index file exists or not
    shell: test -f /usr/local/www/apache24/data/index.html
    ignore_errors: true
    register: file_exists
    failed_when: file_exists.rc not in [0, 1]

  - name: put index.html
    shell: echo "apache httpd index" > /usr/local/www/apache24/data/index.html
    when: file_exists.rc == 1

freebsd@dlp:~ $
ansible-playbook playbook_sample.yml --ask-become-pass

BECOME password:

PLAY [target_servers] *********************************************************************

TASK [Gathering Facts] ********************************************************************
ok: [10.0.0.52]
ok: [10.0.0.51]

TASK [index file exists or not] ***********************************************************
changed: [10.0.0.52]
changed: [10.0.0.51]

TASK [put index.html] *********************************************************************
skipping: [10.0.0.51]
skipping: [10.0.0.52]

PLAY RECAP ********************************************************************************
10.0.0.51                  : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
10.0.0.52                  : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

# verify

freebsd@dlp:~ $
ansible target_servers -m command -a "ls -l /usr/local/www/apache24/data/index.html"

10.0.0.52 | CHANGED | rc=0 >>
-rw-r--r--  1 root wheel 45 Sep 11 10:29 /usr/local/www/apache24/data/index.html
10.0.0.51 | CHANGED | rc=0 >>
-rw-r--r--  1 root wheel 45 Sep 11 10:29 /usr/local/www/apache24/data/index.html
Matched Content