Ansible - Getting Started with the block parameter
by
Jeremy Canfield |
Updated: March 02 2023
| Ansible articles
The block parameter can be used to group 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
file:
path: /usr/local/foo
state: directory
when: inventory_hostname in ( groups['web'] )
- name: upload foo.txt to /usr/local/foo/foo.txt
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
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 playbook.
---
- hosts: all
tasks:
- block:
- name: create the /usr/local/foo directory
file:
path: /usr/local/foo
state: directory
- name: upload foo.txt to /usr/local/foo/foo.txt
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
file:
path: /usr/local/foo/foo.txt
owner: john.doe
group: admins
mode: "0770"
...
Did you find this article helpful?
If so, consider buying me a coffee over at