Playbook中变量的使用

变量定义

变量名

仅字母、数字和下划线组成,且只能以字母开头

playbook中变量的表示以及赋值

使用{{}} mustache语法,运行playbook时添加-e 参数为变量赋值。

  1. setup模块

内置的setup模块,用于查询内置变量。

1
2
3
4
5
6
7
8
9
- name: Gathers facts about remote hosts
setup:
fact_path: # Path used for local ansible facts (`*.fact') - files in this dir will be run (if executable) and their results be added to `ansible_local' facts if a file is not executable it is read. Check notes for Windows options. (from 2.1 on) File/results format can be JSON or INI-format. The default `fact_path' can be specified in `ansible.cfg' for when setup is automatically called as part of `gather_facts'.
filter: # 过滤内容,支持通配符 # If supplied, only return facts that match this shell-style (fnmatch) wildcard.
gather_subset: # If supplied, restrict the additional facts collected to the given subset. Possible values: `all', `min', `hardware', `network', `virtual', `ohai', and `facter'. Can specify a list of values to specify a larger subset. Values can also be used with an initial `!' to specify that that specific subset should not be collected. For instance: `!hardware,!network,!virtual,!ohai,!facter'. If `!all' is specified then only the min subset is collected. To avoid collecting even the min subset, specify `!all,!min'. To collect only specific facts, use `!all,!min', and specify the particular fact subsets. Use the filter parameter if you do not want to display some collected facts.
gather_timeout: # Set the default timeout in seconds for individual fact gathering.

#cmdline
ansible host -m setup -a 'filter=<..>'
  1. 在playbook中定义变量
1
2
3
4
5
- hosts:
remote_user:
vars:
- var1: #变量值1
- var2: #变量值2
  1. 利用命令行指定变量

优先级

命令行的优先级要高于配置文件。

1
ansible-playbook -e 'var1=value1 var2=value2' file.yaml
  1. /etc/ansible/hosts中定义

主机清单中定义变量

分为普通变量公共(组)变量,普通变量优先级高于公共(组)变量。

1
2
3
4
5
[websrvs]
192.168.1.10 var1=value1 var2=value2 #普通变量
[websrvs:vars] #公共(组)变量
var3=value3
var1=value0 #由于普通变量优先于公共(组)变量,所以此处不会应用于192.168.1.10主机

为了避免混乱,还可以采用文件的形式来定义。

  1. 在外部yaml文件定义变量并在playbook中引用
1
echo -e "var1:value1\nvar2:value2" >> /etc/ansible/vars.yaml

在playbook文件中,使用vars_files引用外部文件

1
2
3
4
5
6
7
8
9
---
- hosts:
remote_user:
vars_files:
- /path/to/vars.yaml

tasks:
- name:
<moduel>:
  1. 在role文件中定义变量

模板templates

使用Jinja2语法

注意

template模块只能在playbook文件中使用。

1
2
3
4
5
6
7
8
9
10
11
---
- hosts: ubuntu
remote_user: root

tasks:
- name: install package
apt: name=nginx
- name: copy template
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
- name: start service
service: name=nginx state=started enabled=yes

在playbook文件使用条件判断

when语句

在task后添加when子句可用于条件测试

补充

when语句还支持Jinja2表达式语法。 如:when: var=="value"

1
2
3
4
5
6
7
8
9
10
11
12
---
- hosts: ubuntu
remote_user: root

tasks:
- name: install package
apt: name=nginx
- name: copy template
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
when: var=="value“
- name: start service
service: name=nginx state=started enabled=yes