'How to create a random string and use it in jinja in Ansible

I would like to create a random string in Ansible tasks and use it in jinja2.
The string should contain 0-9, a-z, A-Z with a length of 32 characters.

I found out this function but can't use it in a set_fact

lookup('community.general.random_string', length=12)

I'm using Ansible 2.12.1 set_fact writes the string "lookup('community.general.random_string', length=12)" in me template. I need to create once a random string to use it as passphrase in a config file. On the second run the random string should not be touched - need to add also a check if file exists or something like that.



Solution 1:[1]

A way to create a random string and then add it as a fact would be something like this

---
- hosts: test

  vars:
    my_pass_var: "{{ lookup('password', '/dev/null length=32 chars=ascii_letters,digits') }}"
    
  tasks:
    - set_fact:
        my_pass_as_fact: "{{ my_pass_var }}"
    - debug:
        msg: "{{ my_pass_as_fact }}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 β.εηοιτ.βε