2
votes

I am having trouble getting my jinja2 template from ansible to be able to read a global variable set in group_vars/all.yml.

** My Question is **: How can I get my j2 template to be able to see global variables set within group_vars/all.yml? from my understanding, group_vars/all should apply to all groups.

My ansible project is as follows:

group_vars/
  all.yml

playbooks/
  roles/
    some-role/
      tasks/
        main.yml
      templates/
        template.conf.j2
  my-playbook.yml

tasks/main.yml

---
- name: do it
  template:
    src: template.conf.j2
    dest: ...

templates/template.conf.j2

The global variable is: {{ GlobalVariable }}

group_vars/all.yml

GlobalVariable: something

When I run the playbook, I get an error when trying to write that template.

AnsibleUndefinedVariable: One or more undefined variables: 'GlobalVariable' is undefined
1

1 Answers

4
votes

Place your group_vars folder inside playbooks folder and it should solve your problem.

Something like that:

playbooks/
  group_vars/
    all.yml
  roles/
    some-role/
      tasks/
        main.yml
      templates/
        template.conf.j2
  my-playbook.yml

Then no matter where you executing you ansible-playbook -i hosts my-playbook.yml command (outside of playbook or inside) it should work

Here is little more explanation with reference to the source-code

   """
    Loads variables from group_vars/<groupname> and host_vars/<hostname> in directories parallel
    to the inventory base directory or in the same directory as the playbook.  Variables in the playbook
    dir will win over the inventory dir if files are in both.
    """