[英]how to pass ansible group_vars array to jinja template
I'm trying to template a python script using ansible jinja2. 我正在尝试使用ansible jinja2模板化python脚本。 When I pass the iterated item to the template to further generate a python dictionary is not working. 当我将迭代项传递到模板以进一步生成python字典时,它不起作用。
Thanks in advance for any help!. 在此先感谢您的帮助!
[group_vars]
backups:
- sap
sap:
- db_host: sadf
- db_name: xyz
- db_user: xzzx
- db_pass: alskdf
ansible template looks like: ansible模板如下所示:
- name: transfer backup script file
template:
src: backup.py.j2
dest: "{{ item }}_backup.py"
mode: 0755
with_items:
- "{{ backups }}"
jinja python template looks like: jinja python模板看起来像:
dbs = {
{% for mongo_d in item %}
"{{ mongo_d.db_name }}" :
{
"db_host": "{{ mongo_d.db_host }}",
"db_user": "{{ mongo_d.db_user }}",
"db_password": "{{ mongo_d.db_password }}",
]},
{% endfor %}
failing with error: 失败并显示错误:
item: sap
msg: 'AnsibleUndefinedVariable: ''unicode object'' has no attribute ''db_name'''
Your data structure is cumbersome, use a dictionary instead of a list with single key-value pairs: 您的数据结构繁琐,请使用字典而不是包含单个键值对的列表:
backups:
- sap
sap:
db_host: sadf
db_name: xyz
db_user: xzzx
db_password: alskdf
You don't need to iterate inside the template. 您无需在模板内进行迭代。
The task: 任务:
- name: transfer backup script file
template:
src: backup.py.j2
dest: "{{ item }}_backup.py"
mode: 0755
with_items:
- "{{ backups }}"
vars:
mongo_d: "{{ lookup('vars', item) }}"
The template: 模板:
dbs = {
"{{ mongo_d.db_name }}" :
{
"db_host": "{{ mongo_d.db_host }}",
"db_user": "{{ mongo_d.db_user }}",
"db_password": "{{ mongo_d.db_password }}",
]},
I corrected db_password
typo, but for inconsistencies in the template, I left them as posted in the question. 我更正了db_password
错字,但是由于模板中的不一致,我将其保留在问题中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.