为用户生成随机密码并存储它们以便以后使用

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

我正在尝试为一组用户生成随机密码,显示这些密码并通过电子邮件发送。
但是在用户模块中使用它之后,稍后尝试将其作为电子邮件发送时,密码变量会创建一个新的密码字符串。

我想将密码附加到用户列表。
这是我到目前为止尝试过的:

  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 }}"

您已经在 id_pass 变量中生成了一个随机密码。
要为每个用户生成随机密码,请执行以下操作:

- 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 }}"

您现在在列表的每个项目中都会有一个名为 password 的字段。您可以使用它来设置用户的密码并将其发送给他们。