在说block用法之前,先说一下ansible的yaml文件中判断的使用,符合when的条件的时候,执行,不满足条件就不执行,例如:
- name: when用法举例
hosts: all
tasks:
- name: 修改文件权限
file: src=/root/test.txt.j2 dest=/opt/test.txt mode=0644
when: '$USER=root'
再来看block的例子:
- name: block的用法
hosts: node
tasks:
- debug:
msg: "task1 not in block"
- block:
- debug:
msg: "task2 in block1"
- debug:
msg: "task3 in block1"
when: 2 > 1
是的,当when的判断语句一样时,可以将任务合并,写起来省力一点。此外,block除了能和when结合起来使用,还有一个很重要的功能,就是"错误处理"功能。
不用block:
- hosts: test
remote_user: root
tasks:
- shell: 'cat /etc/redhat-release'
register: stdout_info
ignore_errors: true
rescue:
- debug:
msg: 'I caught an error'
when: 'stdout_info is failed'
使用block:
- hosts: test
remote_user: root
tasks:
- block:
- shell: 'cat /etc/redhat-release'
rescue:
- debug:
msg: 'I caught an error'
如上例所示,定义了一个block,这个block中有一个任务,这个任务在目标主机中执行了’‘cat /etc/redhat-release’''命令,除了block关键字,还有另外一个关键字rescue,rescue关键字与block关键字对齐,rescue的字面意思为"救援",表示当block中的任务执行失败时,会执行rescue中的任务进行补救,当然,在rescue中定义什么任务,是由你决定的。
也就是说当block中的任务出错时,会执行rescue中的任务,当block中的任务顺利执行时,则不会执行rescue中的任务。
你可能会问,使用block的方法完成"错误处理"的功能,似乎与使用failed的方法并没有什么不同,除了代码似乎"精简"了一点,block还有其他优势么?其实,使用block的方式还是有一定优势的,当block中有多个任务时,这种优势就比较明显了:
---
- hosts: testuser
remote_user: root
tasks:
- block:
- debug:
msg: 'I execute normally'
- command: /bin/false
- debug:
msg: 'I never execute, due to the above task failing'
rescue:
- debug:
msg: 'I caught an error'
- command: /bin/false
- debug:
msg: 'I also never execute'
always:
- debug:
msg: "This always executes"
when: 2>1
cmd加解密网站:
md5解密