Ansible vars_files 를 사용한 구성 관리 방법

AnsibleBeginner
지금 연습하기

소개

이 튜토리얼은 효율적인 구성 관리를 위해 Ansible vars_files를 사용하는 방법을 안내합니다. Ansible 은 간단하고 사람이 읽을 수 있는 YAML 파일을 통해 인프라를 관리하는 강력한 자동화 도구입니다. vars_files 기능을 사용하면 자동화 로직과 별도로 구성 데이터를 유지하여 Ansible 프로젝트를 더 체계적으로 관리하고 유지 관리할 수 있습니다.

이 튜토리얼을 마치면 vars_files를 생성하고 구성하고, 플레이북에 통합하며, 이를 활용하여 다양한 환경을 효과적으로 관리하는 방법을 배우게 됩니다. 이 지식을 통해 더 확장 가능하고 유지 관리 가능한 인프라 자동화를 구축할 수 있습니다.

Ansible 설치 및 첫 번째 vars_file 생성

이 첫 번째 단계에서는 시스템에 Ansible 을 설치하고 구성 데이터를 저장하기 위한 첫 번째 vars_file을 생성합니다.

Ansible 설치

Ubuntu 시스템에 Ansible 을 설치하는 것으로 시작해 보겠습니다.

sudo apt update
sudo apt install -y ansible

설치가 완료되면 Ansible 이 올바르게 설치되었는지 확인합니다.

ansible --version

Ansible 버전 및 구성을 보여주는 다음과 유사한 출력을 볼 수 있습니다.

ansible [core 2.12.x]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/labex/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /home/labex/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.10.x (default, Mar 14 2023, 14:21:35) [GCC 11.3.0]
  jinja version = 3.0.3
  libyaml = True

프로젝트 디렉토리 구조 생성

Ansible 프로젝트에 대한 디렉토리 구조를 생성해 보겠습니다.

mkdir -p ~/project/ansible-vars-demo/vars
cd ~/project/ansible-vars-demo

Ansible vars_files 이해

Ansible vars_files는 플레이북으로 가져올 수 있는 변수 정의를 저장하는 YAML 파일입니다. 이러한 파일을 사용하면 다음을 수행할 수 있습니다.

  1. 자동화 로직에서 구성 데이터 분리
  2. 여러 플레이북에서 동일한 변수 재사용
  3. 서로 다른 환경에 대한 다양한 구성 유지 관리

첫 번째 vars_file 생성

웹 서버 구성 설정을 저장하기 위해 첫 번째 vars_file을 생성해 보겠습니다. WebIDE 를 사용하여 ~/project/ansible-vars-demo/vars/webserver.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Web Server Configuration
http_port: 80
server_name: example.com
document_root: /var/www/html
max_clients: 200

vars_file은 웹 서버를 구성하는 데 사용될 수 있는 네 가지 변수를 정의합니다.

  • http_port: 웹 서버가 수신 대기할 포트
  • server_name: 웹 서버의 도메인 이름
  • document_root: 웹사이트 파일이 저장될 디렉토리
  • max_clients: 동시 클라이언트 연결의 최대 수

WebIDE 에서 이 파일의 모양을 이해하려면 왼쪽의 파일 탐색기로 이동하여 project 폴더, ansible-vars-demo, vars를 차례로 확장하면 webserver.yml 파일이 표시됩니다. 내용을 보거나 편집하려면 클릭하십시오.

인벤토리 파일 생성

다음으로, Ansible 에 관리할 호스트를 알려주기 위해 인벤토리 파일을 생성해야 합니다. 실제 환경에서는 실제 서버 주소가 포함되지만, 이 튜토리얼에서는 localhost 를 사용합니다.

~/project/ansible-vars-demo/inventory.ini에 다음 내용으로 새 파일을 생성합니다.

[webservers]
localhost ansible_connection=local

이 간단한 인벤토리는 로컬 머신만 포함하는 webservers라는 그룹을 정의합니다.

프로젝트 구조 이해

이 시점에서 프로젝트 구조는 다음과 같아야 합니다.

ansible-vars-demo/
├── inventory.ini
└── vars/
    └── webserver.yml

이 기본 구조는 인벤토리 (관리할 호스트) 를 변수 정의 (해당 호스트를 구성하는 방법) 와 분리합니다.

vars_files를 사용하여 기본 플레이북 생성

이제 vars_file을 만들었으므로 이러한 변수를 사용하는 간단한 Ansible 플레이북을 빌드해 보겠습니다. 이는 vars_files에서 구성 데이터를 가져와 사용하는 방법을 보여줍니다.

