Cloud-init, Ansible and usermod -p want a password hash, not the password itself. openssl passwd -6 makes the same SHA-512 crypt format that /etc/shadow uses.
Run it without the password on the command line, so it prompts you:
openssl passwd -6
The result looks like $6$salt$long-hash. The $6$ marks SHA-512 crypt, followed by a random salt and the hash. Every run uses a new salt, so the same password gives a different string each time, and both work.
In a script, read the password from standard input rather than an argument:
printf '%s\n' "$PW" | openssl passwd -6 -stdin
Then use it, for example with usermod -p '$6$...' alice, or in the passwd field of cloud-init. Keep the single quotes, since the dollar signs would otherwise be expanded by your shell.
-5 gives SHA-256 crypt. Avoid -1, which is MD5 crypt, and note that OpenSSL 3 also falls back to MD5 when you give no flag at all. Recent Debian and Fedora releases default to yescrypt ($y$) in /etc/shadow, which OpenSSL cannot make, but they still accept $6$ hashes. I would still treat a hash like a secret: it can be attacked offline if it leaks.
Further reading: OpenSSL: openssl-passwd, crypt(5) man page