Ansible to generate random passwords automatically for users
The password
lookup can generate passwords for you and puts the generated password on the control machine (i.e. where the playbook is running). An example task that creates a user and sets their password may look something like this:
- name: Create users with auto generated password
user:
name: "{{ item.name }}"
password: "{{ lookup('password', 'credentials/' + item.name + '/password.txt encrypt=md5_crypt') }}"
with_items: users
This would then create a text file named ~/credentials/$username/password.txt
on the control machine. If you were to rerun the Ansible play then Ansible would recognise that filepath as the password and make sure to set the user's password to that same value - making it idempotent.
This doesn't get you quite what you wanted but gets all the information that you needed on to the Ansible control host so you could then further manipulate it to get the final output that you wanted.
Related videos on Youtube
Pablo
Updated on June 04, 2022Comments
-
Pablo almost 2 years
I am trying to create playbook where list of users will be created.
However, I also want to generate random password for each user. Once the passwords are generated, I would like to have a text file holding username:new_generated_password key values, next to the playbook file. Is it possible to do this without developing a new module?
-
Pablo over 8 yearsJust needed to add
encrypt
parameter and it worked like a charm! tks -
Arbab Nazar over 8 years@Pablo can you please paste your working example like where you have added the
encrypt
parameter, so that it will help other. Thanks -
Pablo over 8 years
{{ lookup('password', 'credentials/' + item.name + '/password.txt encrypt=md5_crypt') }}
-
koniu about 8 yearsThe
<path>
inpassword: "{{ lookup('password', <path>) }}"
appears to actually denote a file location on the localhost (the master), not the remote node? -
zedix over 7 yearsYes, the path denotes a path on the machine running the playbook, not the remote hosts...
-
thinkmassive over 5 yearsNew link to Ansible docs:
password
lookup -
Loenix almost 4 yearsHow to generate a password on remote host ? I don't want any ansible file on master host... If I change the master host, I will lost it... Only remote should know about passwords