lineinfile - how to hit them all?

44 views
Skip to first unread message

Neil Young

unread,
Oct 11, 2021, 3:07:59 PM10/11/21
to Ansible Project
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?



Vladimir Botka

unread,
Oct 11, 2021, 6:41:20 PM10/11/21
to 'Neil Young' via Ansible Project
On Mon, 11 Oct 2021 12:07:59 -0700 (PDT)
"'Neil Young' via Ansible Project" <ansible...@googlegroups.com>
wrote:

> #PasswordAuthentication yes
> PasswordAuthentication yes
>
> I'm trying to change BOTH to "no"

Use the module *replace*, e.g.

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

--
Vladimir Botka

Neil Young

unread,
Oct 12, 2021, 10:28:53 AM10/12/21
to Ansible Project
Yes, thanks Vladimir. Found that out by myself already. Works.
Reply all
Reply to author
Forward
0 new messages