问题描述
我正在尝试迭代一个列表 ["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'}] " }
推荐答案
这是一个字符串有两个原因:首先,你在表达式中间嵌入了一个 " + "
位文本,第二个是因为你调用了 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 的单个列表
答案是完全按照你说的去做,并使用一个中间变量:
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 将列表合并为一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!