'UNREACHABLE!' 오류 방지를 위한 모범 사례 구현
이제 즉각적인 'UNREACHABLE!' 오류를 수정했으므로, 앞으로 이를 방지하기 위한 모범 사례에 집중해 보겠습니다. 여기에는 적절한 인벤토리 관리, 연결 구성 및 오류 처리 기술이 포함됩니다.
강력한 인벤토리 구조 생성
잘 구성된 인벤토리는 문제 해결을 더 쉽게 만듭니다. 더 구조화된 인벤토리 디렉토리를 만들어 보겠습니다.
cd ~/project/ansible-lab
mkdir -p inventory/{group_vars,host_vars}
이제 기본 인벤토리 파일을 만들어 보겠습니다.
cat > inventory/hosts << 'EOF'
## Production Servers
[production]
## prod-server ansible_host=prod.example.com
## Development Servers
[development]
## dev-server ansible_host=dev.example.com
## Local Connections
[local]
localhost ansible_connection=local
## SSH Connections
[ssh_local]
local-ssh ansible_host=127.0.0.1
EOF
다음으로, SSH 연결 그룹에 대한 그룹 변수를 만들어 보겠습니다.
cat > inventory/group_vars/ssh_local.yml << 'EOF'
---
ansible_connection: ssh
ansible_user: labex
ansible_ssh_private_key_file: ~/.ssh/id_rsa
ansible_ssh_common_args: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
EOF
새 인벤토리 디렉토리를 사용하도록 Ansible 구성을 업데이트합니다.
cat > ansible.cfg << 'EOF'
[defaults]
inventory = ./inventory/hosts
host_key_checking = False
retry_files_enabled = True
retry_files_save_path = ~/.ansible/retry-files
timeout = 30
connect_timeout = 30
command_timeout = 30
[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
control_path_dir = ~/.ansible/cp
EOF
재시도 로직을 사용한 연결 테스트 플레이북 생성
Ansible 을 사용하면 실패한 작업을 재시도할 수 있습니다. 재시도 로직이 있는 플레이북을 만들어 보겠습니다.
cat > connection_test_with_retry.yml << 'EOF'
---
- name: Test All Connections
hosts: all
gather_facts: no
tasks:
- name: Ping hosts
ping:
register: ping_result
retries: 3
delay: 5
until: ping_result is not failed
ignore_unreachable: yes
- name: Display ping status
debug:
msg: "Connection to {{ inventory_hostname }} was successful"
when: ping_result is success
- name: Report unreachable hosts
debug:
msg: "Host {{ inventory_hostname }} is unreachable"
when: ping_result is unreachable
EOF
새 인벤토리 구조로 플레이북을 실행합니다.
ansible-playbook connection_test_with_retry.yml
localhost 및 local-ssh 에 대한 성공적인 연결을 보여주는 출력이 표시되어야 합니다.
'UNREACHABLE!' 오류를 정상적으로 처리
'UNREACHABLE!' 오류를 정상적으로 처리하고 보고서를 생성하는 더 고급 플레이북을 만들어 보겠습니다.
cat > connection_report.yml << 'EOF'
---
- name: Test Connections and Generate Report
hosts: all
gather_facts: no
tasks:
- name: Try to connect to hosts
ping:
register: ping_result
ignore_unreachable: yes
- name: Create reachable hosts list
set_fact:
reachable_hosts: "{{ (reachable_hosts | default([])) + [inventory_hostname] }}"
when: ping_result is success
delegate_to: localhost
delegate_facts: true
- name: Create unreachable hosts list
set_fact:
unreachable_hosts: "{{ (unreachable_hosts | default([])) + [inventory_hostname] }}"
when: ping_result is unreachable
delegate_to: localhost
delegate_facts: true
- name: Generate Connection Report
hosts: localhost
gather_facts: no
tasks:
- name: Display reachable hosts
debug:
msg: "Reachable hosts: {{ reachable_hosts | default([]) | join(', ') }}"
- name: Display unreachable hosts
debug:
msg: "Unreachable hosts: {{ unreachable_hosts | default([]) | join(', ') }}"
- name: Write report to file
copy:
content: |
Connection Report
-----------------
Reachable hosts: {{ reachable_hosts | default([]) | join(', ') }}
Unreachable hosts: {{ unreachable_hosts | default([]) | join(', ') }}
Generated on: {{ ansible_date_time.iso8601 }}
dest: ~/project/ansible-lab/connection_report.txt
register: report
- name: Show report location
debug:
msg: "Report saved to {{ report.dest }}"
EOF
보고서 플레이북을 실행합니다.
ansible-playbook connection_report.yml
보고서를 확인해 보겠습니다.
cat ~/project/ansible-lab/connection_report.txt
연결 가능한 호스트와 연결할 수 없는 호스트를 나열하는 보고서가 표시되어야 합니다.
Ansible 인벤토리 플러그인 사용
Ansible 은 호스트를 동적으로 관리하기 위해 인벤토리 플러그인을 제공합니다. 이를 시연하기 위해 간단한 스크립트를 만들어 보겠습니다.
cat > inventory_script.py << 'EOF'
#!/usr/bin/env python3
import json
import socket
def is_host_reachable(host, port=22, timeout=1):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except:
return False
## Define our hosts
hosts = {
'localhost': '127.0.0.1',
'local-ssh': '127.0.0.1',
'virtual-host': '10.10.10.10'
}
## Check reachability and build inventory
inventory = {
'all': {
'hosts': list(hosts.keys())
},
'reachable': {
'hosts': []
},
'unreachable': {
'hosts': []
},
'_meta': {
'hostvars': {}
}
}
for hostname, ip in hosts.items():
reachable = is_host_reachable(ip)
group = 'reachable' if reachable else 'unreachable'
inventory[group]['hosts'].append(hostname)
inventory['_meta']['hostvars'][hostname] = {
'ansible_host': ip,
'reachability_checked': True,
'is_reachable': reachable
}
print(json.dumps(inventory, indent=2))
EOF
chmod +x inventory_script.py
동적 인벤토리 스크립트를 테스트합니다.
./inventory_script.py
연결 가능한 호스트 또는 연결할 수 없는 호스트로 분류된 호스트를 보여주는 JSON 출력이 표시되어야 합니다.
이 동적 인벤토리를 사용하여 플레이북을 실행해 보겠습니다.
ansible-playbook -i ./inventory_script.py connection_test.yml --limit reachable
이렇게 하면 스크립트가 연결할 수 있다고 결정한 호스트에만 연결을 시도하여 'UNREACHABLE!' 오류를 완전히 방지할 수 있습니다.
이러한 모범 사례는 Ansible 연결을 관리하고 프로덕션 환경에서 'UNREACHABLE!' 오류를 방지하기 위한 강력한 프레임워크를 제공합니다.