Blocks allow for logical grouping of tasks and in play error handling. Most of what you can apply to a single task can be applied at the block level, which also makes it much easier to set data or directives common to the tasks. This does not mean the directive affects the block itself, but is inherited by the tasks enclosed by a block. i.e. a when will be applied to the tasks, not the block itself.

In the example above, each of the 3 tasks will be executed after appending the when condition from the block
and evaluating it in the task’s context. Also they inherit the privilege escalation directives enabling “become to root”
for all the enclosed tasks.

New in version 2.3: The name: keyword for block: was added in Ansible 2.3.

tasks:-name:Attempt and graceful roll back demoblock:-debug:msg:'Iexecutenormally'-command:/bin/false-debug:msg:'Ineverexecute,duetotheabovetaskfailing'rescue:-debug:msg:'Icaughtanerror'-command:/bin/false-debug:msg:'Ialsoneverexecute:-('always:-debug:msg:"Thisalwaysexecutes"

The tasks in the block would execute normally, if there is any error the rescue section would get executed
with whatever you need to do to recover from the previous error. The always section runs no matter what previous
error did or did not occur in the block and rescue sections. It should be noted that the play continues if a
rescue section completes successfully as it ‘erases’ the error status (but not the reporting), this means it won’t trigger max_fail_percentage nor any_errors_fatal configurations but will appear in the playbook statistics.

tasks:-name:Attempt and graceful roll back demoblock:-debug:msg:'Iexecutenormally'notify:run me even after an error-command:/bin/falserescue:-name:make sure all handlers runmeta:flush_handlershandlers:-name:run me even after an errordebug:msg:'Thishandlerrunsevenonerror'

New in version 2.1.

Ansible also provides a couple of variables for tasks in the rescue portion of a block:

ansible_failed_task

The task that returned ‘failed’ and triggered the rescue. For example, to get the name use ansible_failed_task.name.

ansible_failed_result

The captured return result of the failed task that triggered the rescue. This would equate to having used this var in the register keyword.