In addition to the answer @BOUKANDOURA Mhamed provided above, I had to modernize the python command by adding a couple of brackets round the print to avoid getting a Missing parentheses in call to 'print'
error.
So my playbook (without the safety cron job) looks something like this:
- hosts: satellite, debroom
gather_facts: no
tasks:
- name: backup shadow file
copy:
src: /etc/shadow
dest: /etc/shadow.ansible-bak
become: yes
- name: generate hash pass
delegate_to: localhost
command: python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.encrypt('{{new_password}}'))"
register: hashedpw
- debug:
var: hashedpw.stdout
- name: update password
user:
name: root
password: '{{hashedpw.stdout}}'
become: yes
I am also passing through my value for new_password
as an environment variable, when I run it like this:
ansible-playbook -i inventory.yml update_password.yml -e new_password=flufflykins123
This seems to be working fine for me, but I am left wondering if the crypto settings on @BOUKANDOURA Mhamed 's original answer maybe needs updating to something stronger, since it's 2025?