Ansible 변수 2 | 조회(lookup), 프롬프트(vars_prompt), 필터(Filters)
1. 조회(lookup) 플러그인
조회(lookup) 플러그인은 파일, 인벤토리, 키/값 저장소, API 등 외부 소스에서 데이터를 검색해 변수로 가져올 수 있습니다.
조회 플로그인의 목록은 다음 명령으로 확인할 수 있습니다.
ansible-doc -t lookup -l
다음은 file 조회 플러그인을 이용해 파일의 내용을 변수로 가져오는 예제입니다.
- hosts: databases
vars:
auth_key: "{{ lookup('file', /home/devops/.ssh/id_rsa.pub') }}"
tasks:
- name: set authorized keys
authorized_key:
user: devops
state: present
key: "{{ auth_key }}"
다음은 url 조회 플러그인을 이용해 정보를 변수로 가져오는 예제입니다.
- name: display ip ranges
debug:
msg: "{{ lookup('url', 'https://ip-ranges.amazonaws.com/ip-ranges.json', split_lines=False }}"
2. 프롬프트
플레이북에 vars_prompt 키워드로 변수를 선언하면, 플레이북을 실행하기 전 사용자에게 변수의 값을 입력하도록 요청할 수 있습니다.
민감한 데이터나 자주 변경되는 데이터를 플레이북에 저장하지 않고 사용자가 입력하도록 하는 것입니다. 사용자를 생성하기 위한 패스워드와 같은 민감한 데이터나, 설치하고자 하는 패키지의 버전이 자주 변경되는 경우 버전을 저장하도록 사용할 수 있습니다.
다음은 사용자 생성을 위한 예제입니다.
- hosts: all
vars_prompt:
- name: username
prompt: Enter username
private: no
default: admin
- name: hashed_password
prompt: Enter password
private: yes
encrypt: sha512_crypt
confirm: yes
salt_size: 16
tasks:
- name: creat user
user:
name: "{{ username }}"
password: "{{ hashed_password }}"
- vars_prompt
- name : 변수명
- prompt : 프롬프트에 출력될 문자열
- private : 입력 값이 보이는지 여부
- default : 기본 값
- encrypt : 암호화 / 해시 알고리즘
- confirm : 입력 값을 한 번 더 검증
- salt_size : Salt 길이 (default : 8)
암호화 방식은 Python의 기본 crypt 라이브러리를 사용합니다.
- bcrypt - BCrypt
- md5_crypt - MD5 Crypt
- sha256_crypt - SHA-256 Crypt
- sha512_crypt - SHA-512 Crypt
◆ Passlib 라이브러리가 지원하는 해시 알고리즘 종류
Python의 Passlib 라이브러리를 설치한 경우 더 많은 알고리즘을 지원합니다.
https://passlib.readthedocs.io/en/stable/lib/passlib.hash.html
passlib.hash - Password Hashing Schemes — Passlib v1.7.4 Documentation
Overview The passlib.hash module contains all the password hash algorithms built into Passlib. While each hash has its own options and output format, they all inherit from the PasswordHash base interface. The following pages describe each hash in detail, i
passlib.readthedocs.io
3. 필터(Filters)
필터는 변수에 기본값을 제공하거나, 변수 값의 형식을 변환하고, 일부 변수를 선택적으로 설정하여 변수 값이 누락되거나 정의되지 않은 변수를 관리하는 등 여러가지 데이터를 조작할 수 있습니다.
필터는 변수 선언 뒤에 파이프( | ) 기호를 이용해 필터를 지정합니다.
필터의 종류는 매우 많으나 그 중 몇 가지를 살펴봅시다.
1) 기본값 제공
{{ variable | default('DEFAULT') }}
출력
DEFAULT
2) 필수값 정의
변수만 정의해놓고 값이 없는 경우도 있습니다. mandatory 필터를 사용하면 변수에 필수로 값이 할당되어야 합니다.
{{ variable | mandatory }}
3) 사전(Dictionary) ↔ 목록(List) 데이터 변환
{{ dict | dict2items }} # dict -> list
{{ list| items2dict }} # list -> dict
4) JSON 쿼리
{{ domain_definition | json_query('domain.cluster[*].name') }}
5) IP 주소 필터
prefix을 제외하고 주소만 추출합니다.
{{ '192.0.2.1/24' | ipaddr('address') }}
출력
192.0.2.1
6) 해시 필터
{{ 'test1' | hash('sha1') }}
{{ 'secretpassword' | password_hash('sha256', 'mysecretsalt') }}
inventory의 호스트 이름을 통해 멱등성을 제공할 수 있습니다.
{{ 'secretpassword' | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}
7) 주석 필터
comment 필터를 사용하면 3줄 주석 처리를 수행합니다.
{{ "Plain style (default)" | comment }}
출력
#
# Plain style (default)
#
8) URL 필터
(1)
{{ 'http://user:password@greta.tistory.com:9000/dir/index.html?query=term#fragment' | urlsplit }}
출력
{
"fragment": "fragment",
"hostname": "greta.tistory.com",
"netloc": "user:password@greta.tistory.com:9000",
"password": "password",
"path": "/dir/index.html",
"port": 9000,
"query": "query=term",
"scheme": "http",
"username": "user"
}
(2)
{{ 'http://user:password@greta.tistory.com:9000/dir/index.html?query=term#fragment' | urlsplit('hostname') }}
출력
greta.tistory.com
9) 정규화 표현식 필터
문자열 검색
{{ 'foobar' | regex_search('(foo)') }}
10) 경로 필터
basename은 파일명, dirname은 디렉토리 경로만 추출합니다.
{{ '/etc/asdf/foo.txt' | basename }}
{{ '/etc/asdf/foo.txt' | dirname }}
출력
foo.txt
/etc/asdf
◆ Ansible 필터
https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html
Using filters to manipulate data — Ansible Documentation
Filters let you transform JSON data into YAML data, split a URL to extract the hostname, get the SHA1 hash of a string, add or multiply integers, and much more. You can use the Ansible-specific filters documented here to manipulate your data, or use any of
docs.ansible.com
◆ Jinja2 필터
https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-filters
Template Designer Documentation — Jinja Documentation (3.0.x)
Template Designer Documentation This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Jinja templates. As the template engine is very flexible, the configuration from the application
jinja.palletsprojects.com