Ansible handling password change on first login

3.8k Views Asked by At

I am creating a playbook that login to a Virtual Machine and perform initial configuration. The image used to create the VM has a default user name that need change of password on initial login. I am looking for a way how to handle this in Ansible?

2

There are 2 best solutions below

5
On

You are looking for the user module, especially the password option.

Keep in mind, that the password option needs the hash of the actual password. Check here how to get that it. (It needs to be hashed, otherwise you would have a cleartext password in your playbook or inventory which would be a security risk.)

Example:

- name: ensure password of default user is changed
  user:
    name: yourdefaultuser
    password: '$6$QkjC8ur2WfMfYGA$ZNUxTGoe5./F0b4GJGrcEA.ff9An473wmPsmU4xv00nSrN4D/Nxk8aKro/E/LlQVkUJLbLL6qk2/Lxw5Oxs2m.'

Note that the password hash was generated with mkpasswd --method=sha-512 for the password somerandompassword.

1
On

I found solution for my problem as follow using ansible module "expect" https://docs.ansible.com/ansible/latest/collections/ansible/builtin/expect_module.html

- name: Change password on initial login
  delegate_to: 127.0.0.1
  become: no
  expect:
    command: ssh {{ ansible_ssh_common_args }} {{ user_expert }}@{{ inventory_hostname }}
    timeout: 20
    responses:
      Password: "{{ user_expert_password }}"
      UNIX password: "{{ user_expert_password }}"
      New password: "{{ user_expert_password_new }}"
      new password:  "{{ user_expert_password_new }}"
      "\\~\\]\\$": exit
  register: status