template module 是冻仁常用的档案模组 (Files Modules) 之一,先前在「Ansible 常用的 Ansible Module」一章时,也曾提到可以用它和变数 (Variables) 来操作档案。
我们只需事先定义变数和模板 (Templates),即可用它动态产生远端的 Shell Scripts、设定档 (Configure) 等。换句话说,我们可以用一份 template 来产生开发 (Development)、测试 (Test) 和正式环境 (Production) 等不同的环境设定。
举例说明:
说了那么多,还是举个小例子说明吧!
1.建立 template 档案:
$ vi hello_world.txt.j2 Hello "{{ dynamic_word }}" ↑ ↑ ↑
由于 Ansible 是借由 Jinja2 来写作 template 系统,所以请使用 *.j2 的副档名。
上面的"{{ dynamic_word }}"代表我们在此 template 里使用了名为 dynamic_word 的变数。
2.建立 playbook,并加入变数。
template_demo.yml
---
- name: Play the template module
hosts: localhost
vars:
dynamic_word: "World"
tasks:
- name:
generation the hello_world.txt file
template: src: hello_world.txt.j2
dest: /tmp/hello_world.txt
- name: show file context
command: cat /tmp/hello_world.txt
register: result
- name: print stdout
debug:
msg: ""
# vim:ft=ansible :
在第 6 行,我们帮 dynamic_word 变数设了一个预设值 World。
在第 9 行的第 1 个 task 里,我们使用了 template module,并指定了档案的来源 (src) 和目的地 (dest)。
之后的 2 个 tasks 则是把 template module 产生出来的档案给印出来
3.执行 playbook。
$ ansible-playbook template_demo.yml
通过 -e 参数将 dynamic_word 覆写成 ansible。
$ ansible-playbook template_demo.yml -e "dynamic_word=ansible"
通过 -e 参数将 dynamic_word 覆写成 Day14。
$ ansible-playbook template_demo.yml -e "dynamic_word=Day14"
怎么让 Playbooks 切换不同的环境?
1.在 Playbooks 里除了用 vars 来宣告变数以外,还可以用 vars_files 来 include 其它的变数档案。
$ vi template_demo2.yml
---
- name: Play the template module
hosts: localhost
vars:
env: "development"
vars_files:
- vars/.yml
tasks:
- name: generation the hello_world.txt file
template:
src: hello_world.txt.j2
dest: /tmp/hello_world.txt
- name: show file context
command: cat /tmp/hello_world.txt
register: result
- name: print stdout
debug:
msg: ""
# vim:ft=ansible :
2.建立 vars/development.yml, vars/test.yml 和 vars/production.yml 档案,接下来将依不同的环境 include 不同的变数档案 (vars files),这样就可以用同一份 playbook 切换环境了!
$ vi vars/development.yml
dynamic_word: "development"
Test
$ vi vars/test.yml
dynamic_word: "test"
Production
$ vi vars/production.yml
dynamic_word: "production"
3.执行playbook,并通过 -e 切换各个环境。
如果觉得我的文章对您有用,请点赞。您的支持将鼓励我继续创作!
赞0
添加新评论0 条评论