Ansible jinja2将列表合并到单个列表 [英] Ansible jinja2 merging lists to a single list
问题描述
我正在尝试迭代列表["abc","def","ghi"]&每次迭代都会生成一个列表,我需要将其设置为ansible变量.
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.
这是我当前的脚本:
- name: add checks
set_fact:
CHECKS: "{% for cKey in checkKey %} {{ CHECKS|default([]) }} + {{ CHECKSMAP | map(attribute=cKey ) | list |join(',')}} {% endfor %}"
生成以下输出,该输出是字符串&不是列表,如何在for循环中附加到类似于list + = temp_list的单个列表
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'}] " }
推荐答案
生成以下输出,该输出是字符串&不是列表
which generates the following output which is a string & not a list
这是一个字符串,有两个原因:首先,您在表达式中间嵌入了" + "
位文本,其次是因为您叫join(',')
,而Jinja却按照您的要求高兴地完成了操作.
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.
如何在for循环中附加到类似于list + = temp_list的单个列表
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 ,您必须使用.extend
技巧,因为set tmp = tmp +
将在循环内声明一个新的tmp
,而不是在循环外分配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
这篇关于Ansible jinja2将列表合并到单个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!