I have to use Ansible modules in order to edit the /etc/ssh/sshd_config file - every time I create a new user I want to append it at these two lines:
AllowUsers root osadmin <new_user>
AllowGroups root staff <new_group>
At this moment I'm using the shell module to execute a sed command but would like to use lineinfile, if possible
- shell: "sed -i '/^Allow/ s/$/ {{ user_name }}/' /etc/ssh/sshd_config"
Any suggestions would be sincerely appreciated.
The replace module will replace all instances of a regular expression pattern within a file. Write a task to match the
AllowUsers
line and replace it with the original line appended with the user name. To ensure the task is idempotent, a negative lookahead assertion in the regular expression checks if the user name already appears in the line. For example:I had the same problem. I needed add user to sudoers group, let's say 'testuser' to line:
This worked well for me:
The point is that if I had '^User_Alias(..)$'* in regexp and not '^(User_Alias(..)$)'* it didn't work and whole line was replaced. With () arround searched text the result was OK:
So then anything can work in line:, included ansible variables like
"{{ usernames | join(', ') }}"
This worked for me
You could do it in a single play with a newline, but I think it's cleaner to use two
lineinfile
plays for this.Note that
groups
is a reserved word so don't use that as a variable name.