Skip to main content

when

Mục đích

Sử dụng when khi cần condition. Ví dụ như khi cần chạy lệnh riêng theo OS Của Host (Ubuntu, CentOS)

Muốn biết key value của host thì lên doc xem hoặc chạy lệnh:

ansible all -m gather_facts
ansible all -m gather_facts | grep distri

Trên terminal sẽ hiện lên như sau:

"ansible_distribution": "Ubuntu"
"ansible_distribution": "CentOS"

Sử dụng trong playbook

install_apache.yaml

---

- hosts: all
  become: true
  tasks:

  - name: apt update repo
    apt:
      update_cache: true
    when: ansible_distribution == "Ubuntu"

  - name: apt install apache
    apt:
      name: apache2
      state: latest
    when: ansible_distribution == "Ubuntu"

  - name: yum update repo
    yum:
      update_cache: true
    when: ansible_distribution in ["CentOS"]

  - name: yum install apache
    yum:
      name: httpd
    when: ansible_distribution in ['CentOS']

remove_apache.yaml

---

- hosts: all
  become: true
  tasks:

  - name: apt remove apache
    apt:
      name: apache2
      state: absent
    when: ansible_distribution in ['Ubuntu']

  - name: yum remove apache
    yum:
      name: httpd
      state: absent
    when: ansible_distribution in ["CentOS"]