6.ansible变量
ansible变量的作用
方便剧本的修改 把可变化的值做成变量 方便剧本的复用
ansible变量的定义方式
1.通过执行命令传入
ansible-playbook install_frpc.yaml -e Server=192.168.1.39 -e Local_Port=22 -e Remote_Port=40022 -e Project=test
2.定义vars或者varfiles
vars
cat vars.yaml
- hosts: webservers
tasks:
- name: Install Packages
yum:
name: {{ Pack }}
state: present
vars:
Pack:
- vim
- nginx
vars_files
1.定义vars_files(名称随便)
[root@zabbix ~]# cat vars_file.yaml
ansible_path: /etc/ansible
ansible_exe: /usr/local/sbin
2.ansible-playbook中调用
[root@zabbix ~]# cat var.yaml
- hosts: 192.168.1.43
vars_files:
- ./vars_file.yaml
tasks:
- name: Print Vars
debug:
msg:
- "{{ ansible_path }}"
- "{{ ansible_exe }}"
3.验证
[root@zabbix ~]# ansible-playbook ./var.yaml
PLAY [192.168.1.43] *****************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.43]
TASK [Print Vars] *******************************************************************************************************************************************
ok: [192.168.1.43] => {
"msg": [
"/etc/ansible",
"/usr/local/sbin"
]
}
PLAY RECAP **************************************************************************************************************************************************
192.168.1.43 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
3.在invertory文件中定义
主机和主机组变量
定义server1.example.com的ansible_user主机变量:
[webservers]
server1.example.com ansible_user=student`
定义dbservers主机组的user组变量:
[dbserver]
dbserver1.example.com
dbserver2.example.com
[dbservers:vars]
user=student
定义嵌套组user变量:
[servers1]node1.example.comnode2.example.com
[servers2]node3.example.comnode4.example.com
[servers:children]
servers1
servers2
[servers:vars]
user=studen
1.在剧本中设置变量信息
方式一:直接在剧本文件编写 优先02
vars:
oldboy01: data01
oldboy02: data02
实践配置:
[root@m01 ansible_playbook]# cat test_变量功能.yaml
- hosts: 172.16.1.7
vars:
src_dir: /etc/hosts
dest_dir: /opt
tasks:
- name: copy file
copy: src={{ src_dir }} dest={{ dest_dir }}
2.在命令行中进行指定 优先01
实践操作:
ansible-playbook -e src_dir=/etc/hosts -e dest_dir=/opt test_变量功能.yaml
PS:剧本中可以不用设置变量
3.在主机清单文件编写 优先03
[oldboy:vars]
oldboy01=data01
oldboy02=data02
实践配置:主机清单配置
[nfs_client]
172.16.1.7
172.16.1.41
[nfs_client:vars]
src_dir=/etc/hosts
dest_dir=/opt