Just a quick note on our own behalf:

I created an Ansible role for changing the wifi key on Unifi systems.

Basically, what was scripted here with PyExpect is realized via Ansible script, which makes the implementation much easier.

As always, I make the whole thing available for free at:

Ansible Galaxy
Jump start your automation project with great content from the Ansible community
ansible_unifi_wifi_key_changer

The source code is available on Github:

GitHub - sowoi/ansible-unifi-wifi-key-changer: This role changes the WLAN key of a given SSID on the Unifi controller remotely.
This role changes the WLAN key of a given SSID on the Unifi controller remotely. - GitHub - sowoi/ansible-unifi-wifi-key-changer: This role changes the WLAN key of a given SSID on the Unifi control...