Append list variable to another list in Ansible

你。 提交于 2020-06-24 05:44:09

问题


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}}"

回答1:


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) | ... }}"



回答2:


The following worked for me with Ansible 2.1.2.0:

- name: Define list of mappings
  set_facts:
    something:
      - name: bla
        mode: 1

- name: Append list with additional mapping
  set_facts:
    something: "{{ something + [{'name': 'blabla', 'mode': 1}] }}"


来源:https://stackoverflow.com/questions/31045106/append-list-variable-to-another-list-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!