조건문과 반복문으로 태스크 제어

AnsibleBeginner
지금 연습하기

소개

하나의 플레이북은 전체 태스크 목록을 중복하지 않고도 호스트마다 다른 작업을 선택할 수 있습니다. 부울 정책 입력과 OS 팩트를 결합하고 구조화된 목록의 모든 항목을 처리하며 실제 등록된 점검 결과로 독립적인 승인 결정을 내립니다. 실제 파일과 명시적 정리를 통해 선택 및 건너뛰기 동작을 모두 관찰할 수 있습니다.

부울 입력과 팩트로 태스크 선택하기

이 단계에서는 하나의 재사용 가능한 플레이북이 두 호스트에서 다르게 동작하게 하고 정책이 비활성화되면 출력을 명시적으로 제거합니다.

준비된 환경의 web1에만 별도 승인 입력 /home/automation/maintenance-approved가 있습니다. 지금은 이 입력을 그대로 두세요. 첫 정책 결정에는 대신 부울 변수와 발견된 OS 팩트를 사용합니다.

컨트롤러 프로젝트로 이동합니다.

cd /home/labex/project

호스트 변수 파일은 데이터를 각 인벤토리 이름과 연결합니다. YAML 부울 값은 문자열이 아닌 true/false 값으로 유지되도록 따옴표 없이 작성하세요.

cat > host_vars/web1.yml <<'YAML'
maintenance_enabled: true
YAML
cat > host_vars/web2.yml <<'YAML'
maintenance_enabled: false
YAML

when 키워드는 현재 호스트의 부울 표현식을 평가합니다. 표현식을 Jinja 중괄호로 감싸지 마세요. 여기서 and는 활성화된 정책과 Debian 계열 팩트를 모두 요구합니다. not은 부울을 반전하고 or는 두 이유 중 하나로 정리 분기를 선택할 수 있게 합니다.

cat > maintenance.yml <<'YAML'
- name: Apply a host-specific maintenance policy
  hosts: all
  gather_facts: true
  tasks:
    - name: Prepare the common policy directory
      ansible.builtin.file:
        path: /home/automation/maintenance-policy
        state: directory
        mode: "0750"

    - name: Record enabled Debian maintenance
      ansible.builtin.copy:
        dest: /home/automation/maintenance-policy/enabled.txt
        content: "Enabled maintenance\n"
        mode: "0640"
      when: maintenance_enabled and ansible_facts.os_family == "Debian"

    - name: Remove the marker when the policy is disabled
      ansible.builtin.file:
        path: /home/automation/maintenance-policy/enabled.txt
        state: absent
      when: not maintenance_enabled or ansible_facts.os_family != "Debian"
YAML

공통 디렉터리는 두 호스트 모두에 존재합니다. 활성화된 Debian 호스트만 표식 파일을 받으며 반대 조건의 absent 태스크는 정책이 비활성화되면 이를 제거합니다. 생성 태스크를 건너뛰기만 하면 이전 표식이 남으므로 정리는 별도의 원하는 상태 태스크입니다.

정책을 검증하고 적용합니다.

ansible-playbook maintenance.yml --syntax-check
ansible-playbook maintenance.yml

출력에는 web1과 web2의 서로 다른 changed/ok/skipped 결정이 나타나야 합니다. 두 호스트의 실제 표식 메타데이터를 확인합니다.

ansible all -m ansible.builtin.stat -a 'path=/home/automation/maintenance-policy/enabled.txt'

stat은 web1에서 exists true, web2에서 false를 보고해야 합니다. 정리를 연습하려면 두 호스트의 부울을 덮어씁니다. JSON 추가 변수는 부울 false 유형을 보존하며 바깥 작은따옴표는 JSON이 셸에서 해석되지 않게 보호합니다.

ansible-playbook maintenance.yml -e '{"maintenance_enabled":false}'
ansible all -m ansible.builtin.stat -a 'path=/home/automation/maintenance-policy/enabled.txt'

이제 두 표식 모두 없어야 합니다. 임시 덮어쓰기 없이 실행하여 저장된 호스트별 정책을 복원합니다.

ansible-playbook maintenance.yml

web1은 표식을 다시 갖고 web2는 비활성 상태로 유지되어야 합니다. 덮어쓰기는 저장된 호스트 변수 파일을 편집하지 않았습니다.

구조화된 반복문의 모든 항목 적용하기

이 단계에서는 활성화된 호스트에 선언된 모든 항목별로 실제 유지보수 점검 기록을 만듭니다.

YAML 목록에는 대시로 시작하는 여러 항목이 있습니다. 아래 각 항목은 name과 purpose 필드가 있는 매핑입니다. all의 그룹 변수는 이 목록을 두 호스트에 제공하지만 기존 부울 조건이 여전히 출력을 받는 호스트를 결정합니다.

cat > group_vars/all.yml <<'YAML'
maintenance_checks:
  - name: disk
    purpose: Inspect disk space
  - name: logs
    purpose: Inspect application logs
  - name: packages
    purpose: Inspect package state
YAML

