반응형

playbook 작성 시 상단에 gather_facts 여부를 지정할 수가 있다.

playbook 하나로 모든 OS에 대해서 대응을 해야 하는 경우, OS에 대한 종류가 많아 분기문이 많이 들어가야 하는 경우에 ansible_facts를 사용해서 해당 하는 서버의 내부 정보를 수집하고, 그 수집된 정보 중 OS의 정보를 가져와서 해당 값들을 분기문에 추가할 수가 있다.

이런 경우 gather_facts를 yes로 지정해 주어야 한다.

 

분기문에 추가하는 경우는 아래와 같이 심플하게 추가할 수 있다.

---
 - hosts: all
   gather_facts: yes
   tasks:
     - name: check ubuntu14
       debug:
         msg: "ubuntu 14!!!"
       when:
         - ansible_facts['distribution_file_variety'] == "Debian"
         - ansible_facts['distribution_major_version'] == "14"

 

inventory에 linux 장비들만 포함되어 있다면 크게 문제가 없이 실행이 된다.

하지만, windows 머신이 inventory에 하나라도 포함되어 있다면, gather_facts시 linux 에서만 수집할 수 있는 ansible_facts['distribution_file_variety'] 값이 없기 때문에 에러가 발생할 수 있다.

 

이런 경우에는 when 문에 아래와 같이 is defined 문을 추가해줌으로써 해결할 수 있다.

---
 - hosts: all
   gather_facts: yes
   tasks:
     - name: check ubuntu14
       debug:
         msg: "ubuntu 14!!!"
       when:
         - ansible_facts['distribution_file_variety'] is defined
         - ansible_facts['distribution_file_variety'] == "Debian"
         - ansible_facts['distribution_major_version'] == "14"

 

일반적인 프로그래밍 언어의 if문과 같은 매커니즘 이므로, is defined 문은 가장 상단에 위치해야 원하는대로 동작하게 된다.

 

이제 facts를 수집해서 분기문을 처리하는 부분까지는 완료를 했으나, 수집된 facts를 msg 등의 string에 포함시켜서 출력해야 하는 경우가 있을 수 있는데, 이런 경우 ansible에서는 jinja2 엔진을 내장하고 있기 때문에 jinja2 문법을 활용하면 된다.

 

아래는 debug모듈의 msg에 ansible에서 수집한 facts 값을 출력하는 예시를 들어보았다.

---
 - hosts: all
   gather_facts: yes
   tasks:
     - name: check ubuntu14
       debug:
         msg: "ubuntu 14!!! file_variety is {{ ansible_facts['distribution_file_variety'] }} !!"
       when:
         - ansible_facts['distribution_file_variety'] is defined
         - ansible_facts['distribution_file_variety'] == "Debian"
         - ansible_facts['distribution_major_version'] == "14"

 

 

반응형
,