Can Ansible check if password is correct before running playbook?
Asked Answered
A

3

5

is there any mechanism that checks if the SSH/SUDO password is correct? When deploying a playbook across the whole environment, after putting in the wrong password, ansible runs on all hosts with the wrong password, it fails and my LDAP/AD account is locked out.

Artemisa answered 28/5, 2018 at 9:4 Comment(2)
No, there is no mechanism. You need to implement one yourself. Better yet, don't use passwords.Litigable
@Litigable I think that'll be my next feature request. SSH keys are one thing, passwordless sudo is another.Artemisa
A
6

Since, as it turns out, Ansible does not seem to have this functionality, I decided to create a workaround myself: in site.yml, I added a role that only runs on one server and has 1 or optionally 2 tasks in it. The first one checks if login itself works, the second one checks if sudo works.

- name: Check ssh password first
  command: echo "ssh password correct"
  changed_when: false

- name: Check sudo password first
  command: echo "sudo password correct"
  become: yes
  changed_when: false
Artemisa answered 28/5, 2018 at 10:55 Comment(0)
D
1

As a good workaround, I usually put this in site.yml:

- hosts: all
  gather_facts: false
  tasks:
   - name: site.yml | Check if Password is correct
  become: true
  command: echo "PW is correct"
  run_once: true
  tags:
    - always

That task will run always, no matter what tags you start the playbook with and will check if the ssh/sudo password works on one host before hammering all your servers with login requests.

Dafna answered 18/7, 2018 at 20:28 Comment(0)
F
0

Sudo password caching can interfere with the validation of the sudo password. Building on Tomas' self-answer, the following tasks first clear the cached password and then check that the sudo password is correct. If the wrong password is given, Ansible may hang waiting for the user to enter a password. This is dealt with by setting a one-second timeout.

- name: Check ssh password
  command: echo "ssh password correct"
  changed_when: false

- name: Clear cached sudo password
  command: sudo -k
  changed_when: false

- name: Check sudo password
  command: echo "sudo password is correct"
  become: true
  timeout: 1
  changed_when: false
  register: result
  ignore_errors: true

- name: Fail if sudo password is invalid
  fail:
    msg: "Invalid sudo password"
  when: result is failed or result.rc is not defined or result.rc != 0

Checked on Ubuntu 22.04.

Faradism answered 16/7, 2024 at 21:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.