Grouping tasks using blocks
Blocks in Ansible allow you to logically group a set of tasks together, primarily for one of two purposes. One might be to apply conditional logic to an entire set of tasks; in this example, you could apply an identical when
clause to each of the tasks, but this is cumbersome and inefficient – it’s far better to place all of the tasks in a block and apply the conditional logic to the block itself. In this way, the logic only needs to be declared once. Blocks are also valuable when it comes to error handling and especially when it comes to recovering from an error condition. We shall explore both of these through simple practical examples in this chapter to get you up to speed with blocks in Ansible.
As ever, let’s ensure we have an inventory to work from:
[frontends] web01.example.org https_port=8443 web02.example.org http_proxy=proxy.example.org [frontends:vars] ntp_server=ntp.web.example.org proxy=proxy.web.example.org [apps...