You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible中从API返回的JSON数据提取所有certname值并过滤未授权主机

解决Ansible中获取所有certname及过滤特定状态主机的问题

1. 获取所有50条数据中的certname值

你之前的debug任务只取了results数组的第一个元素(索引[0]),要获取所有条目,只需要用Ansible的map过滤器提取每个元素的certname字段,再转成列表即可:

- debug:
    msg: "所有主机的certname: {{ data.json.results | map(attribute='certname') | list }}"

这个任务会把results里每一项的certname都提取出来,最终输出一个包含所有50个值的列表。


2. 过滤出subscription_status_label为Unentitled的主机certname

你之前的when条件写法有问题:Ansible的when语句不需要用{{}}包裹表达式,而且直接用selectattr的结果无法作为判断条件。正确的做法是先过滤出符合条件的主机,再提取它们的certname,可以一步完成:

- debug:
    msg: "未授权主机的certname: {{ data.json.results | selectattr('subscription_status_label', 'equalto', 'Unentitled') | map(attribute='certname') | list }}"

这里的关键是:

  • selectattr('subscription_status_label', 'equalto', 'Unentitled'):精确筛选出subscription_status_label等于Unentitled的主机条目
  • 接着用map(attribute='certname')提取这些条目的certname
  • 最后用list转成列表输出

如果你想单独处理过滤后的主机数据,也可以先把过滤结果注册成变量,再进行后续操作:

- name: 过滤未授权主机
  set_fact:
    unentitled_hosts: "{{ data.json.results | selectattr('subscription_status_label', 'equalto', 'Unentitled') | list }}"

- debug:
    msg: "未授权主机的certname列表: {{ unentitled_hosts | map(attribute='certname') | list }}"

整合后的完整Playbook示例

把这两个任务加到你的原有Playbook里,最终版本如下:

- hosts: xxxx
  tasks:
    - name: check subs
      uri:
        url: https://xxxxx/api/v2/hosts
        user: xxxx
        password: xxxx
        method: GET
        force_basic_auth: yes
        return_content: yes
        status_code: [200]
        body_format: json
      register: data
      ignore_errors: true

    - name: 获取所有主机的certname
      debug:
        msg: "所有主机certname: {{ data.json.results | map(attribute='certname') | list }}"
      ignore_errors: true

    - name: 获取未授权主机的certname
      debug:
        msg: "未授权主机certname: {{ data.json.results | selectattr('subscription_status_label', 'equalto', 'Unentitled') | map(attribute='certname') | list }}"
      ignore_errors: true

这样就能同时获取所有certname,以及筛选出特定状态的主机certname了。

内容的提问来源于stack exchange,提问作者Amit Goud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 21:02:47