Study

[Ansible] OS 별 include_tasks 분기

chronosa 2020. 5. 31. 14:06

 

Packer 구성 중 Provisionor로 Ansible를 사용하여 초기 이미지를 셋팅하는 환경을 구성하였다.

이 때 향후 확장성을 고려하여 각 OS 별(예 : Ubuntu 18.04, Redhat 7 등)로 Role에서 각각의 Task를 타도록 구현하고자 하였다.

 

즉, 아래와 같은 Flow로 구성된다.

packer build Ubuntu_18.json  playbook.yml → roles/SSI/tasks/main.yml (OS별 분기) roles/SSI/tasks/Ubuntu_18.yml

 

해당 구성을 위해서는 include_tasks를 사용해주면 된다.

 

Ubuntu_18/roles/SSI/tasks/main.yml

---
# tasks file for SSI
- name: select OS
  include_tasks: "{{ os_dict_major }}.yml"

...

 

Ubuntu_18/roles/SSI/vars/main.yml

---
# vars file for SSI
# example : Ubuntu_18
os_dict_major: "{{ ansible_facts['distribution'] }}_{{ ansible_facts['distribution_major_version'] }}"

...

facts에서 수집된 내용을 통해 OS의 Distribution과 major 버전을 합쳐서 os_dict_major라는 변수를 만들어 이를 활용한다.

 

또한 공통 로직이나 OS Version 별로 구성이 상이한 경우에는 아래와 같이 변수를 사용하면 된다.

 

Ubuntu_18/roles/SSI/tasks/Ubuntu_18.yml

...
- name: modify file permission - 0644
  file:
    path: "{{ item }}"
    owner: root
    group: root
    mode: '0644'
  with_items: "{{ vars[os_dict_major + '_file_0644'] }}" // Ubuntu_18_file_0644
...

 

Ubuntu_18/roles/SSI/vars/main.yml

 

...
Ubuntu_18_file_0644:
  - /etc/passwd
...

 

 

참조

https://stackoverflow.com/questions/29276198/ansible-how-to-construct-a-variable-from-another-variable-and-then-fetch-its-v

 

Ansible: how to construct a variable from another variable and then fetch it's value

Here is my problem I need to use one variable 'target_host' and then append '_host' to it's value to get another variable name whose value I need. If you look at my playbook. Task nbr 1,2,3 fetch ...

stackoverflow.com

https://medium.com/@jyson88/ansible-role-%EC%82%AC%EC%9A%A9-%EB%B0%A9%EB%B2%95-1793da8a452e

 

Ansible Role 사용 방법

Ansible을 처음 입문 하였을 때, playbook 만드는 거에 대해 흥미를 느낍니다. 상당히 재밌습니다.

medium.com

 

'Study' 카테고리의 다른 글

Troubleshooting - ERR_CONNECTION_RESET 해결 기록  (0) 2021.02.02
Django Tutorial  (0) 2020.08.30
AWS Lambda/Kinesis Stream Best Practice  (0) 2020.06.07
Python Testing 기법 기초 내용 정리  (0) 2020.06.07