Ansible 플레이북 이해

Ansible 플레이북은 관리형 호스트에서 실행할 작업 집합을 정의하는 YAML 파일입니다. 플레이북은 Ansible 기능의 핵심이며 복잡한 구성 프로세스를 자동화할 수 있습니다.

간단한 플레이북 생성

vars_file에 정의한 변수를 사용하여 웹 서버를 구성하는 플레이북을 생성해 보겠습니다. ~/project/ansible-vars-demo/webserver_setup.yml에 다음 내용으로 새 파일을 생성합니다.

---
- name: Configure Web Server
  hosts: webservers
  vars_files:
    - vars/webserver.yml

  tasks:
    - name: Display web server configuration
      debug:
        msg: "Web server will be configured with: Port={{ http_port }}, ServerName={{ server_name }}, DocumentRoot={{ document_root }}"

    - name: Create a directory for document root
      file:
        path: "/tmp/{{ document_root }}"
        state: directory
        mode: "0755"

    - name: Create a sample index.html file
      copy:
        content: |
          <html>
            <head>
              <title>Welcome to {{ server_name }}</title>
            </head>
            <body>
              <h1>Welcome to {{ server_name }}</h1>
              <p>This server is configured to handle {{ max_clients }} simultaneous connections.</p>
            </body>
          </html>
        dest: "/tmp/{{ document_root }}/index.html"
        mode: "0644"

이 플레이북이 수행하는 작업을 이해해 보겠습니다.

  1. hosts: webservers - 이 플레이북이 인벤토리의 "webservers" 그룹에 있는 모든 호스트에서 실행되어야 함을 지정합니다.
  2. vars_files: - vars/webserver.yml - vars_file에서 변수를 가져옵니다.
  3. 첫 번째 작업은 debug 모듈을 사용하여 변수를 표시하는 메시지를 표시합니다.
  4. 두 번째 작업은 웹 서버 문서 루트에 사용될 디렉토리 구조를 생성합니다.
  5. 세 번째 작업은 vars_file의 변수를 포함하는 샘플 HTML 파일을 생성합니다.

플레이북 실행

이제 플레이북을 실행하여 실제로 작동하는지 확인해 보겠습니다.

cd ~/project/ansible-vars-demo
ansible-playbook -i inventory.ini webserver_setup.yml

다음과 유사한 출력을 볼 수 있습니다.

PLAY [Configure Web Server] ****************************************************

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

TASK [Display web server configuration] ****************************************
ok: [localhost] => {
    "msg": "Web server will be configured with: Port=80, ServerName=example.com, DocumentRoot=/var/www/html"
}

TASK [Create a directory for document root] ************************************
changed: [localhost]

TASK [Create a sample index.html file] *****************************************
changed: [localhost]

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

결과 확인

플레이북이 예상 파일을 생성했는지 확인해 보겠습니다.

ls -la /tmp/var/www/html/
cat /tmp/var/www/html/index.html

디렉토리 구조와 index.html 파일의 내용을 볼 수 있으며, 여기에는 vars_file의 값이 포함되어야 합니다.

<html>
  <head>
    <title>Welcome to example.com</title>
  </head>
  <body>
    <h1>Welcome to example.com</h1>
    <p>This server is configured to handle 200 simultaneous connections.</p>
  </body>
</html>

워크플로우 이해

지금까지 수행한 작업을 요약해 보겠습니다.

  1. 구성 데이터를 별도의 vars_file(vars/webserver.yml) 에 저장했습니다.
  2. 이 구성 데이터를 가져와 사용하는 플레이북을 생성했습니다.
  3. 변수를 사용하는 작업을 실행하기 위해 플레이북을 실행했습니다.

구성 데이터 (vars_files) 를 자동화 로직 (플레이북) 에서 분리하면 Ansible 코드를 더 쉽게 유지 관리하고 재사용할 수 있습니다. 이제 플레이북 자체를 변경하지 않고 vars_file만 편집하여 구성을 업데이트할 수 있습니다.

여러 vars_files 사용

이제 vars_files의 기본 사항을 이해했으므로 여러 vars_files를 사용하여 다양한 환경을 관리하는 방법을 살펴보겠습니다. 이는 개발, 스테이징 및 프로덕션 환경에 대해 서로 다른 구성을 가질 수 있는 실제 시나리오에서 흔히 사용되는 방식입니다.

환경별 vars_files 생성

다양한 환경에 대한 vars_files를 생성해 보겠습니다. 먼저 개발 환경 구성을 생성해 보겠습니다.

