Ansible and Jinja2 logic for loops

懵懂的女人 提交于 2019-12-04 05:27:26

问题


Variable file createuser:

    userslist:
      - da_cel_upload
      - da_tag_upload

Ansible logic:

    - 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

Contents of sshconfig.j2:

    Match User {{ item }}
    {% raw %}ChrootDirectory /home/{% endraw %}{{ item }}
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp

Output I get in /etc/ssh/sshd_config:

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

Output I need:

    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

Please help.


回答1:


You need to move the loop to inside of the Jinja2 template instead of Ansible's with_items (which causes the /etc/ssh/sshd_config file to be overwritten in each subsequent iteration).

So the task:

- 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

And the template (essentially the same as in the question, but wrapped in for-loop):

{% for item in userslist %}
Match User {{ item }}
{% raw %}ChrootDirectory /home/{% endraw %}{{ item }}
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
{% endfor %}

Add blank line to the end to get the exact output to need. SO does not display dangling blank lines.



来源:https://stackoverflow.com/questions/47132016/ansible-and-jinja2-logic-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!