I am practising ansible. I have come all way through basic and now I am working on building a jinja2 template and using it. There is an exercise when I need to build a report for groups and upload upload them to their respective dns server. Reports for all the server in american group will be uploaded to dns_server_america, similarly for asia.
dns_server_america ansible_host=172.20.1.100 ansible_ssh_pass=Passw0rd ansible_user=root
dns_server_asia ansible_host=172.20.1.101 ansible_ssh_pass=Passw0rd ansible_user=root
[america]
web0001 ansible_hostname=web0001.company.com ansible_host=10.1.1.101
web0002 ansible_hostname=web0002.company.com ansible_host=10.1.1.102
[asia]
web2001 ansible_hostname=web2001.company.com ansible_host=10.1.1.201
web2002 ansible_hostname=web2002.company.com ansible_host=10.1.1.202
This is the YAML.
- name: Generate dns hosts files on americas servers
hosts: dns_server_america
tasks:
- template: src=templates/hosts.j2 dest=/tmp/hosts.txt
vars:
GROUP_NAME: america
- name: Generate dns hosts files on asia servers
hosts: dns_server_asia
tasks:
- template: src=templates/hosts.j2 dest=/tmp/hosts.txt
vars:
GROUP_NAME: asia
This is the jinja2 template.
{% for host in groups[GROUP_NAME] %}
{{ host }} {{ hostvars[host]['ansible_host'] }}
{% endfor %}
Why are we not quoting [host] and [GROUP_NAME] in the jinja2 template. Ansible says that when variables are put in square brackets, they are supposed to be wrapped within quotes. When I enclose then with quotes, I get an error message "undefined variable" and when I remove the quotes I am able to run the playbook successfully. Please advise, I may be missing something or my theory of understanding variables could be wrong.