~/project/ansible-vars-demo/vars/dev_environment.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Development Environment Configuration
environment_name: development
debug_mode: true
log_level: debug
backup_frequency: weekly
max_memory: 512MB

다음으로 프로덕션 환경 구성을 생성해 보겠습니다.

~/project/ansible-vars-demo/vars/prod_environment.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Production Environment Configuration
environment_name: production
debug_mode: false
log_level: error
backup_frequency: daily
max_memory: 2048MB

여러 vars_files를 사용하는 플레이북 생성

이제 웹 서버 구성과 환경별 구성을 모두 사용하는 플레이북을 생성해 보겠습니다. ~/project/ansible-vars-demo/environment_setup.yml에 다음 내용으로 새 파일을 생성합니다.

---
- name: Configure Environment
  hosts: webservers
  vars:
    env: dev
  vars_files:
    - vars/webserver.yml
    - "vars/{{ env }}_environment.yml"

  tasks:
    - name: Display environment details
      debug:
        msg: >
          Setting up {{ environment_name }} environment with the following parameters:
          - Web Server: {{ server_name }} on port {{ http_port }}
          - Debug Mode: {{ debug_mode }}
          - Log Level: {{ log_level }}
          - Backup Frequency: {{ backup_frequency }}
          - Max Memory: {{ max_memory }}
          - Max Clients: {{ max_clients }}

    - name: Create environment config file
      copy:
        content: |
          ## Environment Configuration for {{ server_name }}
          ENVIRONMENT={{ environment_name }}
          DEBUG={{ debug_mode }}
          LOG_LEVEL={{ log_level }}
          BACKUP_FREQUENCY={{ backup_frequency }}
          MAX_MEMORY={{ max_memory }}
          HTTP_PORT={{ http_port }}
          MAX_CLIENTS={{ max_clients }}
        dest: "/tmp/{{ environment_name }}_config.env"
        mode: "0644"

이 플레이북은 몇 가지 새로운 개념을 소개합니다.

  1. 플레이북 자체 내에서 변수 env: dev를 설정합니다.
  2. 웹 서버 vars_file과 환경별 vars_file을 모두 포함합니다.
  3. 환경 vars_file 경로에는 변수가 포함됩니다: "vars/{{ env }}_environment.yml", 이는 vars/dev_environment.yml로 평가됩니다.
  4. 작업은 두 vars_files의 변수를 사용합니다.

서로 다른 환경으로 플레이북 실행

먼저 개발 환경 (이미 기본값임) 으로 플레이북을 실행해 보겠습니다.

cd ~/project/ansible-vars-demo
ansible-playbook -i inventory.ini environment_setup.yml

개발 환경 설정을 포함하는 출력을 볼 수 있습니다.

TASK [Display environment details] ********************************************
ok: [localhost] => {
    "msg": "Setting up development environment with the following parameters:\n- Web Server: example.com on port 80\n- Debug Mode: True\n- Log Level: debug\n- Backup Frequency: weekly\n- Max Memory: 512MB\n- Max Clients: 200"
}

이제 동일한 플레이북을 실행하지만 env 변수를 재정의하여 프로덕션 환경을 사용해 보겠습니다.

ansible-playbook -i inventory.ini environment_setup.yml -e "env=prod"

프로덕션 환경 설정을 포함하는 출력을 볼 수 있습니다.

TASK [Display environment details] ********************************************
ok: [localhost] => {
    "msg": "Setting up production environment with the following parameters:\n- Web Server: example.com on port 80\n- Debug Mode: False\n- Log Level: error\n- Backup Frequency: daily\n- Max Memory: 2048MB\n- Max Clients: 200"
}

구성 파일 확인

플레이북이 환경 구성 파일을 생성했는지 확인해 보겠습니다.

cat /tmp/development_config.env
cat /tmp/production_config.env

각각 해당 환경 vars_file의 설정이 있는 두 개의 서로 다른 구성 파일을 볼 수 있습니다.

변수 우선 순위 이해

여러 vars_files를 사용할 때 Ansible 이 변수에 대한 특정 우선 순위를 따른다는 것을 이해하는 것이 중요합니다. 동일한 변수 이름이 여러 위치에 나타나는 경우 나중에 정의된 값이 이전 정의를 재정의합니다.

예를 들어, http_port를 webserver.yml 과 dev_environment.yml 파일 모두에 정의한 경우 dev_environment.yml 의 값이 vars_files 목록에 나중에 포함되기 때문에 우선합니다.

