0

I have a playbook where I execute several tasks. Each task can be executed if it meets the WHEN condition. I would like to save some data into a list so I can use it later in the process.

Here is an over simplified example to illustrate my need:

- Set GlobalVar = []

- task A
  when task_A_enabled
  register custom_value_A into GlobalVar

- task B
  when task_B_enabled
  register custom_value_B into GlobalVar

- task C
  do something with GlobalVar

I hope it's clear enough to help me figure out how to do that. Thank you.

Kornikopic
  • 188
  • 1
  • 15

2 Answers2

2

An option would be to use block

For example the play below

- hosts: localhost
  gather_facts: no
  vars:
    GlobalVar: []
    task_a: true
    task_b: false
  tasks:
    - name: task A
      block:
        - debug:
            msg: Task A is enabled
        - set_fact:
            GlobalVar: "{{ GlobalVar + [ 'A' ] }}"
      when: task_a
    - name: task B
      block:
        - debug:
            msg: Task B is enabled
        - set_fact:
            GlobalVar: "{{ GlobalVar + [ 'B' ] }}"
      when: task_b
    - name: task C
      debug:
        var: GlobalVar

gives (abridged):

ok: [localhost] => {
    "msg": "Task A is enabled"
}
...
ok: [localhost] => {
    "GlobalVar": [
        "A"
    ]
}
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
2

You can use the module set_fact to do the variable assignment and use blocks to group a task and the variable assignment step so you can check conditions once:

---
  - hosts: "all"
    vars:
        GlobalVar: []
    tasks:
      - block:
         - set_fact:
              GlobalVar: "{{ GlobalVar + [1, 2] }}"
         - debug:
              msg: "{{GlobalVar}}"
        when: true
      - block:
         - set_fact:
              GlobalVar: "{{ GlobalVar + [3, 4] }}"
         - debug:
              msg: "{{GlobalVar}}"
        when: false
      - block:
         - set_fact:
              GlobalVar: "{{ GlobalVar + [5, 6] }}"
         - debug:
              msg: "{{GlobalVar}}"
        when: true
Alassane Ndiaye
  • 4,427
  • 1
  • 10
  • 19