Ansible Playbook Grouping Plays with Block

Ansible Playbook Grouping Plays with Block

Playbooks can group plays using <span>block</span>, not only for grouping, but <span>block</span> can also handle task errors during the execution of the <span>block</span>.

<span>block</span> handles errors in two ways:

  • <span>rescue</span>: This task will only execute if a task within the <span>block</span> returns a failed status.
  • <span>always</span>: This will execute regardless of whether any tasks in the <span>block</span> fail.
- name: block
  hosts: webserver
  gather_facts: true
  tasks:
  - name: System initialization task block
    when: ansible_os_family == 'RedHat'
    become: true
    block:
    - name: install packages
      ansible.builtin.dnf:
        name: "{{ packages_list }}"
        state: present
      vars:
        packages_list:
        - vim
        - bash-completion
    - name: disable selinux
      ansible.builtin.selinux:
        policy: targeted
        state: permissive
    rescue:
    - name: print error
      ansible.builtin.debug:
        msg: "Task execution failed, please check!"
    always:
    - name: create data directory
      ansible.builtin.file:
        path: /data
        state: directory
        mode: '0755'

If the <span>block</span> executes with failed tasks, but the tasks in <span>rescue</span> execute successfully (effectively rescuing), then this node will not be removed from the Playbook execution queue, and subsequent tasks will continue to execute on this node.

<span>block</span> can check for failed task information using the following two variables:

  • <span>ansible_failed_task</span> (you can use <span>ansible_failed_task.name</span> to get the name of the failed task)
  • <span>ansible_failed_result</span> (similar to a variable set by registering a failed task)
- name: print ansible_failed_task.name
  ansible.builtin.debug:
    var: ansible_failed_task.name
- name: print ansible_failed_result
  ansible.builtin.debug:
    var: ansible_failed_result

Leave a Comment