Ansible: How to fill dict value with random passwords?

Viewed 43

given this dictionary:

  passes:
    sql_x:
      password:
    sql_y:
      password:

I want to create random passwords for any key in the passes dict.

How do I loop through the keys in the dict and fill the password value with a random password?

I was able to do it with a list but I need to use a dict.

Something like this:

- name: create passwords
  set_fact: "{{ item.value.password}}": "{{ lookup('password', '/dev/null', seed=inventory_hostname) }}"
  loop: "{{ lookup('dict', passes) }}"

This code above does not work of course, just for clearance what I am trying to achieve.

Thanks for any hint.

1 Answers

you loop over dict2items

- name: "make this working"
  hosts: localhost

  vars: 
    passes:
      sql_x:
        password:
      sql_y:
        password:

  tasks:
    - name: Debug
      set_fact:
        passes: "{{ passes  | combine ({item.key: {'password': password}})  }}"        
      loop: "{{ passes | dict2items }}"
      vars: 
        password: "{{ lookup('password', '/dev/null') }}"

    - name: display
      debug:
        msg: "{{ passes }}"

result:

ok: [localhost] => {
    "msg": {
        "sql_x": {
            "password": "kcOqz_mbIiiT0Wo_2Qox"
        },
        "sql_y": {
            "password": "TMN_nKbnAEIzI5w-8Of."
        }
    }
}
Related