1

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' ?

user3299633
  • 2,971
  • 3
  • 24
  • 38

2 Answers2

1

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.

ilias-sp
  • 6,135
  • 4
  • 28
  • 41
  • Is there a way to prevent 'newgroup' from being duplicated if it already exists? – user3299633 Sep 14 '19 at 01:38
  • thats tough, i tried but not convinced how to do it. you can read this thread if you want to try yourself: [https://stackoverflow.com/questions/406230/regular-expression-to-match-a-line-that-doesnt-contain-a-word](https://stackoverflow.com/questions/406230/regular-expression-to-match-a-line-that-doesnt-contain-a-word) – ilias-sp Sep 14 '19 at 12:41
  • You answered my original question so I'll give you credit. Not fair to add requirements after the fact. – user3299633 Sep 17 '19 at 21:41
1

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
Alassane Ndiaye
  • 4,427
  • 1
  • 10
  • 19