안녕하세요? 정리하는 개발자 워니즈 입니다. 필자가 갑자기 Ansible을 너무 재밌게 하고 있어서 당분간 Ansible 연재를 계속 할 것 같습니다. 지난시간까지는 간단한 playbook 사용법에 대해서 알아봤는데요. 이번시간에는 데이터 변경작업에 대한 이야기를 해보려고 합니다.
Ansible은 보면 템플릿을 잘 활용해야되는데요. 그안에서 데이터를 적절히 조작해서 필요한 작업을 진행할 수 있습니다.
Jinja2 필터는 템플릿에서 데이터를 어떤 형태에서 다른 형태로 바꾸는 작업입니다. 이미 많은 내장 함수를 가지고 있습니다. 이런 필터 기능은 로컬 데이터를 다루는 Ansible의 컨트롤러에서 수행되는 것이며 타겟 머신의 태스크에서 이루어 지는 것이 아닙니다.
#쉘에서 따옴표 추가
- shell: echo {{ string_value | quote }}
#조건식
{{ (name == "John") | ternary('Mr','Ms') }}
#하나의 문자열로 만들기
{{ list | join(" ") }}
#파일의 경로명 `/etc/asdf/foo.txt`에서 파일명 `foo.txt` 만 추출하려면
{{ path | basename }}
#파일 경로에서 디렉토리만 구하기
{{ path | dirname }}
#링크의 실제 경로
{{ path | realpath }}
#주어진 경로의 상대 경로
{{ path | relpath('/etc') }}
#확장자 분리
# with path == 'nginx.conf' the return would be ('nginx', '.conf')
{{ path | splitext }}
#인코딩 문자열 구하기
{{ encoded | b64decode }}
{{ decoded | b64encode }}
#정규 표현식
# convert "ansible" to "able"
{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
# convert "foobar" to "bar"
{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
# convert "localhost:80" to "localhost, 80" using named groups
{{ 'localhost:80' | regex_replace('^(?P.+):(?P\\d+)$', '\\g, \\g') }}
3. Jinja2 테스트 관련 필터
Jinja2의 테스트는 템플릿을 돌려 True 또는 False 결과를 리턴하는가를 보고 판단합니다. Jinja2의 내장 테스트 문서를 참조합니다. 테스트 하는 것은 필터를 이용하는 것과 동일하지만 C(map()) 또는 C(select()) 와 같이 목록에서 항목을 선택하는 것과 같은 목록 처리 필터에도 사용될 수 있습니다.
필터와 마찬가지로 테스트도 로컬 데이터를 테스트하는 Ansible 컨트롤러에서 수행되며, 원격 대상 태스크에서 수행되지는 않습니다.
어떤 그룹이 다른 그룹의 서브셑 또는 수퍼셑 인가를 체크하기 위한 issubset, issuperset 필터가 있습니다.
vars:
a: [1,2,3,4,5]
b: [2,3]
tasks:
- debug: msg="A includes B"
when: a|issuperset(b)
- debug: msg="B is included in A"
when: b|issubset(a)
3-3. 경로 테스트
- debug: msg="path is a directory"
when: mypath|isdir
- debug: msg="path is a file"
when: mypath|is_file
- debug: msg="path is a symlink"
when: mypath|is_link
- debug: msg="path already exists"
when: mypath|exists
- debug: msg="path is {{ (mypath|is_abs)|ternary('absolute','relative')}}"
- debug: msg="path is the same file as path2"
when: mypath|samefile(path2)
- debug: msg="path is a mount"
when: mypath|ismount
3-4. 태스트 결과 테스트
tasks:
- shell: /usr/bin/foo
register: result
ignore_errors: True
- debug: msg="it failed"
when: result|failed
# in most cases you'll want a handler, but if you want to do something right now, this is nice
- debug: msg="it changed"
when: result|changed
- debug: msg="it succeeded in Ansible >= 2.1"
when: result|succeeded
- debug: msg="it succeeded"
when: result|success
- debug: msg="it was skipped"
when: result|skipped
4. 마치며
이번시간에는 앤서블의 Jinja2 필터 사용법에 대해서 알아봤습니다. 대부분의 playbook 예시에서 Jinja2 필터는 상당히 많이 사용되고 있습니다. 기존에 개발자가 코딩으로 만들던 부분을 내장함수를 통해서 손쉽게 데이터를 변환하고 조작할 수 있기에 유용합니다.
다음 이시간에는 조건식/반복문 에 대해서 정리해보도록 하겠습니다.
워니즈 블로그워니즈 깃헙