我是自动化和敏捷的第一个月,正在经历所有学习过程,但是我有一项工作需要花好几天的时间来尝试找出到目前为止没有太大的进展,因此,我将非常感谢您提供的所有提示和技巧。
我在Ansible all_vars.yml代码中有一个带有变量的YAML文件,等待在角色中运行,例如以下示例:
pg_hba:
- section: "DEFAULT"
entries:
- { type: local, database: all, user: all, auth_method: trust }
- { type: host, database: all, user: all, address: 127.0.0.1/32, auth_method: trust }
- { type: host, database: all, user: all, address: 174.34.2.0/24, auth_method: md5, comment: "Private Wifi" }
- section: "DBA"
entries:
- { type: host, database: all, user: all, address: 192.168.2.130/32, auth_method: md5, comment: "Name" }
- { type: host, database: all, user: all, address: 174.34.2.156/32, auth_method: md5, comment: "Name" }
并且Jinja2模板中的输出处理格式约为。像这样:
# TYPE DATABASE USER CIDR-ADDRESS METHOD #
######
# DEFAULT
######
{% for client in pg_hba %}
{{ '{:10}'.format(client.type) }} {{ '{:15}'.format(client.database) }} {{ '{:20}'.format(client.user) }} {{ '{:20}'.format(client.address|default('')) }} {{ '{:10}'.format(client.auth_method) }} {% if client.comment is defined %} # {{ client.comment|default("") }}
{% endif %}
{% endfor %}
{% if replication_group is defined %}
# REPLICATION
##########
{% for item in groups[ replication_group ] %}
{{ '{:10}'.format("host") }} {{ '{:15}'.format("replication") }} {{ '{:20}'.format("postgres") }} {{ '{:20}'.format(hostvars[item].ansible_default_ipv4.address+"/32") }} {{ '{:10}'.format("trust") }}
{% endfor %}
{% endif %}
输出,呈现预期的示例:
# DEFAULT
######
local all all trust
host all all 127.0.0.1/32 trust
host all all 174.34.2.0/24 md5 # Private WiFi
# REPLICATION
#########
host replication postgres 174.34.2.14/32 trust
问题是,没有多个节和多个条目列表的示例工作得很好,就像我们在pg_hba下只留下一个带有3个条目项的列表,没有子目录并通过Jinja2处理它一样,但是当我尝试应用类似逻辑来做时嵌套循环(至少在我看来是这样),并尝试遍历每个部分,然后遍历内部的条目,我无法弄清楚。
下面的模板迭代嵌套循环
{% for item in pg_hba %}
{% if item.section == 'DEFAULT' %}
#########
# DEFAULT
#########
{% for client in item.entries %}
{{ '{:10}'.format(client.type) }} {{ '{:15}'.format(client.database) }} {{ '{:20}'.format(client.user) }} {{ '{:20}'.format(client.address|default('')) }} {{ '{:10}'.format(client.auth_method) }} {% if client.comment is defined %} # {{ client.comment|default("") }}{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% for item in pg_hba %}
{% if item.section == 'DBA' %}
#####
# DBA
#####
{% for client in item.entries %}
{{ '{:10}'.format(client.type) }} {{ '{:15}'.format(client.database) }} {{ '{:20}'.format(client.user) }} {{ '{:20}'.format(client.address|default('')) }} {{ '{:10}'.format(client.auth_method) }} {% if client.comment is defined %} # {{ client.comment|default("") }}{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
给
#########
# DEFAULT
#########
local all all trust
host all all 127.0.0.1/32 trust
host all all 174.34.2.0/24 md5 # Private Wifi
#####
# DBA
#####
host all all 192.168.2.130/32 md5 # Name
host all all 174.34.2.156/32 md5 # Name
这是你要找的吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句