I'm trying to modify my AllowGroups entry in sshd_config but I'm running into a problem where I have AllowUsers on some servers.
Example line:
AllowGroups group1 group2 group3 !*
Desired output:
AllowGroups group1 group2 group3 newgroup !*
Current playbook:
- name: Add group to sshd_config
hosts: '{{ target }}'
handlers:
- name: reload sshd
service:
name: sshd
state: reloaded
tasks:
- name: Add Group to AllowGroups
replace:
dest: /etc/ssh/sshd_config
regexp: '\!\*$'
replace: 'newgroup !*'
validate: 'sshd -t -f %s'
notify: reload sshd
Is there a way I can tweak this where I only capture lines that begin with 'AllowGroups' ?
this task should do it for you:
- name: Add Group to AllowGroups
replace:
path: /tmp/sshd_config
regexp: '^(AllowGroups.*)(\!\*)$'
replace: '\1newgroup !*'
with parentheses, you split the string to "groups", where 1st group is whatever starts with AllowGroups following by everything, and 2nd group the "!*". In the replace
section you keep the first group (\\1)
and modify the 2nd as you described.
sample file used for testing:
line 1
AllowGroups group1 group2 group3 !*
bbbbbbbbbbbb !*
last line text !* last line
hope it helps.
If you don't want duplicates, you can first fetch the file content using the slurp module , check if the group is there, then add it if it isn't. For instance:
- hosts: all
vars:
group_to_add: "newgroup"
tasks:
- name: "get the file content"
slurp:
src: "sshd_config"
register: file
- name: "fetch the right line"
set_fact:
line: "{{ file['content'] | b64decode | regex_search('AllowGroups.*')}}"
- name: "extract the groups"
set_fact:
allowed_groups: "{{ line.split()[1:-1] }}"
- name: "add the group"
replace:
path: "sshd_config"
regexp: "(AllowGroups.*)(\!\*)"
replace: "\1{{group_to_add}} !*"
when: group_to_add not in allowed_groups
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.