我正在尝试使用 jinja2 通过 ansible 模板循环字典以创建多个数据源,但收到此错误[{'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'value'", 'failed': True}]}
运行调试任务时,它确实会返回正确的值,所以我觉得我的问题出在模板本身,但我一直无法弄清楚我做错了什么。
Ansible 任务
- name: debug dictionary
debug: msg="{{ item.value.db_url }}"
with_dict: databases
- name: copy tomcat config files
template: src="{{ item.src }}" dest="{{ item.dest }}"
with_items:
- { src: 'context.xml.j2', dest: '/opt/tomcat/conf/context.xml'}
notify: restart tomcat
with_dict: databases
Ansible 字典
databases:
db1:
db_resource: jdbc/db1
db_maxidle: 50
db_maxconn: 350
db_maxwait: 10000
db_user: dbuser
db_pass: "{{ dbpass }}"
db_url: jdbc:postgresql://server:5432/dbname
db_driver: org.postgresql.Driver
Jinja2 模板
{% for items in databases %}
<resource name="{{ item.value.db_resource }}" auth="container" type="javax.sql.datasource" maxtotal="{{ item.value.db_maxconn }}" maxidle="{{ item.value.db_maxidle }}" maxwaitmillis="{{ item.value.db_maxwait }}" username="{{ item.value.db_user }}" password="{{ item.value.db_pass }}" driverclassname="{{ item.value.db_driver }}" url="{{ item.value.db_url }}" />
{% endfor %}
调试输出
ok: [IP] => (item={'key': 'db1', 'value': {'db_maxwait': 10000, 'db_maxconn': 350, 'db_maxidle': 50, 'db_driver': 'org.postgresql.Driver', 'db_pass': u'REDACTED', 'db_resource': 'jdbc/db1', 'db_user': 'dbuser', 'db_url': 'jdbc:postgresql://server:5432/dbname'}}) => {
"item": {
"key": "db1",
"value": {
"db_driver": "org.postgresql.Driver",
"db_maxconn": 350,
"db_maxidle": 50,
"db_maxwait": 10000,
"db_pass": "REDACTED",
"db_resource": "jdbc/db1",
"db_url": "jdbc:postgresql://server:5432/db",
"db_user": "dbuser"
}
},
"msg": "jdbc:postgresql://server:5432/dbname"
}