Skip to content

14. Blocks

在说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'