Ansible可以通过modules中的json_query或json_file两个模块来解析JSON数据。
- name: Parsing JSON with json_query
hosts: localhost
tasks:
- name: Parse JSON using json_query
debug:
var: "{{ my_json | json_query(query) }}"
vars:
my_json: {
"people": [{
"name": "Alice",
"age": 30
}, {
"name": "Bob",
"age": 40
}],
"info": {
"version": "1.0.0",
"author": "John"
}
}
query: "people[?age > `35`].name"
解释:
首先定义了一个my_json变量,包含了一个人员列表和更多信息。然后定义了一个query变量,用于查询people列表中年龄大于35岁的人的姓名。最后使用debug模块输出结果。
输出:
结果为Bob,因为他年龄大于35岁。
- name: Parsing JSON with json_file
hosts: localhost
tasks:
- name: Parse JSON file
debug:
var: "{{ my_jsonfile | json_query(query) }}"
vars:
my_jsonfile: "/path/to/my/file.json"
query: "people[?age > `35`].name"
解释:
指定一个JSON文件的路径,并使用json_query查询people列表中年龄大于35岁的人的姓名。使用debug模块输出结果。
输出:
与json_query模块输出相同,结果为Bob。
需要注意的是,对于复杂的JSON对象,查询可能会变得很复杂。学习如何使用json_query函数使得查询变得更简单也是很重要的。