2

I would like to set a default array if a variable is empty. Setting an empty array in the defaults filter works described here. Setting an array which is stored in a variable does not.

In the example run_targets is undefined, targets should be used instead.

- name: Set vars
  vars:
    targets: [target1, target2, target3]

- name: Include run sql task
      include: tasks/sql.yml
      with_items: "{{ run_targets | defult(targets) }}"

Is there any way to do this?

0xSheepdog
  • 545
  • 2
  • 19
L3p0
  • 21
  • 1
  • 3

1 Answers1

4

Your playbook is not valid. vars is not a module that you can run in a task. You either use set_fact or declare vars at play level. The following complete example demonstrates that it works without problems:

---
- name: Demo of default from var
  hosts: localhost
  gather_facts: false

  vars:
    default_targets:
      - target1
      - target2
      - target3

  tasks:
    - name: Show run targets else defaults
      debug:
        msg: "{{ run_targets | default(default_targets) }}"

Which gives:

$ ansible-playbook playbook.yml 

PLAY [Demo of default from var] ************************************************

TASK [Show run targets else defaults] ******************************************
ok: [localhost] => {
    "msg": [
        "target1",
        "target2",
        "target3"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

$ ansible-playbook playbook.yml -e "{run_targets: [a,b,c]}"

PLAY [Demo of default from var] ************************************************

TASK [Show run targets else defaults] ******************************************
ok: [localhost] => {
    "msg": [
        "a",
        "b",
        "c"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Zeitounator
  • 1,199
  • 5
  • 12