Conditionally concat jinja2 lists

Viewed 442

Some data used in an ansible role:

list1:
  - foo
  - bar
list2:             # sometimes this is empty

This ansible task fails:

- name: hello
  somemodule:
    dosomething: "{{ list1 + list2 }}"

Error:

fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{list1 + list2}}): can only concatenate list (not \"NoneType\") to list"}

Is there a way to conditionally concatenate only if list2 is not empty?

1 Answers

You can use the none bulitin test combined with an inline if expression for this:

- debug:
    msg: "{{ list1 + (list2 if list2 is not none else []) }}" 

Given the playbook

- hosts: local
  gather_facts: no
  vars:
    list1:
      - foo
      - bar
    list2:

  tasks:
    - debug:
        msg: "{{ list1 + (list2 if list2 is not none else [])  }}"

A play will result in this recap:

PLAY [local] **************************************************************************************

TASK [debug] **************************************************************************************
ok: [local] => {
    "msg": [
        "foo",
        "bar"
    ]
}

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