ansible基礎 Jinja2模版 測試

2021-09-11 23:25:25 字數 3358 閱讀 4513

注:本文demo使用ansible2.7穩定版

jinja2的測試語句被用來評估乙個條件表示式,並且最終返回true或false,經常和「when」語句搭配使用。

測試語句和過濾器的相同點:測試語句的條件表示式也在控制端執行,在目的主機端生效。

測試語句和過濾器的不同點:

測試語句的語法很簡單,寫法如下:

variable is test_name
舉個?,task執行結果為failed時,則返回true:

result is failed
關鍵字「match」和「search」,引數可以使用正規表示式,用來查詢乙個字串是否與測試語句相匹配。

vars:

url:

""tasks:

-debug:

msg:

"matched pattern 1

"when: url is match(

"")-debug:

msg:

"matched pattern 2

"when: url is search(

"/users/.*/resources/.*")

-debug:

msg:

"matched pattern 3

"when: url is search(

"/users/

")

通過上面示例,我們可以看出:

關鍵字「version」(舊版本為「version_compare」),用於比較版本號。

例如,測試當前centos作業系統的版本號是否大於等於「7.2.1511」,可以這樣寫:

}
如果當前作業系統版本號大於或等於「7.2.1511」,條件表示式返回true,否則返回false。

「version」接受的運算子如下:

, gt, >=, ge, ==, =, eq, !=, <>, ne
「version」也可以接受「strict」引數,這個引數預設值為「false」,如果設定為「true」則ansible會進行更嚴格的版本檢查:

}
關鍵字「superset」和「subset」,用於測試乙個列表是否包含或被包含於另乙個列表:

vars:

a: [

1,2,3,4,5

] b: [

2,3]

tasks:

-debug:

msg:

"a includes b

"when: a is superset(b)

-debug:

msg:

"b is included in a

"when: b is subset(a)

關鍵字「all」和「any」,用於檢查列表裡的元素的真假:

vars:

mylist:

- 1- "}"

-true

myotherlist:

-false

-true

tasks:

-debug:

msg:

"all are true!

"when: mylist is all

-debug:

msg:

"at least one is true

"when: myotherlist is any

用大學學的離散數學概括下:

all:一假則假

any:一真則真

測試檔案路徑的關鍵字從字面上就能看出來其含義,下面直接上示例:

-debug:

msg:

"path is a directory

"when: mypath is directory

-debug:

msg:

"path is a file

"when: mypath is

file

-debug:

msg:

"path is a symlink

"when: mypath is link

-debug:

msg:

"path already exists

"when: mypath is exists

-debug:

msg:

"path is }

"-debug:

msg:

"path is the same file as path2

"when: mypath is same_file(path2)

-debug:

msg:

"path is a mount

"when: mypath is

mount

注:這個特性在ansible>=2.5的版本中才有,在生產實踐中,可以替換舊版本中「stat」+「register」+「when」實現的功能。測試任務執行結果也比較通俗易懂,示例如下:

mauricewei 閱讀(

...)

編輯收藏

Ansible中使用jinja2模板部署自定義檔案

ansible將jinja2模板系統用於模板檔案。ansible允許jinja2模板中使用if條件判斷和for迴圈,但是不允許在playbook中使用 1.輸出變數值,會輸出自定義的變數值或facts 2.playbook檔案使用template模組 3.模板檔案裡面變數使用 比如 或使用facts...

Jinja2在Ansible中常用項

過濾器 內容safe 渲染時值不轉義 capitialize 把值的首字母轉換成大寫,其他子母轉換為小寫 lower 把值轉換成小寫形式 upper 把值轉換成大寫形式 title 把值中每個單詞的首字母都轉換成大寫 trim 把值的首尾空格去掉 striptags 渲染之前把值中所有的html標籤...

python模板引擎Jinja2基礎

官方文件 分隔符 delimiters 語句 statements 列印模板輸出的表示式 expressions 注釋 行語句 line statements 變數 variables foo.bar foo bar 過濾器 filters title striptags name 過濾器列表 測試...