Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible block vars

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.

like image 801
itiic Avatar asked Apr 11 '17 08:04

itiic


People also ask

What does block do in Ansible?

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.

Can you loop a block in Ansible?

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 Pre_tasks in Ansible?

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.

What is Changed_when in Ansible?

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.


1 Answers

  • 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.

like image 95
techraf Avatar answered Sep 22 '22 04:09

techraf