我被困住了,希望你能帮助我
我想基于以下带有vars的yml文件构建文件:
---
users:
- name: "user1"
db:
- name: "main"
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
schema:
- name: "public"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "notpublic"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "user2"
db:
- name: "main2"
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
schema:
- name: "public"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "nonpublic"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
如何遍历Jinja模板中声明的架构列表? 如果我使用以下结构
{% for user in users %}
{% for userdb in user.db %}
{% for s in userdb.schema %}
{{ s.name }}
{% endfor %}
{% endfor %}
{% endfor %}
在执行过程中出现以下错误:
FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'schema'"}
答案 0 :(得分:1)
以下剧本f.yml
---
- hosts: localhost
connection: local
gather_facts: False
vars:
users:
- name: "user1"
db:
- name: "main"
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
schema:
- name: "public"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "notpublic"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "user2"
db:
- name: "main2"
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
schema:
- name: "public"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "nonpublic"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
tasks:
- name: templating
template:
src: "f.jj"
dest: "f.txt"
使用此模板f.jj
{% for user in users %}
{% for userdb in user.db %}
{% for s in userdb.schema %}
{{ s.name }}
{% endfor %}
{% endfor %}
{% endfor %}
产生于
$ ansible-playbook f.yml
PLAY [localhost] ***************************************************************
TASK [templating] **************************************************************
ok: [localhost]
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
输出文件f.txt
public
notpublic
public
nonpublic