Add a username in the sshd config file,

Hello everyone,

i have a question. I’m trying to create a new user for all of my virtual servers. The creating works fine, only issue i have is the sshd config file. In this file we have one Line “AllowedUsers: User1 User2 User3 …”

I tried to create a playbook to add User4 in that file. This is how my playbook looks like:

 - name: Find
     dest: /etc/ssh/sshd_testcfg
     line: "user4"
   register: presence

 - name: Add string after pattern
     path: /etc/ssh/sshd_testcfg
     regexp: '^(AllowUsers.+)(\n?)$'
     line: '\1user4'
   when: presence is failed

The result i need is:
User1 User2 User3 User 4
While Ansible does this:
User1 User2 User3
User 4

Can someone help me please?

You need to provide the whole of the desired line to lineinfile not just the value to append.

Personally I’d probably use the JC sshd parser with the JC filter to read the existing configuration.

Also since AllowUsers “may appear multiple times in sshd_config with each instance appending to the list”, I’d suggest that if your SSHD is recent enough to support Include and has a directive like this in it already:

Include /etc/ssh/sshd_config.d/*.conf

Then you might be best off simply writing one file per user to this directory, for example a /etc/ssh/sshd_config.d/user4.conf file containing:

AllowUser user4

Of course there are lots of different ways to achieve what you want and the above are just my initial thoughts on it, there might well be a better way…