Reputation: 5
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?
Upvotes: 0
Views: 5555
Reputation: 2615
There are 2 main issues in your playbook:
userexists
is registering each result individually, but you are referencing only the overall "failure" result. Use a debug
statement to show the variable to see what I meanThere's a couple of different approaches to fix this, but I think this might be the most succinct:
tasks:
- name: add user if it does not exist
user:
name: "{{ item }}"
password: "{{ 'password' | password_hash('sha512', 'mysecretsalt') }}"
update_password: on_create
loop: "{{ users }}"
register: useradd
notify: change password
handlers:
- name: change user password upon creation
shell: chage -d 0 {{ item.name }}
loop: "{{ useradd.results }}"
when: item.changed
listen: change password
Upvotes: 2