Changing different passwords for servers in Ansible

I have 10 Linux servers. I am going to change the password of the root user for all servers. I have written a playbook with “expect” and “user” modules, but I need to run this playbook separately for each server.
*My playbook for change eatch server password

  • name: change password server 1
    command: passwd root
    (?i)password: ‘adfatgqweeee’
    no_log: true
    tags: [change_pass1]

  • name: change password server 2
    command: passwd root
    (?i)password: ‘adfatgqweeee’
    no_log: true
    tags: [change_pass2]

****** Playbook command******

ansible-playbook -i inventory/host_test myproject.yml --tags change_pass1

ansible-playbook -i inventory/host_test myproject.yml --tags change_pass2


I am looking for a solution to set a different password for each server through a playbook. for example :
var1: server1
var2: server2
var3: server3
var10: server10

var1: srver_pass1
var2: srver_pass2
var3: srver_pass3
var4: srver_pass4

I know that passwords and servers should be defined as variables, but I don’t know how to write the playbook. I would be grateful if you could advise me on this matter.

Very Introductory Example

It sounds like you are at the beginning of your ansible learning and testing. Here’s a quick and simple example to achieve what you want.

–This is a very brief example, do not use this for production–

Change to your working directory.
Create a file named inventory. Add a line for each server, using this as your example:

# File: ~/workspace/inventory
server_1 root_pass=Password1
server_2 root_pass=Password2
server_3 root_pass=Password3

Create a playbook for changing the password on each system.

# File: ~/workspace/play_change_passwords.yml
- name: Change Root Password
  hosts: servers
  become: yes
  become_method: sudo
  become_user: root
  become_flags: '-i'
    - name: Change Root Password
        name: root
        password: "{{ root_pass | password_hash('sha512') }}"

Run the playbook:
ansible-playbook -i ~/workspace/inventory ~/workspace/play_change_passwords.yml

Key Takeaways and Things to Research

Inventory and Passwords

Do not use this inventory file in production. The playbook idea is alright, but handling inventories and passwords should not be done like I have above.

Ansible Setup

Research how to setup a basic ansible-core environment.
This Ansible Documentation is a great starting point.

Ansible Vaults

Research how to use ansible-vault command and ANSIBLE_VAULT_PASSWORD_FILE environment variable to begin securely storing passwords and other sensitive information. For example, this is where you would store root_password: YourRootPassword

Host Vars

Research how to setup a host_vars directory and use it to store variables that are unique to each host in your inventory.