如何在Ansible中循环解析JSON响应并筛选指定数据
Ansible Playbook:关联多接口数据并格式化输出
需求说明
已通过uri模块获取app_set端点列表,再循环请求每个端点的详情并注册结果。需要将两次任务的数据关联,按指定格式输出每个端点的AppSetName、StatefulAppSetName及Apps字段。
修正后的Playbook代码
--- - name: Collect and format app set data hosts: localhost gather_facts: no tasks: - name: Collect all app_set base data uri: url: "https://applicationserver.com/api/app_set" method: GET return_content: yes validate_certs: no body_format: json register: app_sets_raw # 保存完整的app_set条目,保留name和labels信息 - name: Store full app_set list set_fact: app_sets: "{{ app_sets_raw.json }}" # 循环请求每个app_set的详情,同时保留原app_set的上下文 - name: Get detailed data for each app_set uri: url: "https://applicationserver.com/api/app_set/{{ item.name }}" method: GET return_content: yes validate_certs: no body_format: json register: app_set_details loop: "{{ app_sets }}" loop_control: label: "{{ item.name }}" # 让循环输出更简洁,只显示name # 合并两次任务的数据,生成结构化列表 - name: Combine base and detailed data set_fact: formatted_app_sets: > {%- set combined = [] -%} {%- for idx in range(app_sets|length) -%} {%- set base = app_sets[idx] -%} {%- set detail = app_set_details.results[idx].json -%} {%- set app_item = { 'index': idx + 1, 'app_set_name': base.name, 'stateful_app_set_name': base.labels.AttachedToStatefulAppSet | default('N/A'), 'apps': detail.pods | map(attribute='app') | list } -%} {%- do combined.append(app_item) -%} {%- endfor -%} {{ combined }} # 按指定格式输出结果 - name: Print formatted output debug: msg: | app_sets {% for item in formatted_app_sets %} Index {{ item.index }} AppSetName: {{ item.app_set_name }} StatefulAppSetName: {{ item.stateful_app_set_name }} Apps: {{ item.apps | join(', ') }} {% endfor %}
关键说明
- 保留完整基础数据:不再只提取
name,而是保存整个app_set的JSON数据,直接获取labels中的AttachedToStatefulAppSet字段。 - 循环关联数据:通过循环索引
idx将基础数据列表app_sets和详情结果列表app_set_details.results一一对应,确保每个app_set的基础信息和详情数据匹配。 - 结构化合并:用Jinja2模板将需要的字段组合成统一的字典列表,方便后续格式化输出。
- 格式化输出:使用
debug模块的多行字符串语法,按照要求的格式打印结果。
示例输出
app_sets Index 1 AppSetName: app-set-01 StatefulAppSetName: stateful-app-set-01 Apps: app-01-pod-1, app-01-pod-2 Index 2 AppSetName: app-set-02 StatefulAppSetName: stateful-app-set-02 Apps: app-02-pod-1, app-02-pod-2
内容的提问来源于stack exchange,提问作者goffo
相关产品推荐
相关产品推荐

