Depending on how random the string needs to be, you can generate a password in such a way that it's always the same for any given host and simply use it in the template.
The Ansible Jinja2 filter docs suggest "an idempotent method to generate unique hashes per system is to use a salt that is consistent between runs":
{{ 'secretpassword' | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}
Note that to decrease how guessable the resulting value is, you'll need to be sure to use something that's unique per host for the seed (e.g. inventory_hostname
might always be localhost
if your playbook is running locally):
PLAY [localhost] *********************************************************************************
TASK [Debug inventory_hostname.] *****************************************************************
ok: [localhost] =>
inventory_hostname: localhost
TASK [Debug idempotent random string.] ***********************************************************
ok: [localhost] =>
msg: $6$rounds=656000$21889$o7dtKP5aAPzYxyDIn9wbTRJMoQboNXtp0snNtTDvcU030aKvMyxsLzTGUuunG/hW2lBSLh/MS/C/c6Dx/uXo51