Ansible uncomment line in file

If you need zero or more white spaces after the '#' character, the following should suffice:

- name: Uncomment line from /etc/ssh/sshd_config
    lineinfile:
      dest: /etc/ssh/sshd_config
      regexp: '^#\s*AuthorizedKeysFile.*$'
      line: 'AuthorizedKeysFile    .ssh/authorized_keys'

The modification to your original code is the addition of the \s* and the .*$ in the regex.

Explanation:

\s - matches whitespace (spaces, tabs, line breaks and form feeds)

* - specifies that the expression to it's left (\s) can have zero or more instances in a match

.* - matches zero or more of any character

$ - matches the end of the line


Firstly, you are using the wrong language. With Ansible, you don't tell it what to do, but define the desired state. So it shouldn't be Uncomment line form /etc/ssh/sshd_config, but Ensure AuthorizedKeysFile is set to .ssh/authorized_keys.

Secondly, it doesn't matter what the initial state is (if the line is commented, or not). You must specify a single, unique string that identifies the line.

With sshd_config this is possible as the AuthorizedKeysFile directive occurs only once in the file. With other configuration files this might be more difficult.

- name: Ensure AuthorizedKeysFile is set to .ssh/authorized_keys
  lineinfile:
    dest: /etc/ssh/sshd_config
    regexp: AuthorizedKeysFile
    line: 'AuthorizedKeysFile    .ssh/authorized_keys'

It will match any line containing AuthorizedKeysFile string (no matter if it's commented or not, or how many spaces are there) and ensure the full line is:

AuthorizedKeysFile .ssh/authorized_keys

If the line were different, Ansible will report "changed" state.

On the second run, Ansible will find the AuthorizedKeysFile again and discover the line is already in the desired state, so it will end the task with "ok" state.


One caveat with the above task is that if any of the lines contains a comment such as a real, intentional comment (for example an explanation in English containing the string AuthorizedKeysFile), Ansible will replace that line with the value specified in line.

Tags:

Linux

Ansible