0

I know in Ansible we can generate random number with unique seed

- name: generate random suffix
  set_fact:
    rand_num: "{{ 1000000 | random(seed=variable_name) | hash('md5') }}"

So, if I want to generate a random string with the seed, how can I generate it?

We have Ansible collection available for random string generation - Random String

Example:

- name: Generate a random string with all lower case characters
  debug:
    var: query('community.general.random_string', upper=false, numbers=false, special=false)

But here I couldn't find the option to put seed.

Thanks

U880D
  • 8,601
  • 6
  • 24
  • 40
LoGan
  • 97
  • 4
  • 13
  • You could have also just rephrased or edited [Ansible code to create a random string with fixed hashing](https://stackoverflow.com/questions/73876934/) ... – U880D Sep 29 '22 at 08:44

1 Answers1

0

According the documentation random_string lookup – Generates random string and your example

upper=false, numbers=false, special=false

I understand that you like to generate a random string of length 8 (since that is the default value of parameter length for module random_string) without numbers and special characters and lower case only. In other words, just a short random string with specific properties.

How to generate an idempotent but random string of length 8 without numbers and special characters and lower case only?

To do so, one can use the password lookup – retrieve or generate a random ... as well. It will only be necessary to define the properties of the result set (chars=ascii_letters,digit length=8' | lower).

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Show string with 8 lowercase characters
    debug:
      msg: "{{ lookup('password', '/dev/null chars=ascii_letters,digit length=8') | lower }}"

As of Ansible v2.12 a Parameter: seed is available

- name: Generate password
  set_fact:
    PASSWORD: "{{ lookup('password', '/dev/null chars=ascii_letters,digit length=8', seed=inventory_hostname) | lower }}"

to make the result idempotent.

With this approach one'll get a string with the required properties. The random_string module support the definition of more or other properties, which you are not using and depend on according your initial description.

U880D
  • 8,601
  • 6
  • 24
  • 40