How to append the new group to the existing AllowGroups line in /etc/ssh/sshd_config

Hi Experts,

I would like to append the new group to the existing AllowGroups in /etc/ssh/sshd_config file without disturbing the existing group. I tried with lineinfile module but unfortunately its failing or overwriting existing groups. Can anyone please provide the clue on logic?

existing setup:

grep AllowGroups /etc/ssh/sshd_config

AllowGroups x y z

required setup: let’s assume “a” is new group, then i am looking as below

grep AllowGroups /etc/ssh/sshd_config

AllowGroups x y z a <-----group “a” needs to be added at the end of the line

Once again thanks for your help

Regards,
Suresh

Enable *backrefs* and create non-greedy capture group in front of the
potentially existent "a" group

    - lineinfile:
        path: /etc/ssh/sshd_config
        backrefs: true
        regexp: '^\s*AllowGroups\s+(.*?)(\s+a)*$'
        line: 'AllowGroups \1 a'

The task is idempotent. Quoting from *regexp*
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html#parameter-regexp

  "When modifying a line the regexp should typically match both the
  initial state of the line as well as its state after replacement by
  line to ensure idempotence."

Thank you so much Vladimir,

How can we loop if we need to append multiple groups.

Regards,
Suresh

Try this:
https://dpaste.com/5ENHWDV7Q

Remember to update the sshd_config to the proper path ie. /etc/ssh/sshd_config

➜ ~ grep ‘^AllowGroups’ sshd_config
AllowGroups a b c
➜ ~ ansible-playbook -i localhost, allow.yml

PLAY [Configure sshd groups] ******************************************************************************************************************************************************************

Playbook run took 0 days, 0 hours, 0 minutes, 1 seconds
➜ ~ grep ‘^AllowGroups’ sshd_config
AllowGroups a b c x y z

HTH

Put them into a variable, e.g.

    - lineinfile:
        path: /etc/ssh/sshd_config
        backrefs: true
        regexp: '^\s*AllowGroups\s+(.*?)(\s+{{ add_groups }})*$'
        line: 'AllowGroups \1 {{ add_groups }}'

thank you so much Vladimir and Jorge

Regards,
Suresh