Ansible
Ansible Variables
코딩+아빠
2023. 6. 27. 21:29
앤서블은 플레이북에서 재활용할 수 있도록 변수(variable)를 지원한다.
변수는 다음과 같이 반복적이거나 동적인 값을 관리할 때 편리하다.
- 여러 사용자를 생성
- 여러 패키지를 설치
- 여러 서비스를 재시작
변수 정의하기
플레이북 안에 변수를 정의할 경우 시작 위치에 있는 vars 블록에 변수를 정의한다.
인벤토리에서는 각각의 host 명을 정의하기도 한다
{{ }} 안에 변수명을 입력하여 host ip를 대체할 수 있다.

playbook1.yaml
-
name: 'Update nameserver entry into resolv.conf file on localhost'
hosts: localhost
tasks:
-
name: 'Update nameserver entry into resolv.conf file'
lineinfile:
path: /etc/resolv.conf
line: 'nameserver {{ nameserver_ip }}'
-
name: 'Disable SNMP Port'
firewalld:
port: '{{ snmp_port }}'
permanent: true
state: disabled
Inventory
# Sample Inventory File
localhost ansible_connection=localhost nameserver_ip=10.1.250.10 snmp_port=160-161
playbook 내부 변수관리
-
name: 'Update nameserver entry into resolv.conf file on localhost'
hosts: localhost
vars:
car_model: 'BMW M3'
country_name: 'USA'
title: 'Systems Engineer'
tasks:
-
name: 'Print my car model'
command: 'echo "My car''s model is {{ car_model }}"'
-
name: 'Print my country'
command: 'echo "I live in the {{ country_name }}"'
-
name: 'Print my title'
command: 'echo "I work as a {{ title }}"'
반응형