Ansible 变量优先级
优先级是从高到低
- 命令行设置的变量优先级最高
- role 中的 vars 变量
- playbook 中定义的变量其次
- host_vars 目录和 group_vars 目录的变量(host_vars 优先于 group_vars)
- inventory 变量
- role 中的 default 变量
- 变量名相同,高优先级会覆盖低优先级变量
- 变量名相同,主机变量会覆盖主机组变量
- 变量名相同,子组覆盖嵌套组的变量
感觉只要变量不重名应该就不涉及优先级问题。
变量的条件判断
判断的类型
针对变量有以下判断方法:
条件判断类型 | 示例 |
---|---|
等于(字符串) | ansible_machine == "x86_64" |
等于(数字) | ansible_distribution_major_version == 8 |
小于 | ansible_memfree_mb < 1024 |
大于 | ansible_memfree_mb > 1024 |
小于等于 | ansible_memfree_mb <= 1024 |
大于等于 | ansible_memfree_mb >= 1024 |
不等于 | ansible_memfree_mb != 1024 |
变量存在 | custom_var is defined |
变量不存在 | custom_var is not defined |
布尔变量为 True。True、Yes 或 1 | ansible_selinux_python_present |
布尔变量为 False。False、No 或 0 | not ansible_selinux_python_present |
第一个变量存在,且在第二个变量的列表里 | ansible_distribution in supported_distros |
变量是否为空 | custom_var == "" |
变量是否不为空 | custom_var != "" |
变量是路径时的文件类型 | custom_var is file (directory、link、mount、exists) |
通过
ansible -e
或ansible-playbook -e
设置的变量为字符串。布尔变量需要用
var=true
和var=false
设置。数字需要通过
json
方式设置:'{ "var": 100 }'
。
判断可以组合使用,比如:
-
custom_var is defined and custom_var == "RedHat"
-
ansible_distribution == "Rocky" or (custom_var is defined and custom_var == "Linux")
-
多个判断可以用列表
when: - my_var is defined - my_var == 'abc'
例子
---
- name: test
hosts: localhost
tasks:
- name: test
debug:
msg:
- "{{ ansible_facts.hostname }}"
when: ansible_distribution == "Rocky" or (custom_var is defined and custom_var == "Linux")
列表变量和字典变量
变量有列表和字典两种。
列表
列表是一个有序的元素集合,元素可以是数字、字符串、字典、甚至是另一个列表。可以通过下标访问列表的元素。
以下是列表变量定义的方式:
list_var1:
- var1
- var2
- var3
list_var2: [ "var4", "var5", "var6" ]
字典
字典是一个无序的键值对集合,每个键都有对应的值。字典可以嵌套,键和值的类型可以是任何数据类型。
以下是字典变量定义的方式:
dict_var1:
var7: 7
var8: "eight"
dict_var2: { var9: "nine", var10: 10 }
列表和字典的混合
list_var:
- var1: 1
- var2: "two"
dict_var:
var3:
- var3_1
- var3_2
var4: "four"
遍历变量
遍历变量通过 loop
实现,以下是一个在 Playbook 遍历变量的例子:
---
- name: test
hosts: localhost
vars:
user_list:
- name: "root"
password: "redhat"
host: "192.168.1.1"
- name: "admin"
password: "redhat"
host: "192.168.1.2"
tasks:
- name: loop list
debug:
msg: "{{ item }}"
loop: "{{ user_list }}"
- name: loop list.name
debug:
msg: "{{ item.name }}"
loop: "{{ user_list }}"
早版本的 Ansible 可能会有
with_items
或with_dict
,不过已经被淘汰了(可能还支持),新版本统一用loop
。