• when 조건절을 사용하면 task 구문이 조건의 수에 따라 필요하게 됨
  • 조건이 많이 필요해서 when을 많이 구성하면 가독성이 떨어짐
  • if 조건절을 사용하면 task 구문을 한개만 사용 가능

1. Centos7인지 Cenos6인지, Centos 아닌지 따라 ip 출력하는 playbook 코드(if 사용)

  • if 문은 평소 파이썬이나 다른 언어에서 사용하는 문법과 큰 차이는 존재하지 않음
  • 변수를 사용하여 상황에 맞게 작성하면 효율적으로 ansible 사용 가능
  • vars: 를 이용해서 linux_version_name 변수에 조건문 값 적용
    $ vi centos_check.yml
    ---
    - name: print ipv4 address for ansible client
      hosts: all
      #gather_facts: no
      vars:
        linux_version_name: "{{ 'centos7' if ansible_distribution == 'CentOS' and ansible_distribution_major_version == '7'
                                 else 'centos6' if ansible_distribution == 'CentOS' and ansible_distribution_major_version == '6'
                                 else 'not_centos' }}"
      tasks:
        - name: debug by msg in OS
          include_tasks: "{{ linux_version_name }}.yml"

2. include_tasks를 통해 불러오는 보조용 yaml 파일 내용

2.1. centos7.yml 파일 내용

$ vi centos7.yml

- name: "Print IP in Centos7"
  debug:
    msg:
      - "Centos7 ip is {{ ansible_all_ipv4_addresses[0] }}"

2.2. centos6.yml 파일 내용

$ vi centos6.yml

- name: "Print IP in Centos6"
  debug:
    msg:
      - "Centos6 ip is {{ ansible_all_ipv4_addresses[0] }}"

2.3. not_centos.yml 파일 내용

$ vi not_centos.yml

- name: "Print IP not in Centos"
  debug:
    msg:
      - "Not Centos ip is {{ ansible_all_ipv4_addresses[0] }}"



3. 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 OS] ************************************************************************
included: /root/centos7.yml for192.168.1.13

TASK [Print IP in Centos7] *************************************************************************
ok: [192.168.1.13] => {
    "msg": [
        "Centos7 ip is 192.168.1.13"
    ]
}

PLAY RECAP *************************************************************************************
192.168.1.13             : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

+ Recent posts