I searched for solution that doesn't do anything if the user already is on the list. This is how it should work in Ansible. My solution at first searches for the user and only if the user is not on the list it will be added.
tasks:
- name: Check if bamboo user already is in SSHD AllowUsers list
command: grep -P '^[ \t]*AllowUsers[ \t]+([-\w ]+[ \t]+)*bamboo([ \t]+.+)*$' /etc/ssh/sshd_config
register: allow_users_exists
changed_when: no
ignore_errors: yes
- name: Allow bamboo user SSH login
lineinfile:
regexp: ^[ \t]*AllowUsers([ \t]+.*)$
line: AllowUsers bamboo\1
dest: /etc/ssh/sshd_config
backrefs: yes
validate: sshd -t -f %s
when: allow_users_exists.rc != 0
notify:
- reload sshd
handlers:
- name: reload sshd
service:
name: sshd
state: reloaded
In this special case I'm searching for static user "bamboo". You could use a variable instead like this:
command: grep -P '^[ \t]*AllowUsers[ \t]+([-\w ]+[ \t]+)*{{ username | regex_escape() }}([ \t]+.+)*$' /etc/ssh/sshd_config
and
line: AllowUsers {{ username }}\1
Results
In:
AllowUsers ubuntu #sdfd
Out:
AllowUsers bamboo ubuntu #sdfd
In:
AllowUsers ubuntu
Out:
AllowUsers bamboo ubuntu
In:
AllowUsers ubuntu bamboo
Out:
AllowUsers ubuntu bamboo