Automate Root Password Change using Ansible Playbook

Updating/Changing the root user’s password is a routine task being performed by every Linux administrator in any organization. Earlier people used to accomplish this task using a script. This task can be automated using an Ansible playbook.

Step 1: Generate password hash

In order to generate a password hash, it is necessary to have hashing library (passlib) installed on the system where you are trying to generate a password hash. Use the below command to install the passlib library.

[root@ansible-host ~]# pip install passlib

Use below command to generate password hash:

[root@ansible-host ~]# python -c "from passlib.hash import sha512_crypt; import getpass; print sha512_crypt.encrypt(getpass.getpass())"
Password:
$6$rounds=656000$nv6b5eRCf0MA3Uth$YLcyFUT63rTMB8crCejv5IdyOYIpv62l5FVt.jjw4cNuqPX8HyYwmx/w48SFq/LJtYLrEV92mje7jV0Nfm/9g0

Step 2: Write a playbook and use above generated hash in it.

Here the playbook:

---
- hosts: all
 gather_facts: no
 tasks:
 - name: Update Root user's Password
   user:
     name: root
     update_password: always
     password: $6$rounds=656000$nv6b5eRCf0MA3Uth$YLcyFUT63rTMB8crCejv5IdyOYIpv62l5FVt.jjw4cNuqPX8HyYwmx/w48SFq/LJtYLrEV92mje7jV0Nfm/9g0

Step 3: Check if written playbook is correct and no syntax error detected

Command to check the syntax is:

[root@ansible-host ~]# ansible-playbook --syntax-check update_password.yml

playbook: update_password.yml

As per above output there is no syntax error in the playbook.

Step 4: Run/Execute playbook

Finally run the playbook to change the password:

[root@ansible-host ~]# ansible-playbook update_password.yml