Change Database Password

Ansible’s extra variables (-e or --extra-vars) is used to pass the new password securely from the command line without hardcoding it into the playbook. Here’s the playbook:

Ansible Playbook

update_password.yml
---
- name: Update PostgreSQL user password
  hosts: all
  become: true # Use sudo for root-level tasks
  become_user: postgres # Execute commands as the postgres user

  tasks:
    - name: Update the password for the database user
      ansible.builtin.postgresql_user:
        name: "deploy"
        password: "{{ db_new_password }}"
        state: present

Run the Playbook

To run this playbook and pass the db_new_password securely via the command line, you can use the following command:

ansible-playbook -i inventory.ini update-password.yml -e "db_new_password=yourNewPasswordHere"

Replace yourNewPasswordHere with the actual password you want to set. If you are running this command in a script or a context where the password might be visible in the command history or logs, consider other methods of securing the password input.

The instructions for Creating Inventory File.

More Secure Alternatives:

  1. Ansible Vault: For a more secure approach, consider using Ansible Vault to encrypt the password variable or an entire variables file. Here’s how you can create an encrypted variable:

    • First, create a file with the password:
      ansible-vault create secret_vars.yml
    • Inside the file, set the variable:
      db_new_password: yourEncryptedPassword
    • Save and close the editor. The file is now encrypted.
    • Run the playbook using:
      ansible-playbook update-password.yml --ask-vault-pass -e "@secret_vars.yml"
    • Ansible will ask for the Vault password to decrypt the file during execution.
  2. Environment Variables: If you are running this playbook in an automated environment, consider passing sensitive data using environment variables and fetching them in the playbook with the lookup plugin:

    • Modify the playbook to use an environment variable:
      password: "{{ lookup('env', 'DB_NEW_PASSWORD') }}"
    • Set the environment variable in your session before running the playbook:
      export DB_NEW_PASSWORD=yourNewPasswordHere
      ansible-playbook update-password.yml
    • Ensure the environment variable is not logged or displayed in any debug output.

These methods ensure that sensitive data like database passwords are not exposed and are handled securely according to best practices.