[Ansible plugins] Lookup Plugin 사용 방법

  



Ansible plugins 중 하나인 Lookup plugin에 대해 알아보겠습니다. Lookup plugin은 플레이북 내에서 외부 데이터를 불러오고 이를 Jinja2 템플릿과 함께 활용할 수 있도록 도와주는 기능입니다.

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 plugin은 플레이북 내에서 외부 소스(파일, 데이터베이스, key/value 저장소, API 등)의 데이터를 가져와 Jinja2 템플릿 언어를 통해 활용할 수 있도록 도와주는 기능입니다. 예를 들어, 외부 파일에 접근해 해당 내용을 변수에 저장하고 이를 작업에 사용할 수 있습니다.

이해를 돕기 위해 아래에 몇 가지 사용 예제를 소개하겠습니다. 참고로 Ansible plugins 개념이 생소하신 분들은 이전에 다룬 "플러그인" 글을 먼저 확인하시면 좋습니다.

 

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

여러 종류의 lookup plugin이 제공되며, 이 중에서 ansible.builtin.file 플러그인을 사용해 보겠습니다. 이 플러그인은 "파일의 내용을 읽어온다"고 설명되어 있습니다.

이제 이 플러그인을 어떻게 활용할 수 있는지, 두 가지 예제를 통해 확인해보겠습니다.

 

예제 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

위 예제에서는 ansible.builtin.file lookup 플러그인을 사용하여 file/test_file.txt의 내용을 읽고, 이를 file_contents 변수에 저장합니다. 해당 변수를 출력하면 다음과 같은 결과를 확인할 수 있습니다.

# 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

아래는 해당 파일 내용을 불러와 메시지에 포함시키는 Ansible 플레이북입니다.

# 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은 외부 데이터를 플레이북에서 직접 불러와 활용할 수 있도록 해주는 유용한 기능입니다.

lookup plugin에서 제공하는 다른 플러그인들도 다양하며, 아래 명령어를 통해 전체 목록을 확인할 수 있습니다.

# ansible-doc -t lookup -l

 

 

참고 사이트

 

댓글

이 블로그의 인기 게시물

[Linux] RHEL Local YUM Repository 구성

[Linux Command] sudo command 설명

[Ansible Modules] Fetch module 설명 및 활용