이 동작을 통해 한 파일에서 공통 기본값을 정의한 다음 서로 다른 환경에 대해 특정 값을 재정의할 수 있습니다.

고급 vars_files 기술

이 마지막 단계에서는 Ansible 에서 vars_files를 사용하는 고급 기술을 살펴봅니다. 여기에는 변수를 계층적으로 구성하고 역할 기반 변수 구성을 구현하는 것이 포함됩니다.

변수를 계층적으로 구성

복잡한 프로젝트에서는 변수를 계층적으로 구성하는 것이 유용한 경우가 많습니다. 다음 구조를 만들어 보겠습니다.

  1. 모든 환경에 적용되는 공통 변수
  2. 환경별 변수
  3. 애플리케이션별 변수

먼저 공통 변수 파일을 생성해 보겠습니다.

~/project/ansible-vars-demo/vars/common.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Common variables for all environments
organization: "Example Corp"
admin_email: "admin@example.com"
timezone: "UTC"

다음으로 애플리케이션별 변수를 생성해 보겠습니다.

~/project/ansible-vars-demo/vars/database.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Database application variables
db_port: 3306
db_user: "dbuser"
db_name: "appdb"
db_max_connections: 100

계층적 플레이북 생성

이제 이러한 계층적 변수를 사용하는 방법을 보여주는 플레이북을 생성해 보겠습니다. ~/project/ansible-vars-demo/hierarchical_setup.yml에 다음 내용으로 새 파일을 생성합니다.

---
- name: Hierarchical Variable Demo
  hosts: webservers
  vars:
    env: dev
    app: database
  vars_files:
    - "vars/common.yml"
    - "vars/{{ env }}_environment.yml"
    - "vars/{{ app }}.yml"

  tasks:
    - name: Display hierarchical configuration
      debug:
        msg: >
          Configuration for {{ app }} in {{ environment_name }} environment:
          - Organization: {{ organization }}
          - Admin Email: {{ admin_email }}
          - Timezone: {{ timezone }}
          - Debug Mode: {{ debug_mode }}
          - Log Level: {{ log_level }}
          - DB Port: {{ db_port }}
          - DB User: {{ db_user }}
          - DB Max Connections: {{ db_max_connections }}

    - name: Create hierarchical config file
      copy:
        content: |
          ## {{ organization }} Configuration
          ## {{ environment_name }} Environment

          ## Common Settings
          ADMIN_EMAIL={{ admin_email }}
          TIMEZONE={{ timezone }}

          ## Environment Settings
          DEBUG={{ debug_mode }}
          LOG_LEVEL={{ log_level }}
          BACKUP_FREQUENCY={{ backup_frequency }}

          ## {{ app | capitalize }} Settings
          DB_PORT={{ db_port }}
          DB_USER={{ db_user }}
          DB_NAME={{ db_name }}
          DB_MAX_CONNECTIONS={{ db_max_connections }}
        dest: "/tmp/{{ environment_name }}_{{ app }}_config.conf"
        mode: "0644"

그룹 및 호스트 변수 이해

vars_files 외에도 Ansible 은 group_varshost_vars라는 특수 디렉토리에 변수를 저장하는 것도 지원합니다. 작동 방식을 살펴보겠습니다.

그룹 및 호스트 변수에 대한 디렉토리 구조를 생성합니다.

mkdir -p ~/project/ansible-vars-demo/group_vars
mkdir -p ~/project/ansible-vars-demo/host_vars

이제 'webservers' 그룹에 대한 그룹 변수 파일을 생성합니다.

~/project/ansible-vars-demo/group_vars/webservers.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Variables for all webservers
firewall_enabled: true
ssh_port: 22
monitoring_enabled: true

그리고 'localhost'에 대한 호스트 변수 파일을 생성합니다.

~/project/ansible-vars-demo/host_vars/localhost.yml에 다음 내용으로 새 파일을 생성합니다.

---
## Variables specific to localhost
local_backup_path: "/tmp/backups"
is_development_machine: true

모든 변수 유형을 사용하는 플레이북 생성

모든 변수 유형을 함께 사용하는 방법을 보여주는 최종 플레이북을 생성해 보겠습니다. ~/project/ansible-vars-demo/complete_setup.yml에 다음 내용으로 새 파일을 생성합니다.

---
- name: Complete Variable Demo
  hosts: webservers
  vars:
    env: prod
    app: database
  vars_files:
    - "vars/common.yml"
    - "vars/{{ env }}_environment.yml"
    - "vars/{{ app }}.yml"

  tasks:
    - name: Display complete configuration
      debug:
        msg: >
          Complete configuration for {{ inventory_hostname }}:
          - Organization: {{ organization }}
          - Environment: {{ environment_name }}
          - Debug Mode: {{ debug_mode }}
          - Firewall Enabled: {{ firewall_enabled }}
          - SSH Port: {{ ssh_port }}
          - Monitoring Enabled: {{ monitoring_enabled }}
          - Local Backup Path: {{ local_backup_path }}
          - Is Development Machine: {{ is_development_machine }}

    - name: Create complete config file
      copy:
        content: |
          ## {{ organization }} - {{ environment_name }} Environment
          ## Host: {{ inventory_hostname }}

          ## Common Settings
          ADMIN_EMAIL={{ admin_email }}
          TIMEZONE={{ timezone }}

          ## Environment Settings
          DEBUG={{ debug_mode }}
          LOG_LEVEL={{ log_level }}

          ## Server Settings
          FIREWALL_ENABLED={{ firewall_enabled }}
          SSH_PORT={{ ssh_port }}
          MONITORING_ENABLED={{ monitoring_enabled }}

          ## Host-specific Settings
          LOCAL_BACKUP_PATH={{ local_backup_path }}
          IS_DEVELOPMENT_MACHINE={{ is_development_machine }}

          ## {{ app | capitalize }} Settings
          DB_PORT={{ db_port }}
          DB_USER={{ db_user }}
          DB_NAME={{ db_name }}
        dest: "/tmp/complete_config.conf"
        mode: "0644"

고급 플레이북 실행

계층적 플레이북을 실행해 보겠습니다.

cd ~/project/ansible-vars-demo
ansible-playbook -i inventory.ini hierarchical_setup.yml

세 개의 vars_files 모두의 변수를 포함하는 출력을 볼 수 있습니다.

이제 완전한 플레이북을 실행해 보겠습니다.

ansible-playbook -i inventory.ini complete_setup.yml

이번에는 vars_files, group_varshost_vars의 변수를 포함하는 출력을 볼 수 있습니다.

구성 파일 확인

고급 플레이북에서 생성된 구성 파일을 확인해 보겠습니다.

cat /tmp/dev_database_config.conf
cat /tmp/complete_config.conf

Ansible 에서 변수 우선 순위 이해

여러 변수 소스를 사용할 때 Ansible 은 특정 우선 순위를 따릅니다.

  1. 명령줄 변수 (-e 또는 --extra-vars)
  2. 플레이에 정의된 변수
  3. 포함된 파일 및 역할의 변수
  4. 호스트 팩트
  5. 호스트 변수
  6. 그룹 변수
  7. 인벤토리 변수
  8. 역할 기본 변수

즉, host_vars에 정의된 변수는 group_vars에 정의된 동일한 변수를 재정의하고, 이는 vars_files에 정의된 동일한 변수를 재정의합니다.

이 계층적 구조는 서로 다른 환경, 호스트 및 애플리케이션에서 구성을 관리하는 강력한 방법을 제공합니다.

요약

이 튜토리얼에서는 Ansible vars_files를 사용하여 구성 관리를 효과적으로 수행하는 방법을 배웠습니다. 다음을 수행했습니다.

  1. Ansible 을 설치하고 구성 데이터를 저장하기 위해 첫 번째 vars_file을 생성했습니다.
  2. 구성과 자동화 로직을 분리하기 위해 vars_files를 사용하는 기본 플레이북을 생성하고 실행했습니다.
  3. 여러 vars_files를 사용하여 다양한 환경을 관리했습니다.
  4. 계층적 변수 구성 및 group_varshost_vars 사용을 포함한 고급 기술을 탐구했습니다.

이러한 기술은 확장 가능하고 유지 관리 가능한 Ansible 자동화를 구축하기 위한 견고한 기반을 제공합니다. 구성 데이터를 자동화 로직과 분리함으로써 다음을 수행할 수 있습니다.

  • 서로 다른 환경에서 플레이북을 더 재사용 가능하게 만듭니다.
  • 구성 값을 업데이트하는 프로세스를 단순화합니다.
  • 복잡한 구성을 구조화된 방식으로 관리합니다.
  • 구성 데이터를 명확하게 구성하여 협업을 개선합니다.

Ansible 을 계속 사용하면서 효과적인 변수 관리가 유지 관리 가능한 자동화를 구축하는 데 핵심이라는 점을 기억하십시오. 이 튜토리얼에서 배운 기술은 Ansible 프로젝트가 복잡해짐에 따라 Ansible 프로젝트를 구성하는 데 도움이 될 것입니다.