1.引用变量
# 变量引用方式
"{{ }}"
2.定义变量 (vars)
- hosts: web
# 定义变量
vars:
- play_var: This_is_play_vars
tasks:
- name: touch new files
file:
# 引用变量
path: "/tmp/{{ play_var }}"
state: touch
3.定义变量文件 (vars_files)
# 定义变量文件 var.yml
# cat var.yml
play_var1: play_var1_sb1
play_var2: play_var2_sb2
# 测试剧本: cat web_test.yml
- hosts: web
#引用变量文件
vars_files:
- ./var.yml
tasks:
- name: touch new files
# 引用变量
file:
name: "/tmp/{{ play_var1 }}"
state: touch
4.主机清单中定义变量 (inventory)
# cat hosts
[web]
172.16.1.7
172.16.1.8
172.16.1.9
# 定义web组的变量,仅web组可使用
[web:vars]
inventory_var=inventory_variables
# 测试剧本: cat web_test.yml
- hosts: web
tasks:
- name: touch new files
file:
path: "/tmp/{{ inventory_var }}"
state: touch
5.定义主机变量 (host_vars)
# 创建主机变量目录
mkdir host_vars
# 创建主机变量文件
touch host_vars/172.16.1.7
# cat host_vars/172.16.1.7
host_var: host_var172.16.1.7
# cat host_vars/172.16.1.8
host_var: host_var172.16.1.8
6.定义主机组变量 (group_vars)
# 创建组变量目录
mkdir group_vars
# 创建组变量文件
touch group_vars/web
# cat group_vars/web
group_vars: group_vars_web
# cat web_test.yml
- hosts:
tasks:
- name: touch new files
file:
path: "/tmp/{{ group_vars }}"
state: touch
# 创建所有主机组变量文件
touch group_vars/all
# cat group_vars/all
group_all: group_all_test
# cat web_test.yml
- hosts:
tasks:
- name: touch new files
file:
path: "/tmp/{{ group_all }}"
state: touch
# cat web_test.yml
- hosts: all
tasks:
- name: touch new files
file:
path: "/tmp/{{ extra_vars }}"
state: touch
# 命令行传参
ansible-playbook web_test.yml -e "extra_vars=123"
8.定义变量的优先级
# 命令行
1. extra
# playbook
2. vars
3. vars_files
# inventory
4. host_vars
5. group_vars
6. group_all
# 可通过debug模块测试
- hosts: web
tasks:
- name: touch new files
debug:
msg: "{{ extra_vars }}"
9.变量注册register
- hosts: web
tasks:
- name: Output Nginx Process
shell: ps aux| grep nginx
# 注册变量
register: nginx_process
- name:
debug:
msg: "{{ nginx_process.stdout_lines }}"
10.核心变量 facts
# 查看ansible可调用系统变量
ansible localhost -m setup
# 调用系统变量,查看系统IP
- hosts: web
tasks:
- name:
debug:
msg: "{{ ansible_eth1.ipv4.address }}"