Search code examples
jinja2ansible

Append list variable to another list in Ansible


is it possible to append a variable list to a static list in ansible?

I can define the whole list as a variable:

my_list:
  - 1
  - 2
  - 3

and then use it in a playbook as

something: {{my_list}}

But I cannot seem to find how to do this (pseudo code):

list_to_append: 
  - 3
  - 4

and then in the playbook:

something:
  - 1
  - 2
  - {{append: list_to_append}}

If that is in fact impossible, what would you suggest for my use case?

I have a list of items in a parameter, but some of them are optional and should be modifiable using variables.

In other words: I have default values + optional values that could or could not be added via variables.

The optional values are not known in advance, I could add 1, 2 or 100 of them, so they are not static.

I basically have a default static list ++ a configurable variable list to append.

edit: I found this but it's only for with_items and I need it in a normal parameter:

  with_flattened:
   - "{{list1}}"
   - "{{list2}}"

Solution

  • If you really want to append to content, you will need to use the set_fact module. But if you just want to use the merged lists it is as easy as this:

    {{ list1 + list2 }}
    

    With set_fact it would look like this:

    - set_fact:
        list_merged: "{{ list1 + list2 }}"
    

    NOTE: If you need to do additional operations on the concatenated lists be sure to group them like so:

    - set_fact:
        list_merged: "{{ (list1 + list2) | ... }}"