Tomas Hrubovcak
Tomas Hrubovcak

Reputation: 355

Can Ansible check if password is correct before running playbook?

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.

Upvotes: 5

Views: 5111

Answers (3)

Matthew Walker
Matthew Walker

Reputation: 2757

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.

Upvotes: 0

Andreas Moog
Andreas Moog

Reputation: 23

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.

Upvotes: 1

Tomas Hrubovcak
Tomas Hrubovcak

Reputation: 355

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

Upvotes: 6

Related Questions