지구정복
[Ansible] facts & magic variables 본문
참고:
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html
1. 배경
Ansible에서 변수는 두 가지가 있다.
fact, magic variable
Ansible에서는 Ansible 자체나 다른 원격 서버에 대한 정보를 사용할 수 있다.
이때 원격 서버에 대한 정보와 관련된 변수는 fact라고 한다.
예를 들면 A서버의 IP주소를 B서버에서 사용할 수 있다.
그리고 Ansible자체와 관련된 정보는 magic variable이라고 한다.
2. Ansible facts
facts는 ansible 원격 호스트와 관련된 정보를 의미하는데 보통 IP주소, filesystem, OS종류 등등을 의미한다.
'ansible_facts' 라는 변수로 이러한 정보들에 기본적으로 접근 가능
그리고 또한 'ansible_' 이란 prefix를 가지는 facts들을 사용할 수 있다.
만약 사용가능한 모든 ansible facts를 보고 싶으면 아래처럼 playbook을 실행해본다.
- name: Print all available facts
ansible.builtin.debug:
var: ansible_facts
혹은 아래처럼 간단하게 ansible명령어로 실행해본다.
ansible localhost -m ansible.builtin.setup
위 결과중에서 이제 특정 정보들을 필터할 수 있다.
예를 들어서 서버의 첫 번째 disk 정보를 확인하고 싶으면 아래 필터를 사용한다.
{{ ansible_facts['devices']['xvda']['model'] }}
또는
ansible localhost -m ansible.builtin.setup -a 'filter=ansible_devices'
2.1. Caching facts
facts들은 모두 memory에 기본적으로 저장되어 cache된다.
그리고 facts는 ansible 각 서버에서 알아서 수집되고 cache된다.
cache되는 이유는 ansible 각 서버에서 재사용되기 위해.
그래서 예를 들면 A서버에서 B서버에서 수집되고 저장된 facts들을 사용할 수 있다.
{{ hostvars['asdf.example.com']['ansible_facts']['os_family'] }}
추가적으로 caching은 'cache plugin'을 통해서 관리되는데 이는 현재 실행되는 playbook에서 facts로 사용될 정보를 수집하고 메모리에 저장하는 Plugin이다.
현재 실행되는 playbook뿐만 아니라 facts를 계속 보관하고 사용하려면 다른 plugin을 사용해야 한다. (https://docs.ansible.com/ansible/latest/plugins/cache.html#cache-plugins)
2.2. Disabling facts
facts수집기능은 기본적으로 켜져있는데 이를 끌 수 있다.
playbook이 실행될 때 기본적으로 각 ansible 서버에선 facts를 수집한 뒤 playbook을 실행한다.
따라서 ansible playbook의 시간단축 및 성능향상을 위해서라면 끌 수 있다.
특히 굉장히 많은 서버를 관리하는 경우라면 끄는게 좋다.
끄는 방법은 playbook의 아래 내용을 추가한다.
gather_facts: false
2.3. Adding custom facts
내가 원하는 정보를 facts로 만들 수 있다.
아래 모듈을 이용한다.
ansible.builtin.set_fact
예제 playbook.
- name: Set a simple fact
ansible.builtin.set_fact:
my_var: "Hello, World!"
- name: Use the fact
debug:
msg: "The value of my_var is: {{ my_var }}"
facts.d / local facts
1.3 버전부터
개인적으로 사용하고싶은 facts를 playbook에서 정의하는 것 외에 facts.d 라는 디렉터리에 미리 파일로 넣어두거나
동적인 facts의 경우 동적인 facts를 만드는 실행스크립트를 facts.d라는 디렉터리에 넣어두고 사용할 수 있다.
예를들면 facts.d 에 있는 스크립트를 실행하여 모든 유저 리스트를 facts로 만들 수 있다.
이를 사용하기 위해선 먼저 /etc/ansible/facts.d라는 디렉터리를 모든 호스트들에 만든다.
만약 다른 디렉터리를 사용하고 싶으면 fact_path 를 사용하여 다른 디렉터리 경로로 설정하면 된다.
그리고 나서 사용하고자 하는 facts가 담긴 파일을 디렉터리에 안에 넣어준다.
여기서 중요한 점은 모든 파일명은 .fact로 끝나야 한다.
그리고 파일 형식은 JSON, INI, 또는 실행가능한 파일 형태만 된다.
아래는 예제이다.
#디렉터리 생성 $ docker exec -it awx_web bash --login $ mkdir /etc/ansible/facts.d #파일 생성 $ vi /etc/ansible/facts.d/preferences.fact [general] asdf=1 bar=2 |
gather_facts가 true인 상태로 playbook이 실행되면 facts중에 general이란 fact가 추가된 것을 확인할 수 있다.
$ ansible localhost -m ansible.builtin.setup -a "filter=ansible_local" { "ansible_local": { "preferences": { "general": { "asdf" : "1", "bar" : "2" } } } } |
ansible_local 이란 네임스페이스는 facts.d에서 생성된 custom facts와 playbook에서 생성된 facts나 variables와 구분된다.
이때 또 한 가지 알아야 할 점은 ansible_local variable에 있는 key=value 형태의 데이터를 모두 소문자로 변환된다.
예를 들어 XYZ=3이라는 데이터가 있으면 ansible_local에서 읽을 때는 아래와 같이 읽어야 한다.
{{ ansible_local['preferences']['general']['XYZ'] }} |
또한 위에서 말했듯이 dynamic custom facts를 실행스크립트를 이용해서 사용할 수 있다.
예를 들어 ansible 각 호스트에 있는 모든 user 목록을 각 host의 fact로 만들 수 있다.
아래는 순서이고, 모든 ansible hosts에서 진행되어야 한다.
1. custom facts로 만들 JSON데이터를 생성하는 스크립트를 작성하고 테스트한다.
2. 해당 스크립트를 facts.d 디렉터리에 위치시킨다.
3. 스크립트는 .fact 확장자를 가져야 한다.
4. 스크립트는 ansible 실행되는 유저가 실행 권한이 있어야 한다.
5. ansible실행되면 facts를 수집하고 custom facts는 ansible_local에서 확인할 수 있다.
실제로 테스트해본다.
-실행스크립트 생성
$ vim /etc/ansible/facts.d/users.fact #!/bin/bash # Generate a list of users USERS=$(cut -d: -f1 /etc/passwd | jq -R . | jq -s .) # Output JSON formatted data echo "{ \"users\": $USERS }" #실행권한 부여 $ chmod +x /etc/ansible/facts.d/users.fact |
-ansible 실행해서 확인해보기
$ ansible localhost -m ansible.builtin.setup -a "filter=ansible_local" |
3. Magic Variables
magic variables를 이용하면 현재 사용하고 있는 Python version, 사용하고 있는 inventory 내의 hosts나 groups, playbooks이나 roles의 디렉터리들의 정보를 알 수 있다.
그리고 변수명을 지을 때 magic variable의 이름들로 지을 수 없다.
예를들면 environment도 magic variable이다.
주로 사용하는 magic variables는 아래와 같다.
hostvars
groups
group_names
inventory_hostname
그리고 어떤 playbook에서든지 variables를 사용할 수 있다.
hostvars같은 경우 facts에서도 사용가능하지만 facts를 이용하려면 gather_facts 활성화상태여야한다.
대표적인 magic variables는 다음과 같다.
* ansible_play_hosts : 현재 playbook에서 액티브상태인 모든 호스트 목록
* ansible_playbook_python : ansible을 실행하는 파이썬의 경로
* inventory_dir : ansible inventory 호스트 파일이 위치한 경로
* inventory_file : 인벤토리 파일명
* playbook_dir : playbook이 위치한 경로
* role_path : role이 위치한 경로
간단한 예제
---
- name: Example Playbook Using Magic Variables
hosts: localhost
gather_facts: yes
tasks:
- name: Display some informations
debug:
msg: >
Host {{ inventory_hostname }} is running on {{ ansible_distribution }}
OS Family: {{ ansible_os_family }} /
ansible_playbook_python: {{ ansible_playbook_python }} /
inventory_dir: {{ inventory_dir }} /
inventory_file: {{ inventory_file }} /
playbook_dir: {{ playbook_dir }}
'데이터 엔지니어링 정복 > Ansible & AWX' 카테고리의 다른 글
[Ansible&AWX] when, with_items, loop, debug 모듈을 사용한 간단한 예제 (0) | 2025.02.06 |
---|