ansible user module change passwd

hello,all

i want to use ansible user module to change password on the remote hosts,

but , if the user is not in the remote hosts, ansible will create the user, how can i change password only, if user is not exist, return error is ok;

Please try the below. It works.

i tried, the playbook still creates the user if user not exists on the remote hosts ;

It worked for me. It throws error if user doesn’t exist.

i tried, the playbook still creates the user if user not exists on
the remote hosts ;

You'll need to add a test to check if the user exist and use a when on the update password task.

---
- hosts: localhost
  remote_user: root
  become: yes
  gather_facts: yes
  vars:
    user_name: youruser

  vars_prompt:
    - name: "new_password"
      prompt: "Enter New Password"
      private: yes
      encrypt: "md5_crypt"
      confirm: yes
      salt_size: 7

  tasks:
    - name: Change password of existing user
      user: name={{user_name}} update_password=always password={{new_password}}

tasks:
   - name: Get information about the user
     getent:
       key={{user_name}}
       database=passwd
       fail_key=false

   - name: Change password of existing user
     user:
       name={{user_name}}
       update_password=always
       password={{new_password}}
     when: getent_passwd[user_name] != None

thanks for ur advice, i have aix and linux, i wrote the playbook based on ur reply, it works , but i think it’s too long, is there a better way to rewrite this ?

thanks for ur advice, i have aix and linux, i wrote the playbook based on ur reply, it works , but i think it's too long, is there a better way to rewrite this ?

In my opinion it's not long, you could but the code in it's one file and use include if you would like the playbook to have less code.

---
- name: test
  hosts: all
  gather_facts: true

  tasks:
   - name: Get information about the user for linux
     getent:
       key=foo
       database=passwd
       fail_key=false
     register: user_info_linux
     when: ansible_system == 'Linux'
   - debug: var=user_info_linux

   - name: Get information about the user for aix
     command: "lsuser foo"
     ignore_errors: yes
     register: user_info_aix
     when: ansible_system == 'AIX'
   - debug: var=user_info_aix

   - name: change pwd for linux
     command: uname -a
     when: ansible_system == 'Linux' and user_info_linux.ansible_facts.getent_passwd.foo != None

   - name: change pwd for aix
     command: uname -a
     when: ansible_system == 'AIX' and user_info_aix.stdout != ""

The other option is to use grep/egrep on /etc/passwd, the you can use the same code on AIX and Linux. I think AIX has egrep.

tasks:
   - Name get user
     shell: egrep "^{{ user }}:" /etc/passwd
     register: user_info

   - name: Change passwd
     command: <whatever to change password>
     when: user_info.rc == 0

thanks, my final playbook comes to this, works pretty well, problem solved!