DRY: Don't repeat yourself. Use Ansible blocks
A very common principle in software development is to not repeat yourself. This principle is not limited to software development only. We should apply this to our whole life. Life means to be creative and we can only be creative if we do not repeat the same patterns over and over again. In Ansible it is incredibly easy to avoid repetition by using use the block clause.
Ansibles most basic building block is a module. In order to use a module for a given purpose we have to create a task in an Ansible playbook.
A task is the runtime configuration for a module.
- name: task1
foo_module:
foo: true
bar: "baz"
var1: "content1"
In a CLI we may run that task with the following command:
$ foo_module --foo --bar "baz" --var1 "content1"
Let us now assume we have hundreds of these tasks in our playbook and all of them are slightly different.
1 - name: task1
2 foo_module:
3 foo: true
4 bar: "baz"
5 var1: "content1"
6 tag:
7 - foo_tag
8
9 - name: task2
10 foo_module:
11 foo: true
12 bar: "baz"
13 var2: "content2"
14 tag:
15 - foo_tag
16
...
792
793 - name: task100
794 foo_module:
795 foo: true
796 bar; "baz"
798 var100: "content100"
799 tag:
800 - foo_tag
There are hundreds of lines of repetition in here. One way to avoid that repetition is to group tasks together in a block.
1 - name: foo_block
2 block:
3 - name: task1
4 foo_module:
5 var1: "content1"
6
7 - name: task2
8 foo_module:
9 var2: "content2"
10
...
398
399 - name: task100
400 foomodule:
401 var100: "content100"
402
403 module_defaults:
404 foo_module:
405 foo: true
406 bar: "baz"
407 tag:
408 - foot_tag
We have reduced our lines of code from 800 to 400 just by grouping tasks together in a block and by setting defaults.
This is just an example of what Ansible blocks are and how they make our lives easier. However in that particular use case we could have used a loop instead and put our data in a clean data structure. But that is a topic for another blog post.