block就是一组逻辑的tasks。使用block可以将多个任务合并为一个组。还可以做错误处理,即当任务发生错误后,执行rescue任务。
# block:block里的tasks,如果运行正确,则不会运行rescue;
# rescue:block里的tasks,如果运行失败,才会运行rescue里的tasks
# always:block和rescue里的tasks无论是否运行成功,都会运行always里的tasks
示例:
- - hosts: test
- user: root
- gather_facts: false
-
- tasks:
- - name: copy file 0 to 1
- shell: cp /data/test/0 /data/test/1
- - block:
- - name: copy file1 a to b
- shell: cp /data/test/a /data/test/b
- - name: copy file2 c to e
- shell: cp /data/test/c /data/test/e
- rescue:
- - name: copy file3 b to d
- shell: cp /data/test/b /data/test/d
- always:
- - name: copy file4 f to g
- shell: cp /data/test/f /data/test/g
- - name: copy file5 h to i
- shell: cp /data/test/h /data/test/i
-
- #释#####################
- 正常执行任务shell cp 0 to 1
- 添加block任务
- 复制file1
- 复制file2
- 当2个任务中任一发生错误后,执行rescue任务中的复制file3
- 如复制file1出错,将跳过复制file2,而直接执行rescue任务
- 无论是否成功都会执行always复制file4
- (注意格式问题)复制file5也无论上面复制文件file1 file2是否失败都执行。
-
-