실습 환경 구성
- 실습환경배포
##파일 다운로드
/drives/c/Users/bom/Desktop/스터디/ansible
13/01/2026 23:05.21 curl -O https://raw.githubusercontent.com/gasida/ vagrant-lab/refs/heads/main/ansible/Vagrantfile
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 2458 100 2458 0 0 8081 0 --:--:-- --:--:-- --:--:-- 8112
✓
/drives/c/Users/bom/Desktop/스터디/ansible
13/01/2026 23:05.27 curl -O https://raw.githubusercontent.com/gasida/ vagrant-lab/refs/heads/main/ansible/init_cfg.sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1072 100 1072 0 0 3975 0 --:--:-- --:--:-- --:--:-- 3985
✓
/drives/c/Users/bom/Desktop/스터디/ansible
13/01/2026 23:05.32
✓
/drives/c/Users/bom/Desktop/스터디/ansible
13/01/2026 23:05.32 curl -O https://raw.githubusercontent.com/gasida/ vagrant-lab/refs/heads/main/ansible/init_cfg2.sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 1074 100 1074 0 0 3781 0 --:--:-- --:--:-- --:--:-- 3795
✓
#파일 다운로드 후 vagrant up
PS C:\Users\bom\Desktop\스터디\ansible> vagrant up
Bringing machine 'server' up with 'virtualbox' provider...
Bringing machine 'tnode1' up with 'virtualbox' provider...
Bringing machine 'tnode2' up with 'virtualbox' provider...
Bringing machine 'tnode3' up with 'virtualbox' provider...
==> server: Preparing master VM for linked clones...
server: This is a one time operation. Once the master VM is prepared,
server: it will be used as a base for linked clones, making the creation
server: of new VMs take milliseconds on a modern system.
==> server: Importing base box 'bento/ubuntu-24.04'...
==> server: Cloning VM...
==> server: Matching MAC address for NAT networking...
==> server: Checking if box 'bento/ubuntu-24.04' version '202510.26.0' is up to date...
==> server: Setting the name of the VM: server
==> server: Clearing any previously set network interfaces...
==> server: Preparing network interfaces based on configuration...
server: Adapter 1: nat
server: Adapter 2: hostonly
==> server: Forwarding ports...
server: 22 (guest) => 60000 (host) (adapter 1)
==> server: Running 'pre-boot' VM customizations...
==> server: Booting VM...
==> server: Waiting for machine to boot. This may take a few minutes...
#############################중략######################################
기본 정보 확인
root@server:~# hostnamectl Static hostname: server Icon name: computer-vm Chassis: vm 🖴 Machine ID: 47e27b291d4344f995b31c7bd9d79f92 Boot ID: 48aba56a31cf4d90b8a573895da77ea2 Virtualization: oracle Operating System: Ubuntu 24.04.3 LTS Kernel: Linux 6.8.0-86-generic Architecture: x86-64 Hardware Vendor: innotek GmbH Hardware Model: VirtualBox Firmware Version: VirtualBox Firmware Date: Fri 2006-12-01 Firmware Age: 19y 1month 1w 6d #통신확인 root@server:~# for i in {1..3}; do ping -c 1 tnode$i; done PING tnode1 (10.10.1.11) 56(84) bytes of data. 64 bytes from tnode1 (10.10.1.11): icmp_seq=1 ttl=64 time=1.12 ms --- tnode1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 1.116/1.116/1.116/0.000 ms PING tnode2 (10.10.1.12) 56(84) bytes of data. 64 bytes from tnode2 (10.10.1.12): icmp_seq=1 ttl=64 time=2.13 ms --- tnode2 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 2.134/2.134/2.134/0.000 ms PING tnode3 (10.10.1.13) 56(84) bytes of data. 64 bytes from tnode3 (10.10.1.13): icmp_seq=1 ttl=64 time=1.52 ms --- tnode3 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 1.519/1.519/1.519/0.000 ms
Ansible소개
앤서블이란 ? Iac기반의 오픈소스 IT 자동화도구로서 코드기반으로 인프라관리를 할수있게끔 지원해주는 도구이다.
- 특징은 별도의 에이전트를 설치하지않는 Agentless방식이며, 멱등성, 그리고 다양한모듈을 제공한다는 특징을 가지고 있다.
앤서블 구성:
*제어 노드 : 앤서블이 설치되는 노드이며, 운영체제가 리눅스면 제어 노드가 될 수 있다.
*관리 노드 : 앤서블이 제어하는 원격 시스템 또는 호스트를 의미한다. 별도 에이전트가 없으므로, SSH통신이 가능해야하며, 파이썬이 설치되어있어야한다.
*인벤토리 : 제어노드가 관리하는 관리노드의 목록을 나열해놓은 파일을 의미.
*모듈: 앤서블은 관리 노드의 작업을 수행할 때 SSH를 통해 연결한 후 사용용도에 따른 모듈을 푸시하여 사용한다.
*플레이북 : 플레이북은 관리 노드에서 수행할 작업들을 YAML 문법을 이용해 순서대로 작성해놓은 파일입니다.
Ansible 설치
ansible-server에 앤서블 설치진행
root@server:~# apt install software-properties-common -y Reading package lists... Done Building dependency tree... Done Reading state information... Done software-properties-common is already the newest version (0.99.49.3). 0 upgraded, 0 newly installed, 0 to remove and 89 not upgraded. root@server:~# add-apt-repository --yes --update ppa:ansible/ansible Repository: 'Types: deb URIs: https://ppa.launchpadcontent.net/ansible/ansible/ubuntu/ Suites: noble Components: main ' Description: Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications— automate in a language that approaches plain English, using SSH, with no agents to install on remote systems. http://ansible.com/ If you face any issues while installing Ansible PPA, file an issue here: https://github.com/ansible-community/ppa/issues More info: https://launchpad.net/~ansible/+archive/ubuntu/ansible Adding repository. Get:1 http://security.ubuntu.com/ubuntu noble-security InRelease [126 kB] Get:2 https://ppa.launchpadcontent.net/ansible/ansible/ubuntu noble InRelease [17.8 kB] Hit:3 http://us.archive.ubuntu.com/ubuntu noble InRelease Get:4 https://ppa.launchpadcontent.net/ansible/ansible/ubuntu noble/main amd64 Packages [772 B] Hit:5 http://us.archive.ubuntu.com/ubuntu noble-updates InRelease Get:6 https://ppa.launchpadcontent.net/ansible/ansible/ubuntu noble/main Translation-en [472 B] Hit:7 http://us.archive.ubuntu.com/ubuntu noble-backports InRelease Fetched 145 kB in 2s (69.9 kB/s) Reading package lists... Done root@server:~# apt install ansible -y Reading package lists... Done Building dependency tree... Done Reading state information... Done ##################중략################################ root@server:~# which ansible /usr/bin/ansible root@server:~# mkdir my-ansible root@server:~# cd my-ansible/ root@server:~/my-ansible#앤서블 접근을 위한 SSH인증구성
root@server:~/my-ansible# ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa Generating public/private rsa key pair. Your identification has been saved in /root/.ssh/id_rsa Your public key has been saved in /root/.ssh/id_rsa.pub The key fingerprint is: SHA256:6c84qKYYcxZjFJPTMg03FVUF3/2kTXqKh77YBKp2qx8 root@server The key's randomart image is: +---[RSA 3072]----+ | +=o.oo..oo. | | =+o. . . . | | .+ . . +| | . . *.| | + S . o +| | . o . . . o o | |o o .E + o | | * . o.o= = . | |. .o.oo++o+ +. | +----[SHA256]-----+ root@server:~/my-ansible# for i in {1..3}; do sshpass -p 'qwe123' ssh-copy-id -o StrictHostKeyChecking=no root@tnode$i; done root@server:~/my-ansible# for i in {1..3}; do echo ">> tnode$i <<"; ssh tnode$i hostname; echo; done >> tnode1 << tnode1 >> tnode2 << tnode2 >> tnode3 << tnode3 root@server:~/my-ansible# for i in {1..3}; do echo ">> tnode$i <<"; ssh tnode$i python3 -V; echo; done >> tnode1 << Python 3.12.3 >> tnode2 << Python 3.12.3 >> tnode3 << Python 3.9.21VS Code SSH연결
# Read more about SSH config files: https://linux.die.net/man/5/ssh_config Host ansible-server HostName 10.10.1.10 User root

