CentOS Stream 8
Sponsored Link

Ansible : Playbook を利用する (条件)2021/06/16

 
[when], [failed_when] を利用することで、条件分岐が可能となります。
[1] 以下の例は、管理対象ホストに [/var/www/html/index.html] がない場合のみ、ファイルを作成する Playbook です。
[cent@dlp ~]$
vi playbook_sample.yml
# [failed_when] でタスクの結果を判定し、

# [when] で結果が失敗(=1) の場合は [index.html] を作成

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

  - name: put index.html
    shell: echo "httpd index" > /var/www/html/index.html
    when: file_exists.rc == 1

[cent@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.51]
changed: [10.0.0.52]

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

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

# 確認

[cent@dlp ~]$
curl 10.0.0.51

httpd index
[cent@dlp ~]$
curl 10.0.0.52

httpd index
関連コンテンツ