Ansible jinja2 merging lists to a single list

偶尔善良 提交于 2021-01-07 03:36:32

问题


I am trying to iterate a list ["abc","def","ghi"] & each iteration generates a list which i need to set it to a variable in ansible.

here is my current script:

- name: add checks
  set_fact:
    CHECKS: "{% for cKey in checkKey %} {{ CHECKS|default([]) }} + {{ CHECKSMAP | map(attribute=cKey ) | list |join(',')}} {% endfor %}"

which generates the following output which is a string & not a list how can i append to the single list similar to list += temp_list in a for loop

ok: [127.0.0.1] => {
"msg": "System  [] + [{u'check': u'system_checks'}, {u'check': u'lms_server_health'}]  [] + [{u'check': u'system_checks'}, {u'check': u'config-service_server_health'}, {u'check': u'config-service_server_restart'}] "   }

回答1:


which generates the following output which is a string & not a list

It's a string for two reasons: first off, you embedded a " + " bit of text in the middle of your expression, and the second is because you called join(',') and jinja cheerfully did as you asked.

how can i append to the single list similar to list += temp_list in a for loop

The answer is to do exactly as you said and use an intermediate variable:

CHECKS: >-
  {%- set tmp = CHECKS | default([]) -%}
  {%- for cKey in checkKey -%}
  {%-   set _ = tmp.extend(CHECKSMAP | map(attribute=cKey ) | list) -%}
  {%- endfor -%}
  {{ tmp }}

AFAIK, you have to use that .extend trick because a set tmp = tmp + will declare a new tmp inside the loop, rather than assigning the tmp outside the loop



来源:https://stackoverflow.com/questions/53114675/ansible-jinja2-merging-lists-to-a-single-list

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