@techraf 指出,在 99% 的情况下,配置文件的完整模板几乎总是更好。
我做过lineinfile 的时间包括由其他进程管理的奇怪而美妙的配置文件,或者我还不完全理解的配置文件的懒惰,并且可能因发行版/版本而异,我不想维护所有的变种......但是。
继续学习更多 Ansible... 这很棒,因为您可以从原始 bash shell 命令一直迭代到最佳实践。
lineinfile 模块
仍然很高兴看到如何最好地配置管理一个或两个设置,只是稍微好一点:
tasks:
- name: Apply sshd_config settings
lineinfile:
path: /etc/ssh/sshd_config
# might be commented out, whitespace between key and value
regexp: '^#?\s*{{ item.key }}\s'
line: "{{ item.key }} {{ item.value }}"
validate: '/usr/sbin/sshd -T -f %s'
with_items:
- key: MaxSessions
value: 30
- key: AuthorizedKeysFile
value: .ssh/authorized_keys
notify: restart sshd
handlers:
- name: restart sshd
service:
name: sshd
state: restarted
-
validate如果更改无效,请不要进行更改
-
notify/handlers正确的方法是只在最后重启一次
-
with_items(很快变成loop)如果你有多个设置
-
^#? 设置可能被注释掉 - 查看其他答案
-
\s*{{ item.key }}\s 不会匹配其他设置(即SettingA 无法匹配NotSettingA 或SettingAThisIsNot)
仍然可能会破坏像 # AuthorizedKeysFile - is a setting 这样的评论,因为可能存在像 AuthorizedKeysFile /some/path # is a setting 这样的设置...重新阅读警告。
模板模块
- name: Configure sshd
template:
src: sshd_config.j2
dest: /etc/ssh/sshd_config
owner: root
group: root
mode: "0644"
validate: '/usr/sbin/sshd -T -f %s'
notify: restart sshd
handlers:
- name: restart sshd
service:
name: sshd
state: restarted
多发行版支持
如果您不是懒于支持所有发行版,请参阅此提示
- name: configure ssh
template: src={{ item }} dest={{ SSH_CONFIG }} backup=yes
with_first_found:
- "{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.sshd_config.j2"
- "{{ ansible_distribution }}.sshd_config.j2"
https://ansible-tips-and-tricks.readthedocs.io/en/latest/modifying-files/modifying-files/
(需要使用first_found 查找更新为loop)