【问题标题】:Concatenate strings in Jinja?在 Jinja 中连接字符串?
【发布时间】:2018-07-01 00:39:55
【问题描述】:

我正在尝试在一个状态下连接字符串,但运气不佳。我看过建议使用 (|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 %}

【问题讨论】:

  • 结果如何?主/从日志中有任何错误吗?
  • 目标上的 /var/log/salt/minion 中没有任何错误,主服务器上的 /var/log/salt/master 中也没有任何错误。 {{ admin_groups }} 为空。
  • 不过,有趣的是,这个状态正上方的状态可以正常工作。 ` sudoers_asmgroups_content: file.append: - name: /etc/sudoers.d/mygroups - text: {% for app in grains['application_groups'] %} {% for group in pilla['admin_users'][app][' members'] %} - '%{{ group }}@mydomain.com ALL=(ALL) ALL' {% endfor %} {% endfor %} `
  • 我已经添加到你的问题中了,添加的sn-p的格式和你所在的州一样吗?

标签: salt-stack


【解决方案1】:

我通过修改解决方案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只有在有另一个值时才添加分隔符。

【讨论】:

  • 在这种情况下,你不能跳过整个循环,直接做{{ pillar['admin_users'][app]['members']|join('@mydomain.com ') }}@mydomain.com
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 2020-04-16
  • 2014-03-31
  • 1970-01-01
  • 2011-04-13
  • 2013-04-12
  • 2011-12-06
相关资源
最近更新 更多