Ansible: insert a single word on an existing line in a file

You could do it in a single play with a newline, but I think it's cleaner to use two lineinfile plays for this.

- hosts: '127.0.0.1'
  vars:
    usernames:
       - larry
       - curly
       - moe
    usergroups:
       - stooges
       - admins
  tasks:
    - lineinfile:
        dest: /etc/ssh/sshd_config
        regexp: '^AllowUsers'
        line: "AllowUsers {{usernames | join(' ')}}"
    - lineinfile:
        dest: /etc/ssh/sshd_config
        regexp: '^AllowGroups'
        line: "AllowGroups {{usergroups | join(' ')}}"

Note that groups is a reserved word so don't use that as a variable name.


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:

- name: Add user to AllowUsers
  replace:
    backup: yes
    dest: /etc/ssh/sshd_config
    regexp: '^(AllowUsers(?!.*\b{{ user_name }}\b).*)$'
    replace: '\1 {{ user_name }}'

Tags:

Ansible

Sshd