template module 是凍仁常用的檔案模組 (Files Modules) 之一,先前在「Ansible 常用的 Ansible Module」一章時(shí),也曾提到可以用它和變數(shù) (Variables) 來操作檔案。
圖片來源:http://www.freeiconspng.com/free-images/txt-file-icon-1203
我們只需事先定義變數(shù)和模板 (Templates),即可用它動(dòng)態(tài)產(chǎn)生遠(yuǎn)端的 Shell Scripts、設(shè)定檔 (Configure) 等。換句話說,我們可以用一份 template 來產(chǎn)生開發(fā) (Development)、測(cè)試 (Test) 和正式環(huán)境 (Production) 等不同的環(huán)境設(shè)定。
說了那么多,還是讓凍仁舉個(gè)小例子說明吧!
$ vi hello_world.txt.j2 Hello "{{ dynamic_word }}" ↑ ↑ ↑
2.建立 playbook,并加入變數(shù)。
$ vi 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 :
3.執(zhí)行 playbook。
$ ansible-playbook template_demo.yml
-e
參數(shù)將 dynamic_word
覆寫成 ansible。$ ansible-playbook template_demo.yml -e "dynamic_word=ansible"
-e
參數(shù)將 dynamic_word
覆寫成 Day14。$ ansible-playbook template_demo.yml -e "dynamic_word=Day14"
vars
來宣告變數(shù)以外,還可以用 vars_files
來 include 其它的變數(shù)檔案。$ 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 :
vars/development.yml
, vars/test.yml
和 vars/production.yml
檔案,接下來將依不同的環(huán)境 include 不同的變數(shù)檔案 (vars files),這樣就可以用同一份 playbook 切換環(huán)境了!
$ vi vars/development.yml
dynamic_word: "development"
$ vi vars/test.yml
dynamic_word: "test"
$ vi vars/production.yml
dynamic_word: "production"
3.執(zhí)行playbook,并通過 -e
切換各個(gè)環(huán)境。
template 系統(tǒng)是實(shí)務(wù)上很常見的手法之一,藉由它我們可以很輕鬆的讓開發(fā)、測(cè)試和正式環(huán)境無縫接軌。
現(xiàn)在是不是有寫 code 管機(jī)器的感覺了呢?(笑)
更多建議: