[Ansible plugins] Lookup Plugin 사용 방법

 

Ansible plugins

Ansible plugins 중 Lookup plugin에 대해 알아보겠습니다.

Lookup plugin 이란?

Ansible plugins 중 하나인 lookup plugin은 아래와 같은 설명이 공식 문서에 정의되어 있습니다.

Lookup plugins are an Ansible-specific extension to the Jinja2 templating language. You can use lookup plugins to access data from outside sources (files, databases, key/value stores, APIs, and other services) within your playbooks. Like all templating , lookups execute and are evaluated on the Ansible control machine. Ansible makes the data returned by a lookup plugin available using the standard templating system. You can use lookup plugins to load variables or templates with information from external sources. You can create custom lookup plugins

간단히 정의하면 lookup을 사용하여 플레이북 내에서 외부 소스 (files, databases, key/value stores, APIs, and other services) 같은 데이터들을 불러와서 Jinja2 템플릿 언어로 처리한 결과를 활용할 수 있습니다. 즉 플레이북 내에서 외부의 파일에 접근한 뒤 그 내용을 플레이북 내로 가져와서 활용할 수 있습니다.

이해를 돕기 위해 아래에서 몇 가지 활용 예제를 보겠습니다. 그 전에 혹시 플러그인이 무엇인지 궁금하신 분들은 “플러그인”을 참고하시면 됩니다.

 

Lookup 플러그인 활용

Ansible plugins 중 lookup plugin은 기본적으로 활성화되어 있어 바로 사용할 수 있습니다.

먼저 lookup plugin과 함께 사용할 수 있는 플러그인을 조회해 보도록 하겠습니다.

[root@bastion ~]# ansible-doc -l -t lookup 
ansible.builtin.config              Lookup current Ansible configuration values               
ansible.builtin.csvfile             read data from a TSV or CSV file                          
ansible.builtin.dict                returns key/value pair items from dictionaries            
ansible.builtin.env                 Read the value of environment variables                   
ansible.builtin.file                read file contents                                        
ansible.builtin.fileglob            list files matching a pattern                             
ansible.builtin.first_found         return first file found from list
...

여러 가지 플러그인이 검출되는데 그 중 ‘ansible.builtin.file’을 사용해 보도록 하겠습니다. 해당 플러그인 설명에서는 “파일 콘텐츠를 읽는다” 라고 되어있습니다. 이 플러그인을 어떻게 활용할 수 있는지 2가지 예제를 보도록 하겠습니다.

 

예제1. 파일 내용을 변수의 값으로 사용

test_file.txt 파일에 다음과 같은 내용이 있습니다.

# cat file/test_file.txt 
webadmin

lookup 플러그인을 이용하면 위 파일의 내용을 불러와 바로 변수에 저장할 수 있습니다.

# cat test.yml
---
- name: lookup test
  hosts: node1
  vars:
    file_contents: "{{ lookup('ansible.builtin.file', 'file/test_file.txt') }}"

  tasks:
    - name: pring variable
      ansible.builtin.debug:
        var: file_contents

위와 같이 변수 선언에 lookup을 이용할 수 있습니다. ansible.builtin.file 기능을 통해 file/test_file.txt 파일을 읽고 그 내용을 file_contents라는 변수에 값으로 저장합니다.

file_contents의 변수를 출력해 보면 값이 “webadmin”이 출력됩니다.

# ansible-playbook test.yaml 

PLAY [lookup test] ********************************************************************************

TASK [Gathering Facts] ****************************************************************************
ok: [node1]

TASK [pring variable] *****************************************************************************
ok: [node1] => {
    "file_contents": "webadmin"
}

PLAY RECAP ****************************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

예제2. 파일 내용을 바로 출력

이번에는 변수에 담는 방법이 아닌 바로 파일의 내용을 출력해 보도록 하겠습니다.

test_file.txt 파일에 다음과 같은 내용이 있습니다.

# cat file/test_file.txt 
webadmin

위 파일의 내용을 불러와 메시지를 출력하는 문구에 저장하는 플레이북입니다.

# cat test.yaml
---
- name: lookup test
  hosts: node1
  vars:
    server: webserver

  tasks:
    - name: pring message
      ansible.builtin.debug:
        msg: "{{ server + ' username is ' + lookup('ansible.builtin.file', 'file/test_file.txt') }}"

debug 모듈의 msg 내용을 자세히 분석해 보면 다음과 같이 해석할 수 있습니다.

  • server 변수의 값인 ‘webserver’가 출력됩니다.
  • “+” 기호를 이용하여 문자열을 연결합니다.
  • username is라는 문자열이 출력됩니다.
  • lookup 함수에서 file모듈을 사용하여 file/test_file.txt의 파일 내용을 불러옵니다.

최종적으로 출력되는 문구는 아래와 같습니다.

$ ansible-playbook test.yml 
...
TASK [pring message] ******************************************************************************
ok: [node1] => {
    "msg": "webserver username is webadmin"
}
..

 

마치며

lookup plugins에서 제공하는 ansible.builtin.file 플러그인 하나의 기능 만을 살펴보았습니다. lookup plugin 에서 제공하는 더 많은 기능은 아래의 명령어로 확인해 보실 수 있습니다.

아래의 플러그인 타입별 기능 조회가 생소하신 분들은 플러그인 문서를 확인해 보시면 도움이 됩니다.

# ansible-doc -t lookup -l

 

 

참고 사이트:

 

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

Scroll to Top