소개
Ansible 은 복잡한 인프라 및 애플리케이션 배포 관리를 단순화하는 널리 사용되는 IT 자동화 도구입니다. 이 튜토리얼에서는 Ansible 플레이북을 통해 실행된 스크립트의 출력을 캡처하는 방법을 살펴봅니다. 이 기능은 자동화 작업의 결과를 모니터링, 디버깅 및 분석하는 데 필수적입니다. 이 랩을 마치면 Ansible 워크플로우에서 스크립트 출력을 캡처하고 활용하는 다양한 기술을 이해하게 될 것입니다.
Ansible 환경 설정
Ansible 로 스크립트 출력을 캡처하기 전에 기본적인 Ansible 환경을 설정해야 합니다. 여기에는 필요한 디렉토리 구조와 구성 파일을 만드는 것이 포함됩니다.
Ansible 기본 사항 이해
Ansible 은 대상 호스트에 연결하여 모듈이라고 하는 작은 프로그램을 푸시하여 작동합니다. 이러한 모듈은 대상 호스트에서 실행되고 완료되면 제거됩니다. Ansible 은 에이전트리스 (agent-less) 방식으로, 관리되는 노드에 특별한 소프트웨어를 설치할 필요가 없습니다.
프로젝트 디렉토리와 필요한 Ansible 파일을 만들어 보겠습니다.
mkdir -p ~/project/ansible-output-demo/scripts
cd ~/project/ansible-output-demo
이제 간단한 인벤토리 파일을 만들어 보겠습니다. Ansible 에서 인벤토리 파일은 플레이북의 명령, 모듈 및 작업이 작동하는 호스트 및 호스트 그룹을 정의합니다.
코드 편집기를 사용하여 인벤토리 파일을 만듭니다.
- IDE 의 왼쪽 상단 모서리에 있는 "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
~/project/ansible-output-demo디렉토리에inventory로 저장합니다.
inventory 파일에 다음 내용을 추가합니다.
[local]
localhost ansible_connection=local
이 인벤토리 파일은 로컬 머신에서 Ansible 을 실행할 것임을 지정합니다.
다음으로, 캡처할 출력을 생성하는 간단한 스크립트를 만들어 보겠습니다. 이 스크립트는 다음을 수행합니다.
- 일부 시스템 정보를 출력합니다.
- 일부 표준 출력을 생성합니다.
- 일부 표준 오류 출력을 생성합니다.
scripts 디렉토리에 info.sh라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
~/project/ansible-output-demo디렉토리에scripts/info.sh로 저장합니다.
info.sh 파일에 다음 내용을 추가합니다.
#!/bin/bash
## Print system information
echo "=== System Information ==="
echo "Hostname: $(hostname)"
echo "Date: $(date)"
echo "Kernel: $(uname -r)"
echo "Memory:"
free -h
## Generate some standard output
echo "=== Standard Output ==="
echo "This is standard output"
echo "Hello from the script!"
## Generate some standard error
echo "=== Standard Error ===" >&2
echo "This is standard error" >&2
echo "An example error message" >&2
## Exit with a specific code
exit 0
이제 스크립트를 실행 가능하게 만듭니다.
chmod +x ~/project/ansible-output-demo/scripts/info.sh
스크립트를 직접 실행하여 어떤 출력을 생성하는지 확인해 보겠습니다.
~/project/ansible-output-demo/scripts/info.sh
시스템 정보, 표준 출력 메시지 및 표준 오류 메시지가 포함된 출력을 볼 수 있습니다.
이제 기본적인 환경이 설정되었습니다. 다음 단계에서는 이 스크립트를 실행하고 출력을 캡처하는 Ansible 플레이북을 만들 것입니다.
Ansible 를 사용한 기본 출력 캡처
이제 환경을 설정했으므로 스크립트를 실행하고 출력을 캡처하는 간단한 Ansible 플레이북을 만들어 보겠습니다.
기본 플레이북 만들기
Ansible 에서 플레이북은 원격 호스트에서 실행할 작업 집합을 정의하는 YAML 파일입니다. info.sh 스크립트를 실행하고 register 키워드를 사용하여 출력을 캡처하는 플레이북을 만들어 보겠습니다.
~/project/ansible-output-demo 디렉토리에 capture_output.yml이라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
~/project/ansible-output-demo디렉토리에capture_output.yml로 저장합니다.
capture_output.yml 파일에 다음 내용을 추가합니다.
---
- name: Capture Script Output
hosts: local
gather_facts: no
tasks:
- name: Execute the info.sh script
command: "{{ playbook_dir }}/scripts/info.sh"
register: script_output
- name: Display the script output
debug:
var: script_output.stdout
이 플레이북을 살펴보겠습니다.
- 플레이북은 인벤토리에 정의된
local그룹을 대상으로 합니다. - 첫 번째 작업은
command모듈을 사용하여info.sh스크립트를 실행합니다. register키워드는 명령의 출력을script_output이라는 변수에 저장합니다.- 두 번째 작업은
debug모듈을 사용하여 스크립트의 표준 출력 (stdout) 을 표시합니다.
플레이북 실행
이제 플레이북을 실행하여 스크립트 출력을 캡처하고 표시하는 방법을 살펴보겠습니다.
cd ~/project/ansible-output-demo
ansible-playbook -i inventory capture_output.yml
다음과 유사한 출력을 볼 수 있습니다.
PLAY [Capture Script Output] *******************************************
TASK [Execute the info.sh script] **************************************
changed: [localhost]
TASK [Display the script output] ***************************************
ok: [localhost] => {
"script_output.stdout": "=== System Information ===\nHostname: ubuntu\nDate: Tue Oct 17 12:34:56 UTC 2023\nKernel: 5.15.0-1031-aws\nMemory:\n total used free shared buff/cache available\nMem: 7.7Gi 1.2Gi 5.2Gi 12Mi 1.3Gi 6.3Gi\nSwap: 0B 0B 0B\n=== Standard Output ===\nThis is standard output\nHello from the script!"
}
PLAY RECAP ************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
표준 출력만 표시되는 것을 확인하세요. script_output.stdout만 표시하도록 요청했기 때문에 표준 오류 (stderr) 출력은 표시되지 않습니다.
출력 가독성 향상
출력은 단일 문자열로 읽기가 약간 어렵습니다. stdout_lines 속성을 사용하여 출력을 더 읽기 쉬운 형식으로 표시하도록 플레이북을 수정해 보겠습니다. 이 속성은 출력을 줄 목록으로 표시합니다.
capture_output.yml 파일을 편집하고 두 번째 작업을 다음과 같이 수정합니다.
- name: Display the script output
debug:
var: script_output.stdout_lines
플레이북을 다시 실행합니다.
ansible-playbook -i inventory capture_output.yml
이제 각 줄이 개별적으로 표시되어 출력이 더 읽기 쉬워야 합니다.
TASK [Display the script output] ***************************************
ok: [localhost] => {
"script_output.stdout_lines": [
"=== System Information ===",
"Hostname: ubuntu",
"Date: Tue Oct 17 12:34:56 UTC 2023",
"Kernel: 5.15.0-1031-aws",
"Memory:",
" total used free shared buff/cache available",
"Mem: 7.7Gi 1.2Gi 5.2Gi 12Mi 1.3Gi 6.3Gi",
"Swap: 0B 0B 0B",
"=== Standard Output ===",
"This is standard output",
"Hello from the script!"
]
}
이 형식은 출력을 훨씬 더 쉽게 읽고 사용할 수 있도록 합니다. 다음 단계에서는 다양한 유형의 출력을 캡처하고 표시하는 방법을 살펴보겠습니다.
다양한 유형의 출력 캡처
이전 단계에서 스크립트의 표준 출력을 캡처하고 표시했습니다. 그러나 스크립트를 실행할 때 캡처하려는 여러 유형의 출력이 있습니다.
- 표준 출력 (stdout): 스크립트의 일반 출력
- 표준 오류 (stderr): 오류 메시지 및 경고
- 반환 코드 (rc): 스크립트의 종료 상태 (0 은 일반적으로 성공을 의미하고, 0 이 아닌 값은 오류를 나타냄)
세 가지 유형의 출력을 모두 캡처하고 표시하는 새 플레이북을 만들어 보겠습니다.
~/project/ansible-output-demo 디렉토리에 capture_all_output.yml이라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
capture_all_output.yml로 저장합니다.
capture_all_output.yml 파일에 다음 내용을 추가합니다.
---
- name: Capture All Types of Script Output
hosts: local
gather_facts: no
tasks:
- name: Execute the info.sh script
command: "{{ playbook_dir }}/scripts/info.sh"
register: script_output
- name: Display standard output
debug:
msg: "Standard Output (stdout):"
- name: Display stdout content
debug:
var: script_output.stdout_lines
- name: Display standard error
debug:
msg: "Standard Error (stderr):"
- name: Display stderr content
debug:
var: script_output.stderr_lines
- name: Display return code
debug:
msg: "Return Code: {{ script_output.rc }}"
이 플레이북은 스크립트를 실행한 다음 다음을 표시합니다.
script_output.stdout_lines를 사용하여 표준 출력script_output.stderr_lines를 사용하여 표준 오류script_output.rc를 사용하여 반환 코드
향상된 플레이북 실행
새 플레이북을 실행해 보겠습니다.
cd ~/project/ansible-output-demo
ansible-playbook -i inventory capture_all_output.yml
세 가지 유형의 출력이 모두 포괄적으로 표시되는 것을 볼 수 있습니다.
PLAY [Capture All Types of Script Output] *****************************
TASK [Execute the info.sh script] *************************************
changed: [localhost]
TASK [Display standard output] ****************************************
ok: [localhost] => {
"msg": "Standard Output (stdout):"
}
TASK [Display stdout content] *****************************************
ok: [localhost] => {
"script_output.stdout_lines": [
"=== System Information ===",
"Hostname: ubuntu",
"Date: Tue Oct 17 12:40:22 UTC 2023",
"Kernel: 5.15.0-1031-aws",
"Memory:",
" total used free shared buff/cache available",
"Mem: 7.7Gi 1.2Gi 5.2Gi 12Mi 1.3Gi 6.3Gi",
"Swap: 0B 0B 0B",
"=== Standard Output ===",
"This is standard output",
"Hello from the script!"
]
}
TASK [Display standard error] *****************************************
ok: [localhost] => {
"msg": "Standard Error (stderr):"
}
TASK [Display stderr content] *****************************************
ok: [localhost] => {
"script_output.stderr_lines": [
"=== Standard Error ===",
"This is standard error",
"An example error message"
]
}
TASK [Display return code] ********************************************
ok: [localhost] => {
"msg": "Return Code: 0"
}
PLAY RECAP **********************************************************
localhost : ok=6 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
이제 스크립트에서 모든 유형의 출력을 볼 수 있습니다.
- 표준 출력은 시스템 정보와 일반 메시지를 표시합니다.
- 표준 오류는 오류 메시지를 표시합니다.
- 반환 코드는 0 으로, 성공적인 실행을 나타냅니다.
오류가 있는 스크립트 만들기
오류를 생성하고 0 이 아닌 종료 코드를 반환하여 Ansible 이 이를 처리하는 방식을 확인하는 스크립트를 만들어 보겠습니다.
scripts 디렉토리에 error.sh라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
scripts/error.sh로 저장합니다.
error.sh 파일에 다음 내용을 추가합니다.
#!/bin/bash
## Print some standard output
echo "Starting error demonstration script"
echo "This will appear in stdout"
## Print some standard error
echo "This will appear in stderr" >&2
echo "Error: Something went wrong!" >&2
## Exit with a non-zero code to indicate error
exit 1
스크립트를 실행 가능하게 만듭니다.
chmod +x ~/project/ansible-output-demo/scripts/error.sh
이제 이 스크립트를 실행하고 오류를 처리하는 플레이북을 만들어 보겠습니다. handle_errors.yml이라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
handle_errors.yml로 저장합니다.
handle_errors.yml 파일에 다음 내용을 추가합니다.
---
- name: Handle Script Errors
hosts: local
gather_facts: no
tasks:
- name: Execute the error script
command: "{{ playbook_dir }}/scripts/error.sh"
register: script_output
ignore_errors: yes
- name: Display standard output
debug:
var: script_output.stdout_lines
- name: Display standard error
debug:
var: script_output.stderr_lines
- name: Display return code
debug:
msg: "Return Code: {{ script_output.rc }}"
- name: Check if script failed
debug:
msg: "The script failed with return code {{ script_output.rc }}"
when: script_output.rc != 0
ignore_errors: yes가 추가된 것을 확인하세요. 이는 명령이 실패하더라도 (0 이 아닌 종료 코드를 반환) Ansible 이 플레이북 실행을 계속하도록 지시합니다.
이 플레이북을 실행해 보겠습니다.
ansible-playbook -i inventory handle_errors.yml
다음과 유사한 출력을 볼 수 있습니다.
PLAY [Handle Script Errors] *******************************************
TASK [Execute the error script] ***************************************
changed: [localhost]
TASK [Display standard output] ****************************************
ok: [localhost] => {
"script_output.stdout_lines": [
"Starting error demonstration script",
"This will appear in stdout"
]
}
TASK [Display standard error] *****************************************
ok: [localhost] => {
"script_output.stderr_lines": [
"This will appear in stderr",
"Error: Something went wrong!"
]
}
TASK [Display return code] ********************************************
ok: [localhost] => {
"msg": "Return Code: 1"
}
TASK [Check if script failed] *****************************************
ok: [localhost] => {
"msg": "The script failed with return code 1"
}
PLAY RECAP **********************************************************
localhost : ok=5 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
이 예제는 다음을 수행하는 방법을 보여줍니다.
- 오류를 생성하는 스크립트에서 출력 캡처
- 오류에도 불구하고 플레이북 실행 계속
- 스크립트의 반환 코드를 기반으로 작업을 조건부로 실행
다음 단계에서는 Ansible 에서 스크립트 출력을 사용하는 더 고급 사용 사례와 모범 사례를 살펴보겠습니다.
고급 출력 처리 및 실제 사용 사례
이제 다양한 유형의 출력을 캡처하는 방법을 이해했으므로 Ansible 에서 스크립트 출력을 처리하고 활용하기 위한 몇 가지 고급 기술을 살펴보겠습니다.
필터를 사용한 출력 구문 분석
Ansible 은 스크립트 출력을 조작하고 특정 정보를 추출할 수 있는 다양한 필터를 제공합니다. 이 섹션에서는 몇 가지 일반적인 필터링 기술을 살펴보겠습니다.
~/project/ansible-output-demo 디렉토리에 parse_output.yml이라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
parse_output.yml로 저장합니다.
먼저 구문 분석할 수 있는 구조화된 출력을 생성하는 스크립트를 만들어 보겠습니다. system_stats.sh라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
scripts/system_stats.sh로 저장합니다.
system_stats.sh 파일에 다음 내용을 추가합니다.
#!/bin/bash
## Display CPU info
echo "CPU_MODEL: $(grep 'model name' /proc/cpuinfo | head -1 | cut -d ':' -f2 | xargs)"
echo "CPU_CORES: $(grep -c 'processor' /proc/cpuinfo)"
## Display memory info in GB
mem_total=$(free -g | grep Mem | awk '{print $2}')
echo "MEMORY_GB: $mem_total"
## Display disk usage
disk_usage=$(df -h / | tail -1 | awk '{print $5}' | tr -d '%')
echo "DISK_USAGE_PCT: $disk_usage"
## Display load average
load_avg=$(uptime | awk -F'load average: ' '{print $2}' | cut -d, -f1)
echo "LOAD_AVG: $load_avg"
exit 0
스크립트를 실행 가능하게 만듭니다.
chmod +x ~/project/ansible-output-demo/scripts/system_stats.sh
이제 이 스크립트를 실행하고 출력을 캡처한 다음 특정 정보를 추출하기 위해 구문 분석하는 플레이북을 만들어 보겠습니다.
parse_output.yml 파일에 다음 내용을 추가합니다.
---
- name: Parse Script Output
hosts: local
gather_facts: no
tasks:
- name: Execute the system_stats.sh script
command: "{{ playbook_dir }}/scripts/system_stats.sh"
register: stats_output
- name: Display raw output
debug:
var: stats_output.stdout_lines
- name: Parse CPU model
set_fact:
cpu_model: "{{ stats_output.stdout | regex_search('CPU_MODEL: (.+)', '\\1') | first }}"
- name: Parse CPU cores
set_fact:
cpu_cores: "{{ stats_output.stdout | regex_search('CPU_CORES: (\\d+)', '\\1') | first }}"
- name: Parse memory
set_fact:
memory_gb: "{{ stats_output.stdout | regex_search('MEMORY_GB: (\\d+)', '\\1') | first }}"
- name: Parse disk usage
set_fact:
disk_usage: "{{ stats_output.stdout | regex_search('DISK_USAGE_PCT: (\\d+)', '\\1') | first }}"
- name: Parse load average
set_fact:
load_avg: "{{ stats_output.stdout | regex_search('LOAD_AVG: ([0-9.]+)', '\\1') | first }}"
- name: Display parsed information
debug:
msg: |
Parsed system information:
- CPU Model: {{ cpu_model }}
- CPU Cores: {{ cpu_cores }}
- Memory (GB): {{ memory_gb }}
- Disk Usage (%): {{ disk_usage }}
- Load Average: {{ load_avg }}
이 플레이북은 다음을 수행합니다.
system_stats.sh스크립트를 실행합니다.- 원시 출력을 표시합니다.
regex_search필터를 사용하여 출력에서 특정 정보를 추출합니다.- 추출된 정보를 변수에 저장합니다.
- 구문 분석된 정보를 구조화된 형식으로 표시합니다.
이 플레이북을 실행해 보겠습니다.
cd ~/project/ansible-output-demo
ansible-playbook -i inventory parse_output.yml
다음과 유사한 출력을 볼 수 있습니다.
PLAY [Parse Script Output] ********************************************
TASK [Execute the system_stats.sh script] *****************************
changed: [localhost]
TASK [Display raw output] *********************************************
ok: [localhost] => {
"stats_output.stdout_lines": [
"CPU_MODEL: Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz",
"CPU_CORES: 2",
"MEMORY_GB: 7",
"DISK_USAGE_PCT: 58",
"LOAD_AVG: 0.08"
]
}
TASK [Parse CPU model] ************************************************
ok: [localhost]
TASK [Parse CPU cores] ************************************************
ok: [localhost]
TASK [Parse memory] ***************************************************
ok: [localhost]
TASK [Parse disk usage] ***********************************************
ok: [localhost]
TASK [Parse load average] *********************************************
ok: [localhost]
TASK [Display parsed information] *************************************
ok: [localhost] => {
"msg": "Parsed system information:\n- CPU Model: Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz\n- CPU Cores: 2\n- Memory (GB): 7\n- Disk Usage (%): 58\n- Load Average: 0.08"
}
PLAY RECAP ***********************************************************
localhost : ok=8 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
출력을 기반으로 의사 결정
스크립트 출력을 캡처하는 가장 강력한 측면 중 하나는 Ansible 플레이북에서 이를 사용하여 의사 결정을 내리는 것입니다. 스크립트 출력을 기반으로 조건부 실행을 보여주는 플레이북을 만들어 보겠습니다.
~/project/ansible-output-demo 디렉토리에 conditional_actions.yml이라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
conditional_actions.yml로 저장합니다.
다음 내용을 추가합니다.
---
- name: Conditional Actions Based on Script Output
hosts: local
gather_facts: no
tasks:
- name: Execute the system_stats.sh script
command: "{{ playbook_dir }}/scripts/system_stats.sh"
register: stats_output
- name: Parse disk usage
set_fact:
disk_usage: "{{ stats_output.stdout | regex_search('DISK_USAGE_PCT: (\\d+)', '\\1') | first | int }}"
- name: Parse load average
set_fact:
load_avg: "{{ stats_output.stdout | regex_search('LOAD_AVG: ([0-9.]+)', '\\1') | first | float }}"
- name: Display system status
debug:
msg: "Current system status: Disk usage: {{ disk_usage }}%, Load average: {{ load_avg }}"
- name: Warn about high disk usage
debug:
msg: "WARNING: Disk usage is high at {{ disk_usage }}%. Consider cleaning up disk space."
when: disk_usage > 50
- name: Warn about high load average
debug:
msg: "WARNING: Load average is high at {{ load_avg }}. Check for resource-intensive processes."
when: load_avg > 1.0
- name: Report healthy system
debug:
msg: "System is healthy. All metrics within normal ranges."
when: disk_usage <= 50 and load_avg <= 1.0
이 플레이북은 다음을 수행합니다.
system_stats.sh스크립트를 실행합니다.- 디스크 사용량 및 로드 평균 값을 구문 분석합니다.
- 값에 따라 다른 메시지를 표시합니다.
- 디스크 사용량이 50% 를 초과하면 경고
- 로드 평균이 1.0 을 초과하면 경고
- 모든 메트릭이 정상 범위 내에 있으면 "정상 시스템" 메시지
이 플레이북을 실행해 보겠습니다.
ansible-playbook -i inventory conditional_actions.yml
출력은 시스템의 현재 상태에 따라 다르지만 디스크 사용량 및 로드 평균을 기반으로 조건부 메시지가 포함되어야 합니다.
이러한 예제는 다음을 수행하는 방법을 보여줍니다.
- 스크립트 출력에서 특정 정보 구문 분석 및 추출
- 해당 정보를 사용하여 Ansible 플레이북에서 의사 결정
- 스크립트 출력에 따라 다른 작업 수행
이러한 기술은 다양한 조건과 시나리오에 적응할 수 있는 동적이고 반응적인 자동화 워크플로를 만드는 데 필수적입니다.
실제 사용 사례 - 시스템 상태 검사
이 마지막 단계에서는 Ansible 을 사용하여 스크립트 출력을 캡처하고 처리하는 데 대해 배운 모든 것을 결합한 완전한 실제 사례를 만들 것입니다. 다음을 수행하는 시스템 상태 검사 도구를 구축합니다.
- 다양한 시스템 메트릭 수집
- 잠재적인 문제를 식별하기 위해 메트릭 분석
- 상태 보고서 생성
- 필요한 경우 시정 조치 수행
상태 검사 스크립트 만들기
먼저 다양한 시스템 메트릭을 수집하는 포괄적인 상태 검사 스크립트를 만들어 보겠습니다.
scripts 디렉토리에 health_check.sh라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
scripts/health_check.sh로 저장합니다.
health_check.sh 파일에 다음 내용을 추가합니다.
#!/bin/bash
## System Health Check Script
echo "HEALTH_CHECK_START: $(date)"
## CPU load
cpu_load=$(uptime | awk -F'load average: ' '{print $2}' | cut -d, -f1)
echo "CPU_LOAD: $cpu_load"
if (($(echo "$cpu_load > 1.0" | bc -l))); then
echo "CPU_STATUS: WARNING"
else
echo "CPU_STATUS: OK"
fi
## Memory usage
mem_total=$(free | grep Mem | awk '{print $2}')
mem_used=$(free | grep Mem | awk '{print $3}')
mem_pct=$(echo "scale=2; $mem_used / $mem_total * 100" | bc)
echo "MEM_USAGE_PCT: $mem_pct"
if (($(echo "$mem_pct > 80" | bc -l))); then
echo "MEM_STATUS: WARNING"
else
echo "MEM_STATUS: OK"
fi
## Disk usage
disk_usage=$(df -h / | tail -1 | awk '{print $5}' | tr -d '%')
echo "DISK_USAGE_PCT: $disk_usage"
if [ "$disk_usage" -gt 80 ]; then
echo "DISK_STATUS: WARNING"
else
echo "DISK_STATUS: OK"
fi
## Check for zombie processes
zombie_count=$(ps aux | grep -c Z)
echo "ZOMBIE_PROCESSES: $zombie_count"
if [ "$zombie_count" -gt 0 ]; then
echo "ZOMBIE_STATUS: WARNING"
else
echo "ZOMBIE_STATUS: OK"
fi
## Check system uptime
uptime_days=$(uptime | awk '{print $3}')
echo "UPTIME_DAYS: $uptime_days"
## Check last 5 log entries for errors
echo "RECENT_ERRORS: $(grep -i error /var/log/syslog 2> /dev/null | tail -5 | wc -l)"
echo "HEALTH_CHECK_END: $(date)"
스크립트를 실행 가능하게 만듭니다.
chmod +x ~/project/ansible-output-demo/scripts/health_check.sh
상태 검사 플레이북 만들기
이제 상태 검사 스크립트를 실행하고 결과를 분석하며 발견 사항에 따라 적절한 조치를 취하는 포괄적인 플레이북을 만들어 보겠습니다.
~/project/ansible-output-demo 디렉토리에 system_health_check.yml이라는 새 파일을 만듭니다.
- "File" 메뉴를 클릭합니다.
- "New File"을 선택합니다.
system_health_check.yml로 저장합니다.
system_health_check.yml 파일에 다음 내용을 추가합니다.
---
- name: System Health Check
hosts: local
gather_facts: no
tasks:
- name: Execute health check script
command: "{{ playbook_dir }}/scripts/health_check.sh"
register: health_check
- name: Display raw health check output
debug:
var: health_check.stdout_lines
## Parse metrics from the health check output
- name: Parse CPU load
set_fact:
cpu_load: "{{ health_check.stdout | regex_search('CPU_LOAD: ([0-9.]+)', '\\1') | first | float }}"
cpu_status: "{{ health_check.stdout | regex_search('CPU_STATUS: (\\w+)', '\\1') | first }}"
- name: Parse memory usage
set_fact:
mem_usage: "{{ health_check.stdout | regex_search('MEM_USAGE_PCT: ([0-9.]+)', '\\1') | first | float }}"
mem_status: "{{ health_check.stdout | regex_search('MEM_STATUS: (\\w+)', '\\1') | first }}"
- name: Parse disk usage
set_fact:
disk_usage: "{{ health_check.stdout | regex_search('DISK_USAGE_PCT: (\\d+)', '\\1') | first | int }}"
disk_status: "{{ health_check.stdout | regex_search('DISK_STATUS: (\\w+)', '\\1') | first }}"
- name: Parse zombie processes
set_fact:
zombie_count: "{{ health_check.stdout | regex_search('ZOMBIE_PROCESSES: (\\d+)', '\\1') | first | int }}"
zombie_status: "{{ health_check.stdout | regex_search('ZOMBIE_STATUS: (\\w+)', '\\1') | first }}"
## Generate a health status summary
- name: Generate health status summary
set_fact:
health_status:
cpu:
load: "{{ cpu_load }}"
status: "{{ cpu_status }}"
memory:
usage_percent: "{{ mem_usage }}"
status: "{{ mem_status }}"
disk:
usage_percent: "{{ disk_usage }}"
status: "{{ disk_status }}"
processes:
zombie_count: "{{ zombie_count }}"
status: "{{ zombie_status }}"
## Display health summary
- name: Display health summary
debug:
var: health_status
## Check overall system status
- name: Determine overall system status
set_fact:
overall_status: "{{ 'WARNING' if (cpu_status == 'WARNING' or mem_status == 'WARNING' or disk_status == 'WARNING' or zombie_status == 'WARNING') else 'OK' }}"
- name: Display overall system status
debug:
msg: "Overall System Status: {{ overall_status }}"
## Take remedial actions if necessary
- name: Recommend actions for CPU issues
debug:
msg: "Action recommended: Check for resource-intensive processes using 'top' or 'htop'"
when: cpu_status == "WARNING"
- name: Recommend actions for memory issues
debug:
msg: "Action recommended: Free up memory by restarting services or clearing cache"
when: mem_status == "WARNING"
- name: Recommend actions for disk issues
debug:
msg: "Action recommended: Clean up disk space using 'du -sh /* | sort -hr' to identify large directories"
when: disk_status == "WARNING"
- name: Recommend actions for zombie processes
debug:
msg: "Action recommended: Identify and restart parent processes of zombies"
when: zombie_status == "WARNING"
## Generate health report file
- name: Create health report directory
file:
path: "{{ playbook_dir }}/reports"
state: directory
- name: Get current timestamp
command: date "+%Y%m%d_%H%M%S"
register: timestamp
- name: Create health report file
copy:
content: |
System Health Report - {{ timestamp.stdout }}
----------------------------------------------
CPU:
Load Average: {{ cpu_load }}
Status: {{ cpu_status }}
Memory:
Usage: {{ mem_usage }}%
Status: {{ mem_status }}
Disk:
Usage: {{ disk_usage }}%
Status: {{ disk_status }}
Processes:
Zombie Count: {{ zombie_count }}
Status: {{ zombie_status }}
Overall Status: {{ overall_status }}
Recommendations:
{% if cpu_status == "WARNING" %}
- CPU: Check for resource-intensive processes using 'top' or 'htop'
{% endif %}
{% if mem_status == "WARNING" %}
- Memory: Free up memory by restarting services or clearing cache
{% endif %}
{% if disk_status == "WARNING" %}
- Disk: Clean up disk space using 'du -sh /* | sort -hr' to identify large directories
{% endif %}
{% if zombie_status == "WARNING" %}
- Processes: Identify and restart parent processes of zombies
{% endif %}
{% if overall_status == "OK" %}
- System is healthy. No actions required.
{% endif %}
dest: "{{ playbook_dir }}/reports/health_report_{{ timestamp.stdout }}.txt"
- name: Display report location
debug:
msg: "Health report saved to {{ playbook_dir }}/reports/health_report_{{ timestamp.stdout }}.txt"
이 포괄적인 플레이북은 다음을 수행합니다.
- 상태 검사 스크립트를 실행합니다.
- 스크립트 출력에서 다양한 메트릭을 구문 분석합니다.
- 시스템 상태에 대한 구조화된 요약을 만듭니다.
- 개별 구성 요소 상태를 기반으로 전체 시스템 상태를 결정합니다.
- 감지된 문제에 대한 특정 권장 사항을 제공합니다.
- 타임스탬프가 포함된 자세한 상태 보고서 파일을 생성합니다.
상태 검사 실행
시스템 상태 검사 플레이북을 실행해 보겠습니다.
cd ~/project/ansible-output-demo
ansible-playbook -i inventory system_health_check.yml
시스템의 상태 상태와 개선에 필요한 권장 사항을 보여주는 자세한 출력을 볼 수 있습니다. 출력은 시스템의 현재 상태에 따라 다릅니다.
플레이북을 실행한 후 보고서 디렉토리를 확인하여 생성된 상태 보고서를 확인합니다.
ls -l ~/project/ansible-output-demo/reports/
health_report_[timestamp].txt라는 파일이 표시됩니다. 이 파일의 내용을 봅니다.
cat ~/project/ansible-output-demo/reports/health_report_*.txt
우리가 배운 내용 요약
이 튜토리얼을 통해 다음을 배웠습니다.
- Ansible 에서 실행된 스크립트에서 다양한 유형의 출력 (stdout, stderr, 반환 코드) 을 캡처하는 방법
- Ansible 필터를 사용하여 스크립트 출력에서 특정 정보를 구문 분석하고 추출하는 방법
- 스크립트 출력을 사용하여 의사 결정을 내리고 조건부 작업을 수행하는 방법
- 시스템 상태 모니터링을 위해 스크립트 출력을 활용하는 완전한 실제 솔루션을 구현하는 방법
이러한 기술은 Ansible 자동화 도구 키트의 강력한 도구로, 정교하고 동적이며 반응적인 자동화 워크플로를 만들 수 있습니다.
요약
이 랩에서는 Ansible 을 통해 실행된 스크립트의 출력을 효과적으로 캡처하고 활용하는 방법을 살펴보았습니다. register 키워드를 사용한 기본적인 출력 캡처부터 시작하여 필터를 사용한 출력 구문 분석 및 스크립트 결과에 따른 의사 결정과 같은 보다 고급 기술로 발전했습니다.
이 튜토리얼의 주요 내용은 다음과 같습니다.
- Ansible 에서 실행된 스크립트에서 다양한 유형의 출력 (stdout, stderr, 반환 코드) 을 캡처하는 기능
- 스크립트 출력에서 특정 정보를 구문 분석하고 추출하기 위한 기술
- 스크립트 출력을 기반으로 작업을 조건부로 실행하는 방법
- Ansible 을 사용하여 시스템 상태 모니터링 솔루션을 구축하는 방법을 보여주는 포괄적인 실제 사례
이러한 기술을 마스터하면 다양한 조건과 시나리오에 적응할 수 있는 보다 정교하고 동적이며 반응적인 자동화 워크플로를 만들 수 있습니다. 이 기능은 Ansible 을 사용한 효과적인 인프라 관리, 애플리케이션 배포 및 시스템 관리에 필수적입니다.
Ansible 여정을 계속 진행하면서 스크립트 출력 캡처는 Ansible 이 제공하는 많은 강력한 기능 중 하나일 뿐임을 기억하십시오. 역할, 템플릿 및 볼트와 같은 다른 Ansible 기능을 탐색하면 자동화 도구 키트가 더욱 향상됩니다.


