循环的 Ansible 和 Jinja2 逻辑
Ansible and Jinja2 logic for loops
可变文件createuser
:
userslist:
- da_cel_upload
- da_tag_upload
Ansible 逻辑:
- 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_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 的 with_items
(这会导致 /etc/ssh/sshd_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 中):
{% for item in userslist %}
Match User {{ item }}
{% raw %}ChrootDirectory /home/{% endraw %}{{ item }}
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
{% endfor %}
在末尾添加空行以获得所需的确切输出。 SO 不显示悬空空行。
可变文件createuser
:
userslist:
- da_cel_upload
- da_tag_upload
Ansible 逻辑:
- 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_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 的 with_items
(这会导致 /etc/ssh/sshd_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 中):
{% for item in userslist %}
Match User {{ item }}
{% raw %}ChrootDirectory /home/{% endraw %}{{ item }}
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
{% endfor %}
在末尾添加空行以获得所需的确切输出。 SO 不显示悬空空行。