loop는 각 목록 항목마다 태스크 하나를 반복합니다. 반복 안에서 item.name과 item.purpose는 해당 항목의 필드를 읽습니다. when 조건은 각 호스트와 항목에 대해 평가됩니다. 앞선 태스크와 들여쓰기를 맞추어 기존 플레이북에 다음 태스크를 덧붙입니다.

cat >> maintenance.yml <<'YAML'

    - name: Prepare checks only for enabled Debian hosts
      ansible.builtin.file:
        path: /home/automation/maintenance-policy/checks
        state: directory
        mode: "0750"
      when: maintenance_enabled and ansible_facts.os_family == "Debian"

    - name: Write every declared maintenance check
      ansible.builtin.copy:
        dest: "/home/automation/maintenance-policy/checks/{{ item.name }}.txt"
        content: |
          host={{ inventory_hostname }}
          check={{ item.name }}
          purpose={{ item.purpose }}
        mode: "0640"
      loop: "{{ maintenance_checks }}"
      when: maintenance_enabled and ansible_facts.os_family == "Debian"

    - name: Remove check outputs when the policy is disabled
      ansible.builtin.file:
        path: /home/automation/maintenance-policy/checks
        state: absent
      when: not maintenance_enabled or ansible_facts.os_family != "Debian"
YAML

정리 태스크는 이전 활성 정책의 오래된 출력을 포함하여 비활성 호스트의 점검 디렉터리 전체를 제거합니다. 반복문은 활성 호스트에 안정적인 콘텐츠와 명시적 권한을 씁니다.

확장된 플레이북을 적용합니다.

ansible-playbook maintenance.yml

web1에는 점검별로 하나씩 세 반복 결과가 있어야 합니다. web2는 쓰기를 건너뛰고 checks 디렉터리가 없어야 합니다. 하나의 성공 항목을 전체 목록의 증거로 여기지 말고 실제 web1 산출물 세 개를 모두 읽으세요.

ansible web1 -m ansible.builtin.command -a 'cat /home/automation/maintenance-policy/checks/disk.txt /home/automation/maintenance-policy/checks/logs.txt /home/automation/maintenance-policy/checks/packages.txt'

각 기록에는 host=web1과 해당 점검 이름 및 목적이 표시되어야 합니다. 비활성 호스트를 독립적으로 점검합니다.

ansible web2 -m ansible.builtin.stat -a 'path=/home/automation/maintenance-policy/checks'

stat 결과는 exists false를 보고해야 합니다. 이 기록은 유지보수 점검 지침을 선언하며 디스크, 로그, 패키지 점검 자체를 실행한 것처럼 가장하지 않습니다.

등록된 점검 결과로 분기하기

이 단계에서는 실제 stat 결과를 독립적인 결정 입력으로 사용하고 전체 정책이 반복 실행에서 안정적인지 확인합니다.

승인 입력은 maintenance_enabled와 별개입니다. stat 태스크는 항상 각 호스트를 점검하고 register는 해당 호스트 결과를 저장합니다. stat.exists 부울은 기존 입력과 누락된 경로를 안전하게 구분합니다. 점검 및 상보적인 출력 태스크를 덧붙입니다.

cat >> maintenance.yml <<'YAML'

    - name: Inspect the independent approval input
      ansible.builtin.stat:
        path: /home/automation/maintenance-approved
      register: approval_info

    - name: Record an existing approval input
      ansible.builtin.copy:
        dest: /home/automation/maintenance-policy/approved.txt
        content: "Approval input exists\n"
        mode: "0640"
      when: approval_info.stat.exists

    - name: Remove the output when approval input is absent
      ansible.builtin.file:
        path: /home/automation/maintenance-policy/approved.txt
        state: absent
      when: not approval_info.stat.exists
YAML

copy 태스크는 등록된 exists 값을 사용합니다. absent 태스크는 반대 경우를 처리하므로 승인 입력이 제거되면 오래된 승인 출력도 제거합니다. 이 분기는 고정 debug 메시지가 아니라 점검한 상태를 기반으로 합니다.

전체 정책을 실행합니다.

ansible-playbook maintenance.yml

준비된 승인 입력은 web1에만 있으므로 approved.txt도 web1에만 있어야 합니다. 두 실제 출력 경로를 확인합니다.

ansible all -m ansible.builtin.stat -a 'path=/home/automation/maintenance-policy/approved.txt'

web1은 exists true, web2는 false를 보고해야 합니다. 플레이북을 반복합니다.

ansible-playbook maintenance.yml

두 요약 행 모두 changed=0, failed=0, unreachable=0을 보고해야 합니다. 조건이 false인 태스크를 건너뛰는 것은 정상이며, 필요한 모든 반복 항목과 선택된 출력은 올바른 콘텐츠로 존재해야 합니다.

요약

호스트별 부울 데이터와 발견한 팩트로 태스크를 선택하고 반복문의 각 매핑을 처리했으며 등록된 stat 메타데이터로 분기했습니다. 생성 건너뛰기가 이전 상태를 되돌린다고 가정하는 대신 반대 조건의 absent 태스크로 오래된 출력을 제거했습니다. 두 호스트는 불필요한 반복 변경 없이 각자의 정책 결과로 수렴했습니다.