在 Jinja 中连接字符串?

Concatenate strings in Jinja?

我正在尝试连接一个状态中的字符串,但运气不佳。我看过建议使用 (|join) 的帖子,但我的所有字符串都不在一个字典中。这是我的代码:

sshd_content:
  file.line:
{% set admin_groups = '' %}
{% for app in grains['application_groups'] %}
{% for group in pillar['admin_users'][app]['members'] %}
{% set admin_groups = admin_groups ~ ' ' ~ group ~ '@mydomain.com' %}
{% endfor %}
{% endfor %}
    - name: /etc/ssh/sshd_config
    - match: AllowGroups wheel fred
    - mode: replace
    - content: AllowGroups wheel fred bob {{ admin_groups }}

我也尝试过使用 + 而不是 ~ ,但没有成功。

我做错了什么?

这个状态工作正常:

sudoers_asmgroups_content:
  file.append:
    - name: /etc/sudoers.d/mygroups
    - text:
{% for app in grains['application_groups'] %}
  {% for group in pillar['admin_users'][app]['members'] %}
      - '%{{ group }}@mydomain.com ALL=(ALL) ALL'
  {% endfor %}
{% endfor %}

我通过修改解决方案here找到了一个可行的方案here

这似乎是 admin_groups 变量的作用域问题。不确定为什么 append 有效,但我不会争论。

对于上面 OP 中的示例,代码如下:

sshd_content:
  file.line:
{% set admin_groups = [] %}
{% for app in grains['application_groups'] %}
{% for group in pillar['admin_users'][app]['members'] %}
{% do admin_groups.append(group) %}
{% endfor %}
{% endfor %}
    - name: /etc/ssh/sshd_config
    - match: AllowGroups wheel myadmin
    - mode: replace
    - content: AllowGroups wheel fred bob {{ admin_groups|join('@mydomain.com ') }}@mydomain.com 
{% endif %}

需要添加第二个@domain.com因为是AD组名,join只有在有其他值时才添加分隔符