我必须使用Ansible模块来编辑/ etc/ssh/sshd_config文件 - 每次创建新用户时我都想在这两行中追加它:
AllowUsers root osadmin <new_user>
AllowGroups root staff <new_group>
Run Code Online (Sandbox Code Playgroud)
此时我正在使用shell模块执行sed命令,但如果可能的话,我想使用lineinfile
- shell: "sed -i '/^Allow/ s/$/ {{ user_name }}/' /etc/ssh/sshd_config"
Run Code Online (Sandbox Code Playgroud)
任何建议都将得到真诚的感谢.
Chi*_*ang 15
在更换模块将替换文件中的正则表达式模式的所有实例.编写一个与该AllowUsers行匹配的任务,并将其替换为附加了用户名的原始行.为了确保任务是幂等的,正则表达式中的否定先行断言检查用户名是否已经出现在行中.例如:
- name: Add user to AllowUsers
replace:
backup: yes
dest: /etc/ssh/sshd_config
regexp: '^(AllowUsers(?!.*\b{{ user_name }}\b).*)$'
replace: '\1 {{ user_name }}'
Run Code Online (Sandbox Code Playgroud)
你可以用换行的单一游戏来做到这一点,但我认为使用两个lineinfile游戏更清晰.
- hosts: '127.0.0.1'
vars:
usernames:
- larry
- curly
- moe
usergroups:
- stooges
- admins
tasks:
- lineinfile:
dest: /etc/ssh/sshd_config
regexp: '^AllowUsers'
line: "AllowUsers {{usernames | join(' ')}}"
- lineinfile:
dest: /etc/ssh/sshd_config
regexp: '^AllowGroups'
line: "AllowGroups {{usergroups | join(' ')}}"
Run Code Online (Sandbox Code Playgroud)
请注意,这groups是一个保留字,所以不要将其用作变量名.
| 归档时间: |
|
| 查看次数: |
16995 次 |
| 最近记录: |