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.
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