Search code examples
postgresqlloopsansibleenvironment-variableshost

How to iterate environment variables in ansible?


In this playbook

# db.yml

- hosts: deploy-server
  become: True
  roles:
    - db
  environment:
    PGHOST: "{{ db_host }}"
    PGPASSWORD: "{{ db_pass }}"

In db roles

# roles/db/tasks/main.yml

- name: Run sql
  shell: "psql -U postgres -f /sql"

I want to deploy the same sql script to multiple db servers.

For example, use these variables:

  • db_host1
  • db_host2
  • ...

Not by ssh but using psql. So is it possible to loop the PGHOST variable to set dynamic list to use?


Solution

  • Q: "Is it possible to loop the PGHOST variable?"

    A: Yes. It is possible. Set the environment variable in the loop, e.g.

    - hosts: localhost
      tasks:
        - command: "echo $PGHOST"
          register: result
          loop: [db_host1, db_host2]
          environment:
            PGHOST: "{{ item }}"
        - debug:
            msg: "{{ result.results|json_query('[].stdout') }}"
    

    gives

      msg:
      - db_host1
      - db_host2
    

    If you want to apply various environment to a role iterate include_role and apply the environment, e.g. the role

    shell> cat roles/db/tasks/main.yml 
    - command: "echo $PGHOST"
      register: result
    - debug:
        var: result.stdout
    

    and the playbook

    shell> cat pb.yml
    - hosts: localhost
      tasks:
        - include_role:
            name: db
            apply:
              environment:
                PGHOST: "{{ item }}"
          loop: [db_host1, db_host2]
    

    give

    ...
    
    TASK [include_role : db] ***********************************************
    
    TASK [db : command] ****************************************************
    changed: [localhost]
    
    TASK [db : debug] ******************************************************
    ok: [localhost] => 
      result.stdout: db_host1
    
    TASK [db : command] ****************************************************
    changed: [localhost]
    
    TASK [db : debug] ******************************************************
    ok: [localhost] => 
      result.stdout: db_host2
    
    ...