- ansible playbook을 작성할 때 when을 사용해서 특정 조건,상황을 만족해야만 실행될 수 있도록 설정
- 특정 조건 해당여부를 확인하고 Task 수행
- 논리 조건 사용 가능 : and/or, 부등호
- 부등호 조건 사용 가능 : ==, !=, >=, <=
- Defined 여부 사용 가능: defined, not defined
1. Centos7인지 Cenos6인지, Centos가 아닌지에 따라 ip 출력하는 playbook 코드
# Centos7인지 Cenos6인지, Centos가 아닌지에 따라 ip 출력하는 playbook 코드
$ vi centos_check.yml
---
- name: print ipv4 address for ansible client
hosts: all
#gather_facts: no
tasks:
- name: debug by msg in Centos
debug:
msg:
- "Centos7 ip is {{ ansible_all_ipv4_addresses[0] }}"
when:
- ansible_distribution == 'CentOS'
- ansible_distribution_major_version == '7'
- name: debug by msg in Centos
debug:
msg:
- "Centos6 ip is {{ ansible_all_ipv4_addresses[0] }}"
when:
- ansible_distribution == 'CentOS'
- ansible_distribution_major_version == '6'
- name: debug by msg not in Cenos
debug:
msg:
- "not Centos ip is {{ ansible_all_ipv4_addresses[0] }}"
when:
- ansible_distribution != 'CentOS'
2. centos_check.yml 파일 실행 결과
# 실행
$ ansible_playbook centos_check.yml
PLAY [print ipv4 address for ansible client] ************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [192.168.1.13]
TASK [debug by msg in Centos] *********************************************************************
ok: [192.168.1.13] => {
"msg": [
"Centos7 ip is 192.168.1.13"
]
}
TASK [debug by msg in Centos] **********************************************************************
skipping: [192.168.1.13]
TASK [debug by msg not in Cenos] ********************************************************************
skipping: [192.168.1.13]
PLAY RECAP ***************************************************************************************
192.168.1.13 : ok=2 changed=0 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0