我有一個YAML文件,其中包含我想在Ansible模板中使用的變量。該文件是這樣的:模板中的Ansible嵌套循環
---
config:
version: "4.0"
description: "Global configuration"
sites:
- name: "Site J"
description: "Ficititious Site J"
servers:
- hostname: server1
- hostname: server2
- hostname: server3
- name: "Site K"
description: "Ficititious Site K"
- name: "Site L"
description: "Ficititious Site L"
我會嘗試引用服務器,但是,對於我的生活不能在Jinja2的模板找出語法。這裏是我當前的模板:
{{ config | to_nice_json }}
{% for site in config['sites'] %}
{{ site['name'] }}
{{ site['description'] }}
{% endfor %}
,輸出是:
{
"description": "Global configuration",
"sites": [
{
"description": "Ficititious Site J",
"name": "Site J",
"servers": [
{
"hostname": "server1"
},
{
"hostname": "server2"
},
{
"hostname": "server3"
}
]
},
{
"description": "Ficititious Site K",
"name": "Site K"
},
{
"description": "Ficititious Site L",
"name": "Site L"
}
],
"version": "4.0"
}
Site J
Ficititious Site J
Site K
Ficititious Site K
Site L
Ficititious Site L
我的問題是訪問數據在「服務器:」現有網站內環路。嵌套循環最明顯的語法:
{% for server in site['servers'] %}
{{ server['hostname'] }}
{% endfor %}
不起作用。我得到這個Ansible錯誤:
fatal: [localhost] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict' object has no attribute 'servers'", 'failed': True}
在每個站點下的YAML文件中循環服務器的正確語法是什麼?我嘗試了很多變化,似乎無法找到合適的變體。
感謝,馬特。模板我最終在對它的值進行任何操作之前先檢查「servers」鍵,這是一個字典列表。我的模板很長,但至少現在我明白了數據結構! – geary