호스트 선정
인벤토리를 이용한 자동화대상 관리 노드 설정
인벤토리 파일은 텍스트 파일이며, 앤서블이 자동화 대상으로 하는 관리 노드를 지정합니다.
이 파일은 INI ,YAML을 포함한 다양한 형식을 사용하여 작성할 수 있습니다
다양한 인벤토리 파일 생성방법
- 호스트 정의: 관리할 서버들을 IP 주소나 호스트명으로 나열하여 기본 목록을 생성합니다.
- 그룹화: 대괄호(
[group])를 사용해 웹, DB 등 역할별로 묶어 효율적으로 관리할 수 있습니다. - 유연한 구성: 한 호스트가 여러 그룹에 속할 수 있어 위치, 환경(운영/개발) 등 다각도 분류가 가능합니다.
- 중첩 그룹:
:children접미사로 기존 그룹들을 하위 그룹으로 포함하는 상위 그룹을 정의할 수 있습니다. - 범위 지정:
[1:10]과 같은 문법을 사용해 유사한 이름의 호스트들을 한 줄로 간결하게 표현합니다.
실습을 위한 인벤토리 그룹 구성
root@server:~/my-ansible# cat <<EOT > inventory [web] tnode1 tnode2 [db] tnode3 [all:children] web db EOT root@server:~/my-ansible# ansible-inventory -i ./inventory --list | jq { "_meta": { "hostvars": {}, "profile": "inventory_legacy" }, "all": { "children": [ "ungrouped", "web", "db" ] }, "db": { "hosts": [ "tnode3" ] }, "web": { "hosts": [ "tnode1", "tnode2" ] } } root@server:~/my-ansible#(참고사항) ansible.config의 적용 우선순위.
ANSIBLE_CONFIG(environment variable if set)ansible.cfg(in the current directory)~/.ansible.cfg(in the home directory)/etc/ansible/ansible.cfg
플레이북 작성
앤서블 환경설정 하는이유
- 구성 체계:
ansible.cfg는[defaults]와[privilege_escalation]섹션으로 나뉘어 앤서블의 동작 방식을 결정합니다. - 기본 접속 설정:
[defaults]에서는 관리 호스트의 인벤토리 경로, 접속 계정명, SSH 암호 확인 여부 등 핵심 연결 정보를 정의합니다. - 권한 상승 관리:
[privilege_escalation]은 접속 후sudo등을 통해 관리자(root) 권한을 자동으로 얻는 방법과 절차를 설정합니다. - 효율성 향상: 설정 파일을 활용하면 실행 시마다 번거로운 옵션을 입력할 필요 없이 일관성 있는 자동화 환경을 구축할 수 있습니다.
- 구성 체계:
실습을 위한 앤서블 환경설정
root@server:~/my-ansible# cat <<EOT > **ansible.cfg** **[defaults]** inventory = ./inventory remote_user = **root** ask_pass = false **[privilege_escalation]** become = true become_method = **sudo** become_user = root become_ask_pass = false EOT플레이북 작성하기
플레이북 작성 및 문법체크 진행
vi my-ansible/first-playbook.yml
- hosts: all
tasks:- name: Print message
debug:
msg: Hello CloudNet@ Ansible Study
- name: Print message
root@server:~/my-ansible# ansible-playbook --syntax-check first-playbook.yml
playbook: first-playbook.yml
root@server:~/my-ansible# ansible-playbook --syntax-check first-playbook-wth-error.yml
[ERROR]: conflicting action statements: debug, msg
Origin: /root/my-ansible/first-playbook-wth-error.yml:4:7
2 - hosts: all
3 tasks:
4 - name: Print message
^ column 7
```
- 플레이북 실행하기
```bash
root@server:~/my-ansible# ansible-playbook first-playbook.yml
PLAY [all] **************************************************************************************
TASK [Gathering Facts] **************************************************************************
ok: [tnode2]
ok: [tnode1]
ok: [tnode3]
TASK [Print message] ****************************************************************************
ok: [tnode1] => {
"msg": "Hello CloudNet@ Ansible Study"
}
ok: [tnode2] => {
"msg": "Hello CloudNet@ Ansible Study"
}
ok: [tnode3] => {
"msg": "Hello CloudNet@ Ansible Study"
}
PLAY RECAP **************************************************************************************
tnode1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tnode2 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tnode3 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
- state 멱등성을 보장하기위한 상태값.
- **started** : `Start service httpd, if not started`
- **stooped** : `Stop service httpd, if started`
- **restarted** : `Restart service httpd, in all cases`
- **reloaded** : `Reload service httpd, in all cases`
- ssh재기동 플레이북 수행
```bash
vi my-ansible/**restart-service.yml**
---
- hosts: all
tasks:
- name: Restart sshd service
ansible.builtin.**service**:
name: ssh # sshd
state: **restarted**
root@server:~/my-ansible# ansible-playbook --check restart-service.yml
PLAY [all] **************************************************************************************
TASK [Gathering Facts] **************************************************************************
ok: [tnode3]
ok: [tnode1]
ok: [tnode2]
TASK [Restart sshd service] *********************************************************************
changed: [tnode1]
changed: [tnode2]
[ERROR]: Task failed: Module failed: Could not find the requested service ssh: host
Origin: /root/my-ansible/restart-service.yml:4:7
2 - hosts: all
3 tasks:
4 - name: Restart sshd service
^ column 7
fatal: [tnode3]: FAILED! => {"changed": false, "msg": "Could not find the requested service ssh: host"}
PLAY RECAP **************************************************************************************
tnode1 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tnode2 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tnode3 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
#다만, Redhat에서는 ssh가아닌 sshd이므로 정상수행이안된다.
```변수
변수 우선 순위: 추가변수(실행 시 파라미터) > 플레이 변수 > 호스트 변수 > 그룹 변수그룹 변수 실습
#인벤토리 파일 하단에 선언된 변수를 의미하며 인벤토리에서 선언후 플레이북에서 활용한다. root@server:~/my-ansible# cat inventory [web] tnode1 tnode2 [db] tnode3 [all:children] web db **[all:vars] user=ansible ## root@server:~/my-ansible# cat create-user.yml --- - hosts: all tasks: - name: Create User {{ user }} ansible.builtin.user: name: "{{ user }}" state: present
root@server:~/my-ansible# ansible-playbook create-user.yml
PLAY [all] **************************************************************************************
TASK [Gathering Facts] **************************************************************************
ok: [tnode2]
ok: [tnode3]
ok: [tnode1]
TASK [Create User ansible] **********************************************************************
changed: [tnode1]
changed: [tnode2]
changed: [tnode3]
PLAY RECAP **************************************************************************************
tnode1 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tnode2 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tnode3 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
##멱등성 확인
TASK [Create User ansible] **********************************************************************
ok: [tnode1]
ok: [tnode2]
ok: [tnode3]**
```호스트 변수 실습
#말그대로 호스트에서만 사용이 가능하다. root@server:~/my-ansible# vi inventory [web] tnode1 ansible_python_interpreter=/usr/bin/python3 tnode2 ansible_python_interpreter=/usr/bin/python3 [db] tnode3 ansible_python_interpreter=/usr/bin/python3 **user=ansible1** [all:children] web db [all:vars] user=ansible root@server:~/my-ansible# for i in {1..3}; do echo ">> tnode$i <<"; ssh tnode$i tail -n 3 /etc/passwd; echo; done >> tnode1 << vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash vboxadd:x:999:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/sh >> tnode2 << vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash vboxadd:x:999:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/sh >> tnode3 << vboxadd:x:991:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/bash ansible1:x:1002:1002::/home/ansible1:/bin/bash플레이 변수
#플레이북에서 선언하는 변수를 의미 root@server:~/my-ansible# cat create-user2.yml --- - hosts: all **vars: user: ansible2** tasks: - name: Create User {{ user }} ansible.builtin.user: name: "{{ user }}" state: present root@server:~/my-ansible# for i in {1..3}; do echo ">> tnode$i <<"; ssh tnode$i tail -n 3 /etc/passwd; echo; done >> tnode1 << vboxadd:x:999:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/sh **ansible2:x:1002:1002::/home/ansible2:/bin/sh** >> tnode2 << vboxadd:x:999:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/sh **ansible2:x:1002:1002::/home/ansible2:/bin/sh** >> tnode3 << ansible:x:1001:1001::/home/ansible:/bin/bash ansible1:x:1002:1002::/home/ansible1:/bin/bash **ansible2:x:1003:1003::/home/ansible2:/bin/bash** #아래와 같은 형태로 vars를 별도관리해서 사용가능 root@server:~/my-ansible# tree vars vars └── users.yml추가 변수
#직접 명령어 수행시 입력하는 변수를 의미한다. root@server:~/my-ansible# ansible-playbook **-e user=ansible4** create-user3.yml root@server:~/my-ansible# for i in {1..3}; do echo ">> tnode$i <<"; ssh tnode$i tail -n 5 /etc/passwd; echo; done >> tnode1 << vboxadd:x:999:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/sh ansible2:x:1002:1002::/home/ansible2:/bin/sh ansible3:x:1003:1003::/home/ansible3:/bin/sh ansible4:x:1004:1004::/home/ansible4:/bin/sh >> tnode2 << vboxadd:x:999:1::/var/run/vboxadd:/bin/false ansible:x:1001:1001::/home/ansible:/bin/sh ansible2:x:1002:1002::/home/ansible2:/bin/sh ansible3:x:1003:1003::/home/ansible3:/bin/sh ansible4:x:1004:1004::/home/ansible4:/bin/sh >> tnode3 << ansible:x:1001:1001::/home/ansible:/bin/bash ansible1:x:1002:1002::/home/ansible1:/bin/bash ansible2:x:1003:1003::/home/ansible2:/bin/bash ansible3:x:1004:1004::/home/ansible3:/bin/bash ansible4:x:1005:1005::/home/ansible4:/bin/bash작업변수 ansible.builtin.debug모듈
#플레이북의 수행결과를 저장한다 register: result문구를 통해확인 root@server:~/my-ansible# ansible-playbook -e user=test create-user.yml PLAY [db] *************************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [tnode3] TASK [Create User test] ************************************************************************* changed: [tnode3] TASK [ansible.builtin.debug] ******************************************************************** ok: [tnode3] => { "result": { "changed": true, "comment": "", "create_home": true, "failed": false, "group": 1006, "home": "/home/test", "name": "test", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1006 } }
Facts
앤서블이 관리 노드에서 수집하는 변수를의미하며 변수종류에는 아래와 같은 종류가 수집된다.
호스트 이름
커널 버전
네트워크 인터페이스 이름
운영체제 버전
CPU 개수
사용 가능한 메모리
스토리지 장치의 크기 및 여유 공간
등등…
팩트 사용하기
root@server:~/my-ansible# ansible-playbook facts.yml PLAY [db] *************************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [tnode3] TASK [Print all facts] ************************************************************************** ok: [tnode3] => { "ansible_facts": { "all_ipv4_addresses": [ "10.0.2.15", "10.10.1.13" ], "all_ipv6_addresses": [ "fd17:625c:f037:2:a00:27ff:fe6f:16b4", "fe80::a00:27ff:fe6f:16b4", "fe80::a00:27ff:feba:8927" ], "ansible_local": {}, "apparmor": { "status": "disabled" }, "architecture": "x86_64", "bios_date": "12/01/2006", "bios_vendor": "innotek GmbH", "bios_version": "VirtualBox", "board_asset_tag": "NA", "board_name": "VirtualBox", "board_serial": "0", "board_vendor": "Oracle Corporation", "board_version": "1.2", "chassis_asset_tag": "NA", "chassis_serial": "NA", "chassis_vendor": "Oracle Corporation", "chassis_version": "NA", ######################중략#################################################특정 정보만 수집하기
--- - hosts: **db** tasks: - name: **Print all facts** ansible.builtin.**debug**: msg: > The default IPv4 address of **{{ ansible_facts.hostname }}** is **{{ ansible_facts.default_ipv4.address }} root@server:~/my-ansible# ansible-playbook facts1.yml PLAY [db] *************************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [tnode3] TASK [Print all facts] ************************************************************************** ok: [tnode3] => { "msg": "The default IPv4 address of tnode3 is 10.0.2.15\n" } PLAY RECAP ************************************************************************************** tnode3 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescu**변수로 사용할 수 있는 앤서블팩트(구표기법은제외)
| 팩트 | ansible_facts.* 표기법 |
| --- | --- |
| 호스트명 | ansible_facts.**hostname** |
| 도메인 기반 호스트명 | ansible_facts.**fqdn** |
| 기본 IPv4 주소 | ansible_facts.**default_ipv4.address** |
| 네트워크 인터페이스 이름 목록 | ansible_facts.**interfaces** |
| 디스크 파티션 크기 | ansible_facts.**device.vda.partitions.vda1.size** |
| DNS 서버 | ansible_facts.**dns.nameservers** |
| 현재 실행 커널 버전 | ansible_facts.**kernel** |
| 운영체제 종류 | ansible_facts.**distribution** |팩트 수집 끄기
--- - hosts: db **gather_facts: no** tasks: **- name: Print message debug: msg: Hello Ansible World
root@server:~/my-ansible# ansible-playbook facts3.yml
PLAY [db] ***************************************************************************************
############Fact수집없음#######################
TASK [Print message] ****************************************************************************
ok: [tnode3] => {
"msg": "Hello Ansible World"
}
PLAY RECAP **************************************************************************************
tnode3 : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0**
```팩트 캐싱
#ansible.cfg에 아래와 같이 적용 영구저장을 위해 File , DB저장도 가능 [defaults] inventory = ./inventory remote_user = root ask_pass = false **gathering = smart fact_caching = jsonfile fact_caching_connection = myfacts** [privilege_escalation] become = true become_method = sudo become_user = root become_ask_pass = false #- DEFAULT_GATHERING(수집 정책 3가지) : implicit(기본값), explicit,smart #- fact_caching_connection : 연결 정의 or **캐싱 경로**도전과제
--- - hosts: all gather_facts: yes tasks: - name: Print kernel and distribution ansible.builtin.debug: msg: - "Kernel: {{ ansible_facts.kernel }}" - "Distribution: {{ ansible_facts.distribution }}" TASK [Print kernel and distribution] ************************************************************ ok: [tnode1] => { "msg": [ "Kernel: 6.8.0-86-generic", "Distribution: Ubuntu" ] } ok: [tnode2] => { "msg": [ "Kernel: 6.8.0-86-generic", "Distribution: Ubuntu" ] } ok: [tnode3] => { "msg": [ "Kernel: 5.14.0-570.52.1.el9_6.x86_64", "Distribution: Rocky" ] }
반복문
단순반복문
--- - hosts: **all** tasks: - name: Check sshd and rsyslog state **ansible.builtin.service: name: "{{ item }}" state: started loop: - vboxadd-service** # ssh **- rsyslog root@server:~/my-ansible# ansible-playbook loop.yml PLAY [all] ************************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [tnode3] ok: [tnode2] ok: [tnode1] TASK [Check sshd and rsyslog state] ************************************************************* ok: [tnode1] => (item=vboxadd-service) ok: [tnode2] => (item=vboxadd-service) ok: [tnode3] => (item=vboxadd-service) ok: [tnode1] => (item=rsyslog) ok: [tnode2] => (item=rsyslog) ok: [tnode3] => (item=rsyslog) PLAY RECAP ************************************************************************************** tnode1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 tnode2 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 tnode3 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0**
```사전 목록에 의한 반복문
** builtin.file모듈 파일모듈도 상당히 많이쓰는 모듈중하나로 파일 및 파일 속성 관리 모듈이다
--- - hosts: **all** tasks: - name: Create files ansible.builtin.**file**: path: "**{{ item['log-path'] }}**" mode: "**{{ item['log-mode'] }}**" state: touch **loop**: - log-path: /var/log/test1.log log-mode: '0644' - log-path: /var/log/test2.log log-mode: '0600' root@server:~/my-ansible# ansible-playbook make-file.yml PLAY [all] ************************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [tnode3] ok: [tnode2] ok: [tnode1] TASK [Create files] ***************************************************************************** changed: [tnode1] => (item={'log-path': '/var/log/test1.log', 'log-mode': '0644'}) changed: [tnode2] => (item={'log-path': '/var/log/test1.log', 'log-mode': '0644'}) changed: [tnode3] => (item={'log-path': '/var/log/test1.log', 'log-mode': '0644'}) changed: [tnode1] => (item={'log-path': '/var/log/test2.log', 'log-mode': '0600'}) changed: [tnode2] => (item={'log-path': '/var/log/test2.log', 'log-mode': '0600'}) changed: [tnode3] => (item={'log-path': '/var/log/test2.log', 'log-mode': '0600'}) PLAY RECAP ************************************************************************************** tnode1 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 tnode2 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 tnode3 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0반복문 과 Register변수 사용
Register변수를 사용해 작업의 출력을 캡쳐
--- - hosts: localhost tasks: - name: Loop echo test ansible.builtin.**shell**: "echo 'I can speak {{ item }}'" **loop**: - Korean - English **register**: **result** - name: Show result ansible.builtin.**debug**: **var: result** root@server:~/my-ansible# ansible-playbook loop_register.yml PLAY [localhost] ******************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [localhost] TASK [Loop echo test] *************************************************************************** changed: [localhost] => (item=Korean) changed: [localhost] => (item=English) TASK [Show result] ****************************************************************************** ok: [localhost] => { "result": { "changed": true, "msg": "All items completed", "results": [ { "ansible_loop_var": "item", "changed": true, "cmd": "echo 'I can speak Korean'", "delta": "0:00:00.005160", "end": "2026-01-14 23:37:54.886917", "failed": false, "invocation": { "module_args": { "_raw_params": "echo 'I can speak Korean'", ############################중략######################################### ] } ], "skipped": false } } PLAY RECAP ************************************************************************************** localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0--- - hosts: **localhost** tasks: - name: Loop echo test ansible.builtin.**shell**: "echo 'I can speak {{ item }}'" **loop**: - Korean - English **register**: result - name: Show result ansible.builtin.**debug**: **msg**: "Stdout: {{ item.**stdout** }}" **loop**: "{{ result.results }}" TASK [Show result] ****************************************************************************** ok: [localhost] => (item={'changed': True, 'stdout': 'I can speak Korean', 'stderr': '', 'rc': 0, 'cmd': "echo 'I can speak Korean'", 'start': '2026-01-14 23:40:03.964047', 'end': '2026-01-14 23:40:03.969023', 'delta': '0:00:00.004976', 'msg': '', 'invocation': {'module_args': {'_raw_params': "echo 'I can speak Korean'", '_uses_shell': True, 'expand_argument_vars': True, 'stdin_add_newline': True, 'strip_empty_ends': True, 'cmd': None, 'argv': None, 'chdir': None, 'executable': None, 'creates': None, 'removes': None, 'stdin': None}}, 'stdout_lines': ['I can speak Korean'], 'stderr_lines': [], 'failed': False, 'item': 'Korean', 'ansible_loop_var': 'item'}) => { "msg": "Stdout: I can speak Korean" } ok: [localhost] => (item={'changed': True, 'stdout': 'I can speak English', 'stderr': '', 'rc': 0, 'cmd': "echo 'I can speak English'", 'start': '2026-01-14 23:40:04.174039', 'end': '2026-01-14 23:40:04.179185', 'delta': '0:00:00.005146', 'msg': '', 'invocation': {'module_args': {'_raw_params': "echo 'I can speak English'", '_uses_shell': True, 'expand_argument_vars': True, 'stdin_add_newline': True, 'strip_empty_ends': True, 'cmd': None, 'argv': None, 'chdir': None, 'executable': None, 'creates': None, 'removes': None, 'stdin': None}}, 'stdout_lines': ['I can speak English'], 'stderr_lines': [], 'failed': False, 'item': 'English', 'ansible_loop_var': 'item'}) => { "msg": "Stdout: I can speak English" } |rc: ‘return code’ 반환코드
반환 코드 의미 0 성공 1 일반 오류 2 잘못된 인자 126 실행 권한 없음 127 명령 없음 130 Ctrl+C 종료 137 SIGKILL 139 Segmentation fault
조건문
조건작업 구문
when문은 조건부로 작업을 실행할때 조건으로 값을 사용한다.
--- - hosts: **localhost** vars: run_my_task: **true** tasks: - name: echo message ansible.builtin.**shell**: "echo test" **when: run_my_task** register: result - name: Show result ansible.builtin.**debug**: var: result root@server:~/my-ansible# ansible-playbook when_task.yml PLAY [localhost] ******************************************************************************** TASK [Gathering Facts] ************************************************************************** ok: [localhost] **TASK [echo message] ***************************************************************************** changed: [localhost]** TASK [Show result] ****************************************************************************** ok: [localhost] => { "result": { "changed": true, "cmd": "echo test", "delta": "0:00:00.004151", "end": "2026-01-14 23:49:23.953038", "failed": false, "msg": "", "rc": 0, "start": "2026-01-14 23:49:23.948887", "stderr": "", "stderr_lines": [], "stdout": "test", "stdout_lines": [ "test" ] } } PLAY RECAP ************************************************************************************** localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0#false로 수행시 echo message는 건너뜀 TASK [echo message] ***************************************************************************** skipping: [localhost]조건연산자
when절에 bool변수(true,false)외에 조건연산자도 사용이 가능하다.
연산 예시 설명 ansible_facts[’machine’] == “x86_64” ansible_facts[’machine’] 값이 x86_64와 같으면 true max_memory == 512 max_memory 값이 512와 같다면 true min_memory < 128 min_memory 값이 128보다 작으면 true min_memory > 256 min_memory 값이 256보다 크면 true min_memory <= 256 min_memory 값이 256보다 작거나 같으면 true min_memory >= 512 min_memory 값이 512보다 크거나 같으면 true min_memory != 512 min_memory 값이 512와 같지 않으면 true min_memory is defined min_memory 라는 변수가 있으면 true min_memory is not defined min_memory 라는 변수가 없으면 true memory_available memory 값이 true이며 true, 이때 해당 값이 1이거나 True 또는 yes면 true not memory_available memory 값이 false이며 true, 이때 해당 값이 0이거나 False 또는 no면 true ansible_facts[’distribution’] in supported_distros ansible_facts[’distribution’]의 값이 supported_distros 라는 변수에 있으면 true --- - hosts: all **vars**: supported_distros: - Ubuntu - CentOS tasks: - name: Print supported os ansible.builtin.debug: msg: "This {{ ansible_facts['distribution'] }} need to use **apt**" when: ansible_facts['distribution'] **in** supported_distros
TASK [print supported os] ***********************************************************************
ok: [tnode1] => {
"msg": "This Ubuntu need to use apt"
}
ok: [tnode2] => {
"msg": "This Ubuntu need to use apt"
}
```복수조건문
when은 단일조건외에 복수도 사용가능하다.
--- - hosts: all tasks: - name: Print os type ansible.builtin.debug: msg: >- OS Type: {{ ansible_facts['distribution'] }} OS Version: {{ ansible_facts['distribution_version'] }} when: > ( ansible_facts['distribution'] == "Rocky" and ansible_facts['distribution_version'] == "9.6" ) or ( ansible_facts['distribution'] == "Ubuntu" and ansible_facts['distribution_version'] == "24.04" ) TASK [Print os type] **************************************************************************** ok: [tnode1] => { "msg": "OS Type: Ubuntu OS Version: 24.04" } ok: [tnode2] => { "msg": "OS Type: Ubuntu OS Version: 24.04" } ok: [tnode3] => { "msg": "OS Type: Rocky OS Version: 9.6" }root@server:~/my-ansible# ansible tnode1 -m ansible.builtin.setup | grep -iE 'os_family|ansible_distribution|fqdn' "ansible_distribution": "Ubuntu", "ansible_distribution_file_parsed": true, "ansible_distribution_file_path": "/etc/os-release", "ansible_distribution_file_variety": "Debian", "ansible_distribution_major_version": "24", "ansible_distribution_release": "noble", "ansible_distribution_version": "24.04", "ansible_fqdn": "tnode1", "ansible_os_family": "Debian",
핸들러 및 작업 실패 처리
앤서블 핸들러
앤서블에서 핸들러를 사용할때는 notify문을 사용하여 명시적으로 호출된 경우에만 사용이 가능하다.
hosts: tnode2
tasks:- name: restart rsyslog
ansible.builtin.service:
name: "rsyslog"
state: restarted
notify:- print msg
handlers:
- name: print msg
ansible.builtin.debug:
msg: "rsyslog is restarted"
- name: restart rsyslog
RUNNING HANDLER [print msg] *********************************************************************
ok: [tnode2] => {
"msg": "rsyslog is restarted"
}
```작업실패무시
앤서블은 플레이 시 각 작업의 반환 코드를 평가하여 작업의 성공 여부를 판단합니다. 일반적으로 작업이 실패하면 앤서블은 이후의 모든 작업을 건너뜁니다.
하지만 작업이 실패해도 플레이를 계속 실행할 수 있습니다. 이는
ignore_errors라는 키워드로 구현할 수 있습니다.#아래와 같이 Print msg 태스크는 수행이 되지않는다. --- - hosts : **tnode1** tasks: - name: Install apache3 ansible.builtin.**apt**: name: **apache3** state: latest - name: Print msg ansible.builtin.**debug**: msg: "Before task is ignored"
root@server:~/my-ansible# ansible-playbook apache.yml
PLAY [tnode1] ***********************************************************************************
TASK [Gathering Facts] **************************************************************************
ok: [tnode1]
TASK [Install apache3] **************************************************************************
[ERROR]: Task failed: Module failed: No package matching 'apache3' is available
Origin: /root/my-ansible/apache.yml:5:7
3
4 tasks:
5 - name: Install apache3
^ column 7
fatal: [tnode1]: FAILED! => {"changed": false, "msg": "No package matching 'apache3' is available"}
PLAY RECAP **************************************************************************************
tnode1 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
```
```bash
# ignore_errors: yes 변수를 넣어주면 실패시에도 Print msg를 수행한다.
---
- hosts : **tnode1**
tasks:
- name: Install apache3
ansible.builtin.**apt**:
name: **apache3**
state: latest
**ignore_errors: yes**
- name: Print msg
ansible.builtin.**debug**:
msg: "Before task is ignored"
root@server:~/my-ansible# ansible-playbook apache.yml
PLAY [tnode1] ***********************************************************************************
TASK [Gathering Facts] **************************************************************************
ok: [tnode1]
TASK [Install apache3] **************************************************************************
[ERROR]: Task failed: Module failed: No package matching 'apache3' is available
Origin: /root/my-ansible/apache.yml:5:7
3
4 tasks:
5 - name: Install apache3
^ column 7
fatal: [tnode1]: FAILED! => {"changed": false, "msg": "No package matching 'apache3' is available"}
...ignoring
TASK [Print msg] ********************************************************************************
ok: [tnode1] => {
"msg": "Before task is ignored"
}
```작업 실패 조건지정
- shell과 같은 커맨드형 스크립트 사용시 멱등성 보장이 힘들다. 셸스크립트보다는 모듈을 사용하도록한다.
앤서블 블록 및 오류처리
block (작업 그룹화): 실행할 기본 작업들을 논리적으로 하나로 묶어 관리하는 단위
rescue (오류 복구):
block내 작업이 실패했을 때만 실행되는 예외 처리 및 복구 단계always (강제 실행): 작업의 성공이나 실패 여부와 상관없이 마지막에 반드시 수행되는 마무리 단계
hosts: tnode2
vars:
logdir: /var/log/daily_log
logfile: todays.logtasks:
name: Configure Log Env
block:- name: Find Directory
ansible.builtin.find:
paths: "{{ logdir }}"
register: result
failed_when: "'Not all paths' in result.msg"
rescue:
- name: Make Directory when Not found Directory
ansible.builtin.file:
path: "{{ logdir }}"
state: directory
mode: '0755'
always:
- name: Create File
ansible.builtin.file:
path: "{{ logdir }}/{{ logfile }}"
state: touch
mode: '0644'
- name: Find Directory
#첫수행
[ERROR]: Task failed: Action failed: Not all paths examined, check warnings for details
Origin: /root/my-ansible/block.yml:10:118 - name: Configure Log Env
9 block:
10 - name: Find Directory^ column 11fatal: [tnode2]: FAILED! => {"changed": false, "examined": 0, "failed_when_result": true, "files": [], "matched": 0, "msg": "Not all paths examined, check warnings for details", "skipped_paths": {"/var/log/daily_log": "'/var/log/daily_log' is not a directory"}}
#다시수행
root@server:~/my-ansible# ansible-playbook block.ymlPLAY [tnode2] ***
TASK [Gathering Facts] **
ok: [tnode2]TASK [Find Directory] ***
ok: [tnode2]TASK [Create File] **
changed: [tnode2]PLAY RECAP **
tnode2 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
롤 구조 소개 및 사용법
재사용 및 모듈화: 플레이북 내용을 기능 단위로 쪼개어 부품처럼 관리하며, 언제든 코드를 재사용할 수 있는 구조
효율적인 관리와 협업: 변수 설정 및 대규모 프로젝트 관리가 용이해져 여러 개발자가 동시에 작업유용
생태계 활용: 잘 만든 롤은 앤서블 갤럭시(Ansible Galaxy)를 통해 전 세계 사용자와 공유하거나 가져다 쓸 수 있다
롤생성
root@server:~/my-ansible# ansible-galaxy role -h usage: ansible-galaxy role [-h] ROLE_ACTION ... positional arguments: ROLE_ACTION init Initialize new role with the base structure of a role. remove Delete roles from roles_path. delete Removes the role from Galaxy. It does not remove or alter the actual GitHub repository. list Show the name and version of each role installed in the roles_path. search Search the Galaxy database by tags, platforms, author and multiple keywords. import Import a role into a galaxy server setup Manage the integration between Galaxy and the given source. info View more details about a specific role. install Install role(s) from file(s), URL(s) or Ansible Galaxy options: -h, --help show this help message and exit root@server:~/my-ansible# tree ./my-role/ ./my-role/ ├── defaults │ └── main.yml ├── files ├── handlers │ └── main.yml ├── meta │ └── main.yml ├── README.md ├── tasks │ └── main.yml ├── templates ├── tests │ ├── inventory │ └── test.yml └── vars └── main.yml 9 directories, 8 files플레이북 개발
#메인태스크 작성 ~/my-ansible/**my-role/tasks/main.yml --- # tasks file for my-role - name: install service {{ service_title }} ansible.builtin.apt: name: "{{ item }}" state: latest loop: "{{ httpd_packages }}" when: ansible_facts.distribution in supported_distros - name: copy conf file ansible.builtin.copy: src: "{{ src_file_path }}" dest: "{{ dest_file_path }}" notify: - restart service # index.html 생성** ~/my-ansible/**my-role/files/index.html root@server:~/my-ansible/my-role# echo "Study Let's go" > files/index.html # 핸들러 작성** ~/my-ansible/**my-role/handlers/main.yml** --- # handlers file for my-role - name: restart service ansible.builtin.**service**: name: "{{ service_name }}" state: **restarted #default(가변변수작성)** ~/my-ansible/**my-role/defaults/main.yml root@server:~/my-ansible/my-role# echo 'service_title: "Apache Web Server"' >> defaults/main.yml #vars(불변변수) ~/**my-ansible/**my-role/vars/main.yml**플레이북에 롤추가하기
~/my-ansible/**role-example.yml** --- - hosts: **tnode1** **tasks**: - name: Print start play ansible.builtin.**debug**: msg: "Let's start role play" - name: Install Service by role ansible.builtin.**import_role**: name: **my-role
##실행
root@server:~/my-ansible# ansible-playbook role-example.yml
PLAY [tnode1] ***********************************************************************************
TASK [Gathering Facts] **************************************************************************
ok: [tnode1]
TASK [Print start play] *************************************************************************
ok: [tnode1] => {
"msg": "Let's start role play"
}
TASK [my-role : install service Apache Web Server] **********************************************
changed: [tnode1] => (item=apache2)
changed: [tnode1] => (item=apache2-doc)
TASK [my-role : copy conf file] *****************************************************************
changed: [tnode1]
RUNNING HANDLER [my-role : restart service] *****************************************************
changed: [tnode1]
PLAY RECAP **************************************************************************************
tnode1 : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0**
```앤서블 갤럭시
- 공식 공유 허브: 전 세계 사용자가 제작한 롤(Role)과 컬렉션(Collection)을 자유롭게 공유하고 찾는 저장소
- 빠른 구축:
ansible-galaxy명령어로 검증된 코드를 즉시 내려받아 자동화 시스템 구축 시간을 획기적으로 단축가능 - 표준화된 구조:
init기능을 통해 앤서블이 권장하는 표준 디렉터리 구조를 자동으로 생성하여 관리가 편리하다. - 커뮤니티 검증: 사용자 평점과 다운로드 수를 통해 신뢰할 수 있는 고품질의 자동화 코드를 선택하기 용이하다.
- 버전 및 의존성 관리: 특정 버전의 코드를 지정해 설치할 수 있어 프로젝트의 일관성과 안정성 보장
'Study > K8S-Deploy' 카테고리의 다른 글
| K8S) 1주차 과제 (0) | 2026.01.08 |
|---|
