自动化运维—playbook(应用变量)
1.定义变量
变量名应该由字母、数字、下划线组成,变量名需要以字母开头,ansible内的关键字不能作为变量名。
2.在playbook中使用变量
如果我们想要在某个play中定义变量,可以借助vars关键字
除了能够在playbook中直接定义变量:我们还可以在某个文件中定义变量,然后再在playbook中引入对应的文件,引入文件后,playbook即可使用文件中定义的变量
vim var1.yml
---
- hosts: testB
vars:
testvar1: testfile
remote_user: root
tasks:
- name: task1
file:
path=/testdir/{{ testvar1 }}
state=directory
执行:
ansible-playbook var1.yml
语法2(YAML块序列语法):
vars:
- testvar1: testfile
3.定义多个变量
定义多个变量:
vars:
testvar1: testfile1
testvar2: testfile2
除了使用上述语法,使用YAML的块序列语法也可以定义变量, 示例如下:
vars:
- testvar1: testfile1
- testvar2: testfile2
vim var1.yml
---
- hosts: testB
vars:
- testvar1: testfile
- testvar2: testfile2
remote_user: root
tasks:
- name: task1
file:
path=/testdir/{{ testvar1 }}
state=directory
- name: task2
file:
path=/testdir/{{ testvar2 }}
state=directory
执行:
ansible-playbook var1.yml
4.定义变量参数
当我们需要引用这两个变量时,有两种语法可用语法:
语法一
"{{httpd.conf80}}"
语法二
"{{nginx['conf8080']}}"
语法一应用:
vim var2.yml
---
- hosts: testB
remote_user: root
vars:
httpd:
conf80: /etc/httpd/conf.d/80.conf
conf8000: /etc/httpd/conf.d/8000.conf
tasks:
- name: task1
file:
path: "{{httpd.conf80}}"
state: touch
- name: task2
file:
path: "{{httpd.conf8000}}"
state: touch
语法2:
---
- hosts: testB
remote_user: root
vars:
httpd:
conf80: /etc/httpd/conf.d/80.conf
conf8000: /etc/httpd/conf.d/8000.conf
tasks:
- name: task1
file:
path: "{{httpd['conf80']}}"
state: touch
- name: task2
file:
path: "{{httpd['conf8000']}}"
state: touch
还可以使用=(不需要引号):
---
- hosts: testB
remote_user: root
vars:
httpd:
conf80: /etc/httpd/conf.d/80.conf
conf8000: /etc/httpd/conf.d/8000.conf
tasks:
- name: task1
file:
path={{httpd['conf80']}}
state=touch
- name: task2
file:
path={{httpd['conf8000']}}
state=touch
5.文件变量分离
如果我们定义了变量,但又不想把变量的值直接写在剧本里,可以采用这种方法:将变量的值写在文件中
注意:文件名也是要以.yml结尾,而文件中的语法也要使用YAML语法
vars_ files关键字也可以引入多个变量文件,每个被引入的文件都需要以"- "开头
vars files:
- /testdir/ansible/nginx_vars.yml
- /testdir/ansible/other_vars.yml
vars关键字和vars_ files关键字可以同时使用,如下:
vars:
- conf90: /etc/nginx/conf.d/90.conf
vars_files:
- /testdir/ansible/nginx_vars.yml
vim var2.yml
---
- hosts: testB
remote_user: root
vars_files:
- httpd_vars.yml
tasks:
- name: task1
file:
path={{httpd['conf80']}}
state=touch
- name: task2
file:
path={{httpd['conf8000']}}
state=touch
vim httpd_vars.yml
httpd:
conf80: /etc/httpd/conf.d/80.conf
conf8000: /etc/httpd/conf.d/8000.conf
ansible-playbook var2.yml