[英]undefined variable error in ansible when using jinja2 templates
我正在練習 ansible。 我已經完成了基本操作,現在我正在構建一個 jinja2 模板並使用它。 當我需要為組構建報告並將它們上傳到各自的 dns 服務器時,有一個練習。 美國組中所有服務器的報告將上傳到 dns_server_america,亞洲也是如此。
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
這是 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
這是 jinja2 模板。
{% for host in groups[GROUP_NAME] %}
{{ host }} {{ hostvars[host]['ansible_host'] }}
{% endfor %}
為什么我們不在 jinja2 模板中引用[host]和[GROUP_NAME] 。 Ansible 說,當變量放在方括號中時,它們應該用引號括起來。 當我用引號括起來時,我收到一條錯誤消息“未定義的變量”,當我刪除引號時,我能夠成功運行劇本。 請告知,我可能遺漏了一些東西,或者我理解變量的理論可能是錯誤的。
問: “為什么我們不在 jinja2 模板中引用 [host] 和 [GROUP_NAME]?”
A: host和GROUP_NAME都是變量。 索引中需要變量的值。 如果變量的名稱被引用“host”或“GROUP_NAME” ,則使用變量的名稱而不是變量的值。
直接和間接
例如,模板
shell> cat test.txt.j2
{{ dict[index] }}
{{ dict['index'] }}
和劇本
shell> cat playbook.yml
- hosts: localhost
vars:
dict:
index: value of attribute index
attr1: value of attribute attr1
tasks:
- template:
src: test.txt.j2
dest: test.txt
vars:
index: attr1
給
shell> cat test.txt
value of attribute attr1
value of attribute index
這不僅限於模板。 它通常是有效的。 例如
- debug:
msg:
- "{{ dict[index] }}"
- "{{ dict['index'] }}"
vars:
index: attr1
給
msg:
- value of attribute attr1
- value of attribute index
點綴
可以使用“dotted”引用。 例如
- debug:
var: dict.index
給
dict.index: value of attribute index
“dotted”引用可用於嵌套字典。 例如使用嵌套字典
dict:
index:
var1: value of attribute index
attr1:
var1: value of attribute attr1
兩個版本都按預期工作
- debug:
msg:
- "{{ dict.index.var1 }}"
- "{{ dict['index'].var1 }}"
vars:
index: attr1
給
msg:
- value of attribute index
- value of attribute index
模板中的虛線引用
但是使用模板時有區別。 當引用放入括號[]
時,所有后續引用也必須放入括號中。 否則,模板將失敗。 例如
shell> cat test.txt.j2
{{ dict.index.var1 }} # OK
{{ dict.index['var1'] }} # OK
{{ dict['index']['var1'] }} # OK
{{ dict['index'].var1 }} # WRONG: has no attribute var1
將失敗
fatal: [localhost]: FAILED! => changed=false
msg: 'AnsibleUndefinedVariable:
''ansible.parsing.yaml.objects.AnsibleUnicode object''
has no attribute ''var1'''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.