Ansible 中 template 模块
template模块介绍
copy模块可以将文件拷贝给远程主机,但是如果希望每个拷贝的文件内容都不一样呢?比如给所有web主机拷贝index.html内容是各自的IP地址该如何实现?
Ansible使用template模块上传具有特定格式的文件(如文件中包含变量),当远程主机接收到文件之后,文件中的变量将会变成具体的值。template模块上传文件使用的语法叫Jinja2。Ansible利用Jinja2模板引擎读取变量,之前在playbook中调用变量,就是Jinja2的功能。Jinja2的表达式包含在分隔符"{{ }}"内。
template模块常用选项:
-
src:要上传的文件
-
dest:目标文件路径
使用template模块将含有变量的文件上传到webservers组中的主机,代码示意如下:
# 创建含有变量的文件
[root@pubserver ansible]# vim index.html
Welcome to {{ansible_hostname}} on {{ansible_ens160.ipv4.address}}
# 编写playbook
[root@pubserver ansible]# vim templ.yml
---
- name: upload index
hosts: webservers
tasks:
- name: create web index
template: # 调用template模块
src: index.html
dest: /usr/share/nginx/html/index.html
# 运行编写的playbook
[root@pubserver ansible]# ansible-playbook templ.yml
PLAY [upload index] *******************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [web2]
ok: [web1]
TASK [create web index] ***************************************************************************************************************************
changed: [web1]
changed: [web2]
PLAY RECAP ****************************************************************************************************************************************
web1 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
# 进入web1主机进行查看
[root@web1 ~]# cat /usr/share/nginx/html/index.html
Welcome to web1 on 192.168.88.11
# 进入web2主机进行查看
[root@web2 ~]# cat /usr/share/nginx/html/index.html
Welcome to web2 on 192.168.88.12