How to loop into user defined variables and use them to generate file using jinja template in ansible?

Hi,

I have a roles/myrole/vars/main.yml as below:

HAProxy_Vars:
ADMIN: “{{ lookup(‘env’, ‘ADMIN’) }}”
MANAGED1: “{{ lookup(‘env’, ‘MANAGED1’) }}”
MANAGED2: “{{ lookup(‘env’, ‘MANAGED2’) }}”
MANAGED1PORT: “{{ lookup(‘env’, ‘MANAGED1PORT’)|default(‘20300’,true) }}”
MANAGED2PORT: “{{ lookup(‘env’, ‘MANAGED2PORT’)|default(‘20300’,true) }}”
ENVHOME: “{{ lookup(‘env’, ‘HOME’) }}”

roles/myrole/tasks/main.yml as below:

looping into HAProxy_Vars to verify each and every value are assigned something otherwise it should fail.

  • name: “Checking if all variables are assigned during haproxy-installation role”
    fail: msg=“Variable ‘{{ item }}’ is not defined”

when: item.value == “”
with_dict: “{{ HAProxy_Vars }}”

Below is giving me hard time. Any of above mentioned variable are not identified by ansible during generation of file using eg: {{ ENVHOME }} in jinja2 template.

  • name: “Generating correct service file with jinja2 template”
    tags: “haproxy-service-jinja”
    template:
    src: haproxy.service.j2
    dest: /usr/lib/systemd/system/haproxy.service
    owner: root
    group: root
    mode: ‘0600’

It fails with:

TASK [haproxy-installation : Generating correct service file with jinja2 template] ***
task path: /ossusr01/oss/users/acdoss07/ACDSOM/roles/haproxy-installation/tasks/main.yml:36
fatal: [adminserver]: FAILED! => {“changed”: false, “failed”: true, “invocation”: {“module_args”: {“dest”: “/usr/lib/systemd/system/haproxy.service”, “group”: “root”, “mode”: “0600”, “owner”: “root”, “src”: “haproxy.service.j2”}, “module_name”: “template”}, “msg”: “AnsibleUndefinedVariable: 'ENVHOME’ is undefined”}

What am I doing wrong here?

ENVHOME doesn't exist.
Your varible is a dictionary called HAProxy_Vars, so you need to use the complete name {{ HAProxy_Vars.ENVHOME }}