json - ansible, jinja2, json - 在 Jinja 中使用 json_query?
问题描述
开发者社区您好!
我目前正在开发一些 Ansible 剧本来管理 Citrix NetScaler 配置,并希望获得以下方面的帮助。我在变量文件中定义了以下数据结构:
nsadc_config_file_textfsm_nsapp_lb_service_parsed
{
"bind_lbvserver_NotParsed": "",
"bind_lbvserver_analyticsprofile": "",
"bind_lbvserver_gotopriorityexpression": "",
"bind_lbvserver_name": "VSRV-CS-Client1",
"bind_lbvserver_policyname": "",
"bind_lbvserver_priority": "",
"bind_lbvserver_service_group_name": "SVC_Client1_App1_Server1_Port1",
"bind_lbvserver_type": "",
"bind_lbvserver_weight": ""
},
{
"bind_lbvserver_NotParsed": "",
"bind_lbvserver_analyticsprofile": "",
"bind_lbvserver_gotopriorityexpression": "NEXT",
"bind_lbvserver_name": "VSRV_Client2_App2",
"bind_lbvserver_policyname": "policy_Client2_Rewrite",
"bind_lbvserver_priority": "80",
"bind_lbvserver_service_group_name": "",
"bind_lbvserver_type": "REQUEST",
"bind_lbvserver_weight": ""
},
我想在 Jinja 文件中查询这个 JSON 结构,尝试了以下方法,但不幸的是它不起作用。我不是 100% 确定是否可以在 Jinja 文件中使用“json_query”。
servicebindings:
{% for item_1 in nsadc_config_file_textfsm_nsapp_lb_vserver_binding_parsed %}
{% if (item_0.add_lbvserver_name == item_1.bind_lbvserver_name) and (item_1.bind_lbvserver_service_group_name in nsadc_config_file_textfsm_nsapp_lb_service_parsed) %}
- servicename: "{{ item_1.bind_lbvserver_service_group_name }}"
{% if item_1.bind_lbvserver_weight is defined and item_1.bind_lbvserver_weight %}
weight: "{{ item_1.bind_lbvserver_weight }}"
{% endif %}
{% endif %}
{% endfor %}
除了使用(item_1.bind_lbvserver_service_group_name in nsadc_config_file_textfsm_nsapp_lb_service_parsed)
上面的方法,我还尝试直接在 Jinja 中包含一个 json_query 语句,但没有运气。恐怕,使用引号和转义字符可能会出现问题。
{% if (item_0.add_lbvserver_name == item_1.bind_lbvserver_name) and (nsadc_config_file_textfsm_nsapp_lb_service_parsed | json_query(\"[?add_svc_name == '\" + item_1.bind_lbvserver_service_group_name + \"']\")) %}
有人可以建议是否可以直接在 Jinja 中查询 JSON 结构?
提前谢谢了!
解决方案
json_query
是一个 Jinja 过滤器,所以你当然可以在模板中使用它……或者任何 Jinja 表达式有效的地方。
例如,如果我在这样的剧本(和模板任务)中有数据:
- hosts: localhost
gather_facts: false
vars:
var1:
- name: thing1
color: red
- name: thing2
color: blue
var2:
- name: bob
likes: blue
- name: alice
likes: green
tasks:
- template:
src: template.in
dest: output.txt
我可以编写一个如下所示的模板:
{% for person in var2 %}
{% for thing in var1|json_query('[?color == `{}`]'.format(person.likes)) %}
- {{ person.name }} likes {{ thing.name }}
{% endfor %}
{% endfor %}
这将产生以下输出output.txt
:
- bob likes thing2
json_query
请注意关于模板中表达式的两件事:
- 因为我们正在寻找一个文字字符串,所以我们需要使用反引号来引用该值。
- 我们使用 Python 字符串格式将目标值包含在查询字符串中。
代替字符串格式化语法,我们可以写成:
json_query('[?color == `' + person.likes + '`]')
推荐阅读
- symfony - Nginx Location 块到 Symfony 路径
- python - 定义函数时对变量的评估
- python - 如何在 python 3 中为 datetime.time 对象添加额外的秒数?
- python - Python:在所有实例中复制的类变量占用内存
- apache-flink - Flink Gelly 内存耗尽
- php - 在 bash 脚本中包含 PHP 命令执行并退出
- linear-programming - 在 GLPK 中对分段函数进行建模
- hazelcast - Hazelcast 通过侦探追踪
- neural-network - 如何在 Torch 中修改 nn.MSECriterion.lua 等内置函数
- c# - 忽略集合成员 AutoMapper C# 的属性