'How to execute a task on user creation in Ansible

I want to automate user creation/maintenance through Ansible. I want every new user to have to choose a new password once they log in for the first time.

Imagine that I have a list of users with their names, passwords, groups, etc. in a vars file. I then have a role which does this:

 ---
    - name: Add/maintain users
      user:
        name: "{{ item.name }}"
        password: "{{ item.password }}"
        update_password: on_create
        createhome: true
        generate_ssh_key: true
        groups: "{{ item.groups}}"
        shell: /bin/bash
        state: present
      register: users_added
      with_items: "{{ users }}"

    - name: Force created users to change password
      shell: "chage -d 0 {{ item.name }}"
      when: "{{ item.changed }}"
      with_items: "{{ users_added.results }}"

    - name: Set authorized keys
      authorized_key:
        user: "{{ item.name }}"
        key: "{{ item.item.authorized_key }}"
        manage_dir: yes
      when: "{{ item.changed }}"
      with_items: "{{ users_added.results }}"

I want the second task ("Force created users to change password") to be triggered only for newly created users. The best thing I've found so far is to check if it's been changed.

Unfortunately, this is triggered if the user does not have a SSH key. The user which runs this task does not have a SSH key when a machine is provisioned. Ansible expires its password and every subsequent command fails because it needs sudo.

Anyone knows of a way to make a task work only if a user has been created ? Something like generate_ssh_key's on_create option.



Solution 1:[1]

system: boolean Choices: no ? yes When creating an account state=present, setting this to yes makes the user a system account. This setting cannot be changed on existing users.

- name: Force created users to change password
  shell: "chage -d 0 {{ item.name }}"
  when: **item.changed and item.system is defined and not item.system**
  with_items: "{{ users_added.results }}"

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 SiAl