Generate random passwords for users and store them so they can be used later

Viewed 531

I'm trying to generate random passwords for set of users, display those password and send them via email.
But after using it in the user module, and later trying to send it as email the password variable creates a new password string.

I want to either append the passwords to the user list.
This is what I have tried so far:

  vars:
    USER_ID_details:
      - user_id: testid1
        real_full_name: TESTID_1
        groups: wheel
        email_id: abc@abc.com
      - user_id: randnme
        groups: wheel
        real_full_name: TESTID_2
        email_id: abc@abc.com
    id_pass: "{{ lookup('password', '/dev/null length=15 chars=ascii_letters') }}"

  - name: create Linux user as per specification
    user:
      name: "{{ item.user_id }}"
      password: "{{ id_pass | password_hash('sha512') }}"
    loop: "{{ USER_ID_details }}"
    when:
      - os_type == "RedHat"
  - name: Send the details of the user id and password to the email address
    mail:
      subject: "*Confidential: {{ item.user_id }} user id created on {{ affected_host }}"
      body: "Hello, User id {{ item.user_id }} created on server {{ affected_host }} \n password: {{ id_pass }}"
      to: "{{ item.email_id }}"
    loop: "{{ USER_ID_details }}"
1 Answers

You are already generating a random password in your id_pass variable.
To generate a random password for every user, do this:

- set_fact:
    USER_ID_details: | 
      {{ USER_ID_details | map('combine', { "password": "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=15') }}"}) }}

# you need this, otherwise you will see different passwords every time you read the list
- set_fact:
    USER_ID_details: "{{ USER_ID_details }}"

You will now have a field called password in every item of your list. You can use that to set the user's password and send it to them.

Related