Search code examples
ansibleansible-template

Use Dict in Vars with Templates in Ansible


I'm trying to use templates with different sets of variables for each itteration of a determined set of tasks. For example, in one of the tasks I'd like to set specific values for postgres:

- name: Define values for postgres-ds
  template:
    src: postgres-ds.xml.j2
    dest: /opt/ear_{{ instance_control.value }}/postgres-ds.xml
  vars: "{{ postgres_desenv }}"
  notify: Restart Service

In role/vars/main.yaml, I defined:

postgres_desenv:
  var1: somevalue
  var2: someothervalue
  ...

Still, I get the following error:

fatal: [rmt]: FAILED! => {
    "failed": true, 
    "reason": "Vars in a Task must be specified as a dictionary, or a list of dictionaries
    ...

When I try to use the same variable in another context, it works fine:

- debug:
    msg: "{{ item.key }} - {{ item.value }}"
  with_dict: "{{ postgres_desenv }}"

I tried following the answers to this question but I'm still stuck.


My next step is to use a variable to call the variable inside vars, something like:

- name: Define values for postgres-ds
  template:
    src: postgres-ds.xml.j2
    dest: /opt/ear_{{ instance_control.value }}/postgres-ds.xml
  vars: postgres_{{ another_var }}
  notify: Restart Service

Solution

  • You can do something like this:

    - name: Define values for postgres-ds
      template:
        src: postgres-ds.xml.j2
        dest: /opt/ear_{{ instance_control.value }}/postgres-ds.xml
      vars:
        settings: "{{ postgres_desenv }}"
      notify: Restart Service
    

    Then within the template you could refer to, e.g.,

    {{ settings.var1 }}