block can be used to group a block of tasks together. As a sort of arbitrary example, let's say you have a playbook that contains three tasks. In this example, the first two tasks contain the when parameter so that the tasks is only run on managed hosts in the "web" group.
---
- hosts: all
tasks:
- name: create the /usr/local/foo directory
ansible.builtin.file:
path: /usr/local/foo
state: directory
when: inventory_hostname in ( groups['web'] )
- name: upload foo.txt to /usr/local/foo/foo.txt
ansible.builtin.copy:
src: /usr/local/ansible/files/foo.txt
dest: /usr/local/foo/foo.txt
when: inventory_hostname in ( groups['web'] )
- name: update foo.txt owner group mode
ansible.builtin.file:
path: /usr/local/foo/foo.txt
owner: john.doe
group: admins
mode: "0770"
...
The block parameter can be used to group the first two tasks together, so that the when parameter only needs to be declared once, which results in a much less repetitive and less error prone playbook.
---
- hosts: all
tasks:
- block:
- name: create the /usr/local/foo directory
ansible.builtin.file:
path: /usr/local/foo
state: directory
- name: upload foo.txt to /usr/local/foo/foo.txt
ansible.builtin.copy:
src: /usr/local/ansible/files/foo.txt
dest: /usr/local/foo/foo.txt
when: inventory_hostname in ( groups['web'] )
- name: update foo.txt owner group mode
ansible.builtin.file:
path: /usr/local/foo/foo.txt
owner: john.doe
group: admins
mode: "0770"
...
Let's say you have a group of tasks that require become. Without block, you may have two (or more) tasks with the same become settings. In this example, we do not want to use become for the entire playbook since there are tasks to do not require become.
---
- hosts: all
remote_user: superuser
tasks:
- name: create the /usr/local/foo directory
become: yes
become_method: sudo
ansible.builtin.file:
path: /usr/local/foo
state: directory
owner: john.doe
groups: admins
- name: upload bar.txt to /usr/local/foo/bar.txt
become: yes
become_method: sudo
ansible.builtin.copy:
src: bar.txt
dest: /usr/local/foo/bar.txt
owner: john.doe
groups: admins
mode: '0777'
- name: append 'Hello World' to bar.txt
ansible.builtin.lineinfile:
path: /usr/local/foo/bar.txt
line: "Hello World"
...
block can be used to use become in a block of tasks which results in a much cleaner, less repetitive and less error prone playbook.
---
- hosts: all
remote_user: superuser
tasks:
- block:
- name: create the /usr/local/foo directory
ansible.builtin.file:
path: /usr/local/foo
state: directory
owner: john.doe
groups: admins
- name: upload bar.txt to /usr/local/foo/bar.txt
ansible.builtin.copy:
src: bar.txt
dest: /usr/local/foo/bar.txt
owner: john.doe
groups: admins
mode: '0777'
become: yes
become_method: sudo
- name: append 'Hello World' to bar.txt
ansible.builtin.lineinfile:
path: /usr/local/foo/bar.txt
line: "Hello World"
...
Did you find this article helpful?
If so, consider buying me a coffee over at