Search
Duplicate
📒

[Ansible] 02-1. Inventory, Playbook

상태
완료
수업
Ansible
주제
4 more properties
참고

인벤토리

NOTE
인벤토리 파일은 Ip 혹은 /etc/hosts에 등록된 호스트명을 등록해서 작업을 수행할 수 있게 해주는 파일입니다.
인벤토리는 그룹별로 호스트 설정하여 그룹별로 작업을 처리할 수 있게 할 수 있습니다.
# controll node그룹 [controll] controll-node ansible_host=192.168.32.14 # managed node 그룹 [managed] manage-node-1 ansible_host=192.168.32.15 manage-node-2 ansible_host=192.168.32.16 # 중첩 그룹(:children) [node:children] controll managed # 그룹 변수 설정(:vars) [node:vars] ansible_user=root ansible_become=true # 범위 그룹([start:end]) [nested] 192.168.32.[14:16]
Bash
복사
host.ini
all: children: controll: hosts: controll-node: ansible_host: 192.168.32.14 managed: hosts: manage-node-1: ansible_host: 192.168.32.15 manage-node-2: ansible_host: 192.168.32.16 node: children: controll: managed: vars: ansible_user: root ansible_become: true nested: hosts: 192.168.32.14: 192.168.32.15: 192.168.32.16:
YAML
복사
host.yaml
# --list 특정 인벤토리 확인 ansible-inventory -i /inventory --list # -y, --yaml 데이터 형식에 맞춰서 출력 ansible-inventory -i ./inventory/hosts.yaml --list --yaml # --graph 트리 형태로 인벤토리 확인 ansible-inventory -i /inventory --graph vi ansible.cfg # cfg는 기본 인벤토리 값 ansible-inventory --list # cfg 설정 파일에 정의된 인벤토리 확인
Bash
복사
인벤토리 CLI

플레이북

NOTE
플레이북은 시스템 구성, 배포 및 일반적인 IT 작업을 자동화 하는데 사용할 수 있습니다. 플레이북은 한 번에 하나 이상의 작업을 정의하여 여러 호스트에서 순차적 또는 병렬로 실행할 수 있습니다.
# Playbook 실행 ansible-playbook playbook.yaml # --syntax-check Playbook 문법검증 ansible-playbook --syntax-check playbook.yaml # --check dry-run 실행 ansible-playbook --check playbook.yaml tail -f /var/log/messages # sshd 서비스 재시작확인
Bash
복사
Playbook CLI
--- - name: 모든 호스트에 인사하기 # hosts: 작업이 실행될 호스트 그룹을 정의합니다. hosts: node gather_facts: True become: yes # Vars: 플레이북 내에서 사용할 변수 vars: haproxy_cfg_path: /etc/haproxy/haproxy.cfg # Tasks: 실행할 작업 목록 tasks: - name: 안녕하세요! ansible.builtin.shell: cmd: echo "안녕하세요!" - name: HAProxy 설치 ansible.builtin.package: name: haproxy state: present notify: - Restart HAProxy - name: HAProxy 설정 파일 복사 ansible.builtin.template: src: templates/haproxy.cfg.j2 dest: "{{ haproxy_cfg_path }}" notify: - Restart HAProxy # Handlers: 특정 조건이 충족되면 호출되는 작업 handlers: - name: Restart HAProxy ansible.builtin.service: name: haproxy state: restarted
YAML
복사
Playbook 예시
global log /dev/log local0 log /dev/log local1 notice chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin stats timeout 30s user haproxy group haproxy daemon defaults log global mode http option httplog option dontlognull timeout connect 5000 timeout client 50000 timeout server 50000 errorfile 400 /etc/haproxy/errors/400.http errorfile 403 /etc/haproxy/errors/403.http errorfile 408 /etc/haproxy/errors/408.http errorfile 500 /etc/haproxy/errors/500.http errorfile 502 /etc/haproxy/errors/502.http errorfile 503 /etc/haproxy/errors/503.http errorfile 504 /etc/haproxy/errors/504.http frontend http_front bind *:80 stats uri /haproxy?stats default_backend http_back backend http_back balance roundrobin server server1 127.0.0.1:8001 check
Bash
복사
templates/haproxy.cfg

Jinja2 Template

NOTE
Jinja2는 Python에서 사용되는 Template 엔진이며, template 모듈을 사용해서 Jinja2 템플릿 파일을 클라이언트에 배포할 수 있습니다.
{{ }} # 변수, 식 출력 {% %} # 논리 제어(조건, 반복)에 사용 {# #} # 주석
Bash
복사
# name, company 변수 사용 Hello, {{ name }}! Welcome to {{ company }}.
Bash
복사
변수.j2
# 조건문 {% if name == 'admin' %} Hello, Admin Master! {% else %} Hello, {{ name }} {% endif %} # 반복문 Users: {% for user in users%} - {{ user.name }} {{ user.role }} {% endfor %} # 조건-반복문 {% set matrix = [[1,2,3],[4,5,6],[7,8,9]]%} {% for row in matrix %} {% for item in row %} - {{ item }} {% endfor %} {% endfor %}
Bash
복사
제어문.j2
# 매직변수(hostvars, groups, facts) {% for host in groups['all'] %} HOST {{ hostvars[host]['ansible_facts']['hostname'] }} IPADDR: {{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {% endfor %} # 변수 필터 Original: {{ 'Hello, World!' }} Upper: {{ 'Hello, World!' | upper }} Lower: {{ 'Hello, World!' | lower }} REPLACE: {{ 'Hello, World!' | replace('World', 'Jinja2' }} DEFAULT: {{ variable | default('hello') }} RANDOM: {{ [1, 2, 3, 4, 5] | random }} MIN: {{ [1, 2, 3, 4, 5] | min }} MAX: {{ [1, 2, 3, 4, 5] | max }}
Bash
복사

Ansible Playbook 처리루틴(병렬)

NOTE
Ansible에서 플레이북을 처리하면, 모든 클라이언트가 task를 동시에 처리하게 됩니다.
Ansible은 이론상 모든 클라이언트에 동시 실행이 가능하지만, 수백 개의 호스트를 대상으로 하는경우 제어 노드에 부하가 발생할 수 있습니다.
Ansible이 생성하는 최대 동시 연결수는 ansible.cfg[defaults] 그룹의 fork값으로 제어됩니다.
[defaults] fork = 10 # 최대 10개의 호스트에서 작업실행
Bash
복사
ansible.cfg가 아닌 playbook에서도 병렬작업을 제어할 수 있는 키워드가 있습니다.
- hosts: servers # strategy # linear(기본값): 모든 호스트에서 각 태스크 순차실행 # free: 각 호스트에서 가능한 빨리 실행 strategy: free # serial: 동시에 수행되는 호스트 수 serial: 2 tasks: - name: 인사 debug: msg: "안녕하세요" # throttle: 특정 task의 호스트 실행제한 - name: 인사2 debug: msg: "안녕하세요2" throttle: 3 # async: 작업이 완료될떄 까지 기다리지 않고 백그라운드 실행 # poll: 작업의 완료 상태 주기적으로 확인 - name: 인사3 debug: msg: "안녕하세요3" async: 60 poll: 5
YAML
복사