Automatic Password generator to work with Ansible

I recently had an Idea to change all of my root passwords across my entire environment using Ansible. Ansible made this pretty straight forward however what they did STILL required human interaction… Which I didn’t really want.. I wanted to make a cron job that would run this every X amount of months that would launch a script edit my playbook and launch the playbook and finally emailing our password to me (The email part I know is dicey and I am working on using curl to add it into our password management program via REST. I will edit this article later when this is done with the edits I make to the script). This seemingly simple task caused me a huge headache because the hash was contained to many characters for sed to pass properly and the python module (libpass) is a POS and it won’t accept variables passed in a string. I will start off with my Ansible playbook that i’m running to edit the accounts. It’s standard really, and you can find it right on Ansibles’ web site


- hosts: test
  - name: Change root password
    user: name=root update_password=always password=asd76aseJFSADA6/


(yes that’s all it contains)

As you can see from above there’s nothing special about changing passwords with Ansible. Just that you have to generate it manually and then edit the playbook with the updated hash for each password change.  (which drives me nuts). To automate this process I made a bash script which in hindsight is pretty simple..  It uses openssl to generate a 6 character password then uses crypt to create the hash, Adds it to the playbook, and then launches the playbook (see comments in script).

#Generate Random 6 char password
clearpass=`openssl rand -base64 6`
#Use sed to remove the user line to clear last password update
sed -i '/user/d' /etc/ansible/playbooks/rootpass.yml
#Use crypt to make a hash of your 6 char password
HASH=`openssl passwd -crypt "${clearpass}"`
#Add the User line back into the file with your new hash
echo "    user: name=root update_password=always password=${HASH}" >> /etc/ansible/playbooks/rootpass.yml
#Email me my new password
mail -s  ${clearpass} < /dev/null
#Launch playbook
ansible-playbook /etc/ansible/playbooks/rootpass.yml

And there it is! I so far have tested this method on Centos 5,6,7 I cannot verify functionality on any other OS; However I assume as long as you have openssl libs installed you should be good to go. Enjoy and hopefully I will save some other nerd time trying to jump through hoops.

Leave a Reply

Your email address will not be published.