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.
[php]
*My playbook for change eatch server password

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

  • name: change password server 2
    expect:
    command: passwd root
    responses:
    (?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

[/php]

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

var1: srver_pass1
var2: srver_pass2
var3: srver_pass3
.
.
.
var4: srver_pass4
[/php]

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
[servers]
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'
  
  tasks:
    - name: Change Root Password
      ansible.builtin.user:
        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.