在Ansible中,query模块可以用于从JSON、YAML或ini文件中查询特定的值。如果需要在查询时使用循环来处理查询结果,可以使用循环控制结构。
以下是一个示例,演示了如何使用循环在query模块中处理结果:
name: Query the JSON file for specific values query: data: "servers": [ { "name": "web-server-1", "ip": "10.0.0.1", "status": "running" }, { "name": "web-server-2", "ip": "10.0.0.2", "status": "stopped" }, { "name": "web-server-3", "ip": "10.0.0.3", "status": "running" } ] query: "[? status == 'running']" register: running_servers
name: Print the names of the running servers debug: msg: "Server name: {{ item.name }}" with_items: "{{ running_servers.results[0].query_result }}"
在上面的示例中,我们查询了JSON文件中"status"为"running"的服务器。然后,我们使用循环遍历查询结果,并输出每个运行中服务器的名称。
需要注意的是,循环结构可以在任何Ansible模块中使用,而不仅仅是在query模块中。