循环的Ansible和Jinja2逻辑

循环的Ansible和Jinja2逻辑,ansible,jinja2,ansible-template,Ansible,Jinja2,Ansible Template,变量文件createuser: userslist: - da_cel_upload - da_tag_upload 可解析逻辑: - include_vars: group_vars/createuser - name: Create custom file /etc/ssh/shhd_config for user configuration and restart sshd service template: src=ssh

变量文件
createuser

    userslist:
      - da_cel_upload
      - da_tag_upload
可解析逻辑:

    - include_vars: group_vars/createuser


    - name: Create custom file /etc/ssh/shhd_config for user configuration and restart sshd service
      template: src=sshconfig.j2 dest=/etc/ssh/sshd_config
      with_items: '{{userslist}}'
      notify: restart ssh
sshconfig.j2的内容

    Match User {{ item }}
    {% raw %}ChrootDirectory /home/{% endraw %}{{ item }}
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp
我在
/etc/ssh/sshd\u config
中获得的输出:

    Match User da_tag_upload
    ChrootDirectory /home/da_tag_upload
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp
我需要的输出:

    Match User da_cel_upload
    ChrootDirectory /home/da_tag_upload
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp

    Match User da_tag_upload
    ChrootDirectory /home/da_tag_upload
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp

请提供帮助。

您需要将循环移动到Jinja2模板的内部,而不是Ansible的
和_items
(这会导致
/etc/ssh/sshd\u config
文件在每个后续迭代中被覆盖)

因此,任务是:

- name: Create custom file /etc/ssh/shhd_config for user configuration and restart sshd service
  template:
    src: sshconfig.j2
    dest: /etc/ssh/sshd_config
  notify: restart ssh
和模板(基本上与问题中相同,但包装在
for
-loop中):


在末尾添加空行以获得所需的确切输出。因此不会显示悬空的空行。

欢迎使用StackOverflow!请看一下,特别是
{% for item in userslist %}
Match User {{ item }}
{% raw %}ChrootDirectory /home/{% endraw %}{{ item }}
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
{% endfor %}