lineinfile - how to hit them all?

My /etc/ssh/sshd_config after initial installation contains these two lines for some reasons:

#PasswordAuthentication yes

PasswordAuthentication yes

I’m trying to change BOTH to “no” with this statement:

  • name: SSH - Disable SSH password authentication and restart OpenSSH at the end
    lineinfile:
    path: /etc/ssh/sshd_config
    state: present
    line: “{{ item.line }}”
    regexp: “{{ item.regexp }}”
    with_items:
  • { regexp: ‘^#?PermitRootLogin’, line: ‘PermitRootLogin prohibit-password’ }
  • { regexp: ‘^#?PasswordAuthentication yes’, line: ‘PasswordAuthentication no’ }
    notify:
  • Reload OpenSSH

What baffles me a bit is that it needs two runs to change both occurances:

In the first run the last line is changed. The second run changes the first line.

TASK [SSH - Disable SSH password authentication and restart OpenSSH at the end] *************************************************************
changed: [ubuntuVM] => (item={‘regexp’: ‘^#?PermitRootLogin’, ‘line’: ‘PermitRootLogin prohibit-password’})
changed: [ubuntuVM] => (item={‘regexp’: ‘^#?PasswordAuthentication yes’, ‘line’: ‘PasswordAuthentication no’})

TASK [SSH - Disable SSH password authentication and restart OpenSSH at the end] **********************************************************************
ok: [ubuntuVM] => (item={‘regexp’: ‘^#?PermitRootLogin’, ‘line’: ‘PermitRootLogin prohibit-password’})
changed: [ubuntuVM] => (item={‘regexp’: ‘^#?PasswordAuthentication yes’, ‘line’: ‘PasswordAuthentication no’})

What would I have to do in order to kill two birds with one stone?

Use the module *replace*, e.g.

    - replace:
        path: /etc/ssh/sshd_config
        regexp: '^(#*)PasswordAuthentication yes'
        replace: '\1PasswordAuthentication no'

Yes, thanks Vladimir. Found that out by myself already. Works.