Rebeca Maia
Rebeca Maia

Reputation: 438

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

Upvotes: 3

Views: 3887

Answers (3)

Ricky Levi
Ricky Levi

Reputation: 8007

In my case, following the answer above, all i had to do is using {{ item.value.(mydictkey) }} and that's it

In my case i defined a global variable like so:

vars:
  vhosts:
    web1
      port: 8080
      dir:  /mywebsite
    web2:
      ...

Then in the task I used:

- name: Render template
  template:        
    src:  "../templates/httpd.vhost.conf.j2"       # Local template
    dest: "/etc/httpd/conf.d/{{ item.key }}.conf"  # Remote destination
    owner: root
    group: root
    mode:  644      
  with_dict: "{{ vhosts }}"

In the template I used:

<VirtualHost *:{{ item.value.port }}>
  DocumentRoot /var/www/{{ item.value.dir }}
</VirtualHost>

Upvotes: 0

Tk Thomas
Tk Thomas

Reputation: 57

If postgres_desenv is defined in vars/main.yml that will be loaded automatically and be available to the role and rest of the playbook. Why do you have to specify that again using "vars" option in the template module task?

Upvotes: -1

larsks
larsks

Reputation: 312818

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 }}

Upvotes: 2

Related Questions