How can I set in Ansible block vars (visible only for tasks in block) ?
I tried:
---
- hosts: test
tasks:
- block:
- name: task 1
shell: "echo {{item}}"
with_items:
- one
- two
but it seems that it's a wrong way.
Blocks allow for logical grouping of tasks and in play error handling. Most of what you can apply to a single task (with the exception of loops) can be applied at the block level, which also makes it much easier to set data or directives common to the tasks.
Loops are sets of commands or instructions that are set to repeat a certain number of times as per user requirements. Loops allow for better control flow in your scripts and remove overall redundancy from them. Ansible also comes with multiple methods of looping blocks of code.
What is Ansible pre_tasks? Ansible pretask is a conditional execution block that runs before running the play. It can be a task with some prerequisites check (or) validation.
Ansible lets you define when a particular task has “changed” a remote node using the changed_when conditional. This lets you determine, based on return codes or output, whether a change should be reported in Ansible statistics and whether a handler should be triggered or not.
If you want to define a variable for a block:
- block:
- debug:
var: var_for_block
vars:
var_for_block: "value for var_for_block"
If you want to "loop over blocks" as your code suggests - you can't. It's not implemented in Ansible. Follow this thread.
For now consider saving the tasks to a separate file and use include
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With