EN VI

Ansible - How to remove duplicate parameters in a playbook?

2024-03-13 03:30:09
Ansible - How to remove duplicate parameters in a playbook?

Given that I have a role name postgres that runs locally and has this definition of roles/postgres/tasks/main.yml

- name: Ping
  postgresql_ping:
    login_host: localhost
    login_user: postgres
    login_password: postgres
    db: postgres

- name: Create database
  postgresql_db:
    login_host: localhost
    login_user: postgres
    login_password: postgres
    name: newdb
    encoding: UTF-8

- name: Drop database
  postgresql_db:
    login_host: localhost
    login_user: postgres
    login_password: postgres
    name: newdb
    state: absent

Is there a way for me to reduce that by moving the parameters login_host, login_user, and login_password somewhere else so wherein I use the postgressql galaxy collection, it will always connect to the same database instance?

Solution:

The postgres modules ultimately use the libpq library, which means you can use any of the standard environment variables. That means you should be able to write your playbook like this:

- hosts: localhost
  gather_facts: false
  collections:
  - community.postgres
  environment:
    PGHOST: localhost
    PGUSER: postgres
    PGPASSWORD: secret
  tasks:
  - name: Ping
    postgresql_ping:

  - name: Create database
    postgresql_db:
      name: newdb
      encoding: UTF-8

  - name: Drop database
    postgresql_db:
      name: newdb
      state: absent

Absent explicit configuration in each task, the modules will use the values from the PG* environment variables.


There are three places you can set environment variabeles in Ansible:

  1. At the playbook level, as demonstrated above.

  2. At the task level:

    - postgresl_ping:
      environment:
        PGHOST: localhost
        PGUSER: postgres
        PGPASSWORD: secret
    
  3. Outside of your playbook:

    PGHOST=localhost PGUSER=postgres PGPASSWORD=secret \
    ansible-playbook playbook.yaml
    

If you execute roles using import_role or include_role, you can use option 2, above, to set per-role environment variables:

- hosts: localhost
  gather_facts: false
  collections:
  - community.postgres
  tasks:
    - import_role:
        name: postgres
      environment:
        PGHOST: localhost
        PGUSER: postgres
        PGPASSWORD: secret
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login