Ansible to generate random passwords automatically for users

16,945

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.

Share:
16,945

Related videos on Youtube

Pablo
Author by

Pablo

Updated on June 04, 2022

Comments

  • Pablo
    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
    Pablo over 8 years
    Just needed to add encrypt parameter and it worked like a charm! tks
  • Arbab Nazar
    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
    Pablo over 8 years
    {{ lookup('password', 'credentials/' + item.name + '/password.txt encrypt=md5_crypt') }}
  • koniu
    koniu about 8 years
    The <path> in password: "{{ lookup('password', <path>) }}" appears to actually denote a file location on the localhost (the master), not the remote node?
  • zedix
    zedix over 7 years
    Yes, the path denotes a path on the machine running the playbook, not the remote hosts...
  • thinkmassive
    thinkmassive over 5 years
    New link to Ansible docs: password lookup
  • Loenix
    Loenix almost 4 years
    How 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