July 26, 2020

How to Update User Password with Ansible

It's very easy to change a user's password with Ansible. Here I included 2 ways for your perusal: one with Ansible Playbook, and another one directly via command line.

Before we proceed, since Ansible does not allow us to pass a cleartext password through the User module, we'll need to leverage on a password hashing library in Python.

$ pip install passlib

Update User Password with Ansible Playbook

Setup your playbook as followed. Let's call it change-password.yml. This playbook aims to update the password for the user admin across all hosts.

- hosts: all
  become: yes
    - name: Change user password
        name: admin
        update_password: always
        password: "{{ newpassword|password_hash('sha512') }}"

To run this playbook, run the command as below. This will input the newpassword variable that will be used by our playbook.

$ ansible-playbook -i hostfile change-password.yml --extra-vars newpassword=12345678

Update User Password with Ansible from Command Line

Alternatively, if you prefer to run it only one time from command line directly, here's the command that will do the same thing as the playbook above:

$ ansible -i hostfile all -m user -a "name=admin update_password=always password={{ newpassword|password_hash('sha512') }}" -b --extra-vars "newpassword=12345678"

Personally, I prefer the playbook approach as I could then commit to Github for future reuse.



Hello! My name is Jian Jye and I work on Laravel projects as my main job. If my article was helpful to you, a shoutout on Twitter would be awesome! I'm also available for hire if you need any help with Laravel. Contact me.