'Adding users in ansible and enforcing password change, resets user's password when adding new user

I am having problems with Ansible and adding new users to servers. Firstly I check if the users are present on the system and if not, then I proceed to create them.

I found a somewhat similar problem here: ansible user module always shows changed and I was able to fix the changed status when adding a new user in the file userlist with adding a simple salt. However, the last part, which is the handler, is always performed.

This is how my playbook looks like:

---
- hosts: all
  become: yes
  vars_files:
    - /home/ansible/userlist

  tasks:

    # check if user exists in system, using the username 
    # and trying to search inside passwd file
    - name: check user exists  
      getent:
        database: passwd
        key: "{{ item }}"
      loop: "{{ users }}"
      register: userexists
      ignore_errors: yes

    - name: add user if it does not exit
      user:
        name: "{{ item }}"
        password: "{{ 'password' | password_hash('sha512', 'mysecretsalt')  }}"
        update_password: on_create
      loop: "{{ users }}"
      when: userexists is failed
      notify: change password

  handlers:

    - name: change user password upon creation
      shell: chage -d 0 "{{ item }}"
      loop: "{{ users }}"
      listen: change password

And here is the simple file called userlist:

users:
- testuser1
- testuser2
- testuser3
- testuser22

When I am running the playbook without changes to the userlist file, everything is fine. However, if I add a new user to the file, then, when an existing user tries to log in, the system enforces them to change their password, because the handler is always called. Is there any way to alter the code in a way that the enforcing of changing the password immediately is only performed on newly created users?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source