條件判斷語句 when
- when 的基本用法
when 是條件判斷語句,類似編程語言的if
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/command
when: result |failed
- commadn: /bin/command_else
when: result|success
- command: /bin/command_else_else
when: result|skipped
- 與include一起使用
- include: tasks/sometasks.yml
when: “‘reticulating splines’ in output”
- 與role 一起使用
- host: all
roles:
- {role: debian_stock_config, when: ansible_os_family == 'debian'}
loop 循環(huán)
- 字典循環(huán)
with_items 用于迭代的list類型變量,支持簡單的字符列表,哈希列表
- name: add several users
user: name{{item.name}} state=present groups={{item.groups}}
with_iterms:
- {name: 'name1', groups: 'group1'}
- {name" 'name2', groups: 'group2'}
使用 .號訪問內(nèi)層和外層的變量
- 循環(huán)也可以嵌套,使用[ ]訪問內(nèi)層和外層的循環(huán),例如item[0]
- 對哈希表的循環(huán)
在變量文件中或者使用vars區(qū)域定義了一組列表變量items,可以這樣使用
vars:
items: ["user1","user2"]
tasks:
....
with_items: "{{iterms}}"
with_dict: "{{字典名}}"
- 文件循環(huán)(with_file, with_fileglob)
with_file 是將每個(gè)文件的文件內(nèi)容作為item的值
with_fileglob 是將每個(gè)文件的全路徑作為item的值, 在文件目錄下是非遞歸的, 如果是在role里面應(yīng)用改循環(huán), 默認(rèn)路徑是roles/role_name/files_directory
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:
- /playbooks/files/fooapp/*
bolck 塊
- 使用block關(guān)鍵字可以將多個(gè)任務(wù)整合成一個(gè)塊,把這個(gè)塊當(dāng)成一個(gè)整體,對這個(gè)塊進(jìn)行判斷,當(dāng)條件成立時(shí),執(zhí)行塊中的所以語句
tasks:
- debug:
msg: "task1 not in block"
- block:
- debug:
msg: "task2 in block1"
- debug:
msg: "task3 in block1"
when: 2 > 1
- 錯(cuò)誤處理功能
錯(cuò)誤處理功能就是當(dāng)任務(wù)出錯(cuò)時(shí),執(zhí)行指定的其他任務(wù)
**failed 的用法**
tasks:
- block:
- shell: 'ls /ooo'
rescue:
- debug:
msg: 'I caught an error'
**rescue的用法**
tasks:
- block:
- shell: 'ls /opt'
- shell: 'ls /testdir'
- shell: 'ls /c'
rescue:
- debug:
msg: 'I caught an error'
always:
- debug:
msg:"this always executes"
如上例所示,block中有三個(gè)任務(wù),這三個(gè)任務(wù)中的任何一個(gè)任務(wù)錯(cuò)了,就會執(zhí)行rescue中的任務(wù),所以通常會使用block和rescue結(jié)合,完成“錯(cuò)誤捕捉,報(bào)出異常”的功能
我們還可以加入always關(guān)鍵字,加入always以后,無論block中的任務(wù)執(zhí)行成功還是失敗,always中的任務(wù)總是被執(zhí)行。