ansible 如何从嵌套的 json 中获取多个值,例如 output

如何解决ansible 如何从嵌套的 json 中获取多个值,例如 output

我期待着一种从嵌套变量(具有字典和列表值)中列出值的方法,即 registerresponse_find 并且我主要采用 json 格式和大多数json 中的值嵌套在 [] 列表中,如构造。

如果我像下面那样从中获取单个值,它会以某种方式工作:

var=response_find['json']['results'][0]['content_facet_attributes']

var=response_find['json']['results'][0]['certname']

但是当我在下面做的时候没有用:

var=response_find['json']['results'][0]['content_view_id']

以下是我期待从这个嵌套输出中获取的几个值:

"architecture_name": "x86_64","name": "satcap.rest.example.com","url": "https://satcap.rest.example.com:9090"
"content_source_name": "satcap.rest.example.com","name": "ccv-azure-infra-rhel7"
"name": "Prod"
"id": 33485,"ip": "192.168.88.88","name": "invwharn108.test.exampl.com","registered_through": "satcap.rest.example.com"

嵌套的 Json 输出:

{
    "response_find": {
        "apipie_checksum": "7533ab625c45a3819647f4fb4c9394c2832c0180","cookies": {
            "_session_id": "25872833d9e2723073797fbd8cfa2d63"
        },"cookies_string": "_session_id=25872833d9e2723073797fbd8cfa2d63","foreman_version": "1.24.1.21","json": {
            "page": 1,"per_page": 20,"results": [
                {
                    "architecture_id": 1,"architecture_name": "x86_64","build": false,"capabilities": [
                        "build"
                    ],"certname": "invwharn108.test.exampl.com","comment": null,"content_facet_attributes": {
                        "applicable_module_stream_count": 0,"applicable_package_count": 0,"content_source": {
                            "id": 17,"url": "https://satcap.rest.example.com:9090"
                        },"content_source_id": 17,"content_source_name": "satcap.rest.example.com","content_view": {
                            "id": 67,"name": "ccv-azure-infra-rhel7"
                        },"content_view_id": 67,"content_view_name": "ccv-azure-infra-rhel7","errata_counts": {
                            "bugfix": 0,"enhancement": 0,"security": 0,"total": 0
                        },"id": 32255,"kickstart_repository": {
                            "id": 5772,"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
                        },"kickstart_repository_id": 5772,"kickstart_repository_name": "5772","lifecycle_environment": {
                            "id": 5,"name": "Prod"
                        },"lifecycle_environment_id": 5,"lifecycle_environment_name": "Prod","upgradable_module_stream_count": 0,"upgradable_package_count": 0,"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
                    },"created_at": "2020-12-23 13:19:35 UTC","disk": null,"domain_id": 25,"domain_name": "test.example-aws.example.com","enabled": true,"environment_id": null,"environment_name": null,"errata_status": 1,"errata_status_label": "Could not calculate errata status,ensure host is registered and the katello-host-tools package is installed","global_status": 1,"global_status_label": "Warning","hostgroup_id": 982,"hostgroup_name": "infra","hostgroup_title": "NXDI-hg-aws/west-europe/infra","id": 33485,"image_file": "","image_id": null,"image_name": null,"installed_at": null,"ip6": null,"last_compile": "2020-12-23 13:19:38 UTC","last_report": null,"location_id": 37,"location_name": "west-europe","mac": "02:78:43:60:ee:fb","managed": false,"medium_id": null,"medium_name": null,"model_id": 25,"model_name": "HVM domU","openscap_proxy": null,"openscap_proxy_id": null,"openscap_proxy_name": null,"operatingsystem_id": 21,"operatingsystem_name": "RedHat 7.8","organization_id": 3,"pxe_loader": "PXELinux BIOS","subnet_id": 65,"subnet_name": "aws-west-europe-infra","subscription_facet_attributes": {
                        "autoheal": true,"hypervisor": false,"id": 33593,"last_checkin": "2020-12-23 13:19:42 UTC","purpose_addons": [],"purpose_role": "","purpose_usage": "","registered_at": "2020-12-23 13:19:35 UTC","registered_through": "satcap.rest.example.com",},"subscription_global_status": 1,"subscription_status": 1,"subscription_status_label": "Partially entitled",}
            ],"search": "name=invwharn108.test.exampl.com","sort": {
                "by": null,"order": null
            },"subtotal": 1,"total": 13121
        },"msg": "OK (unknown bytes)","x_request_id": "e02dd9b3-b2f8-4c39-8bf5-1ce1897d9548",}
}

我的游戏:

---
- hosts: localhost
  tasks:
    - include_vars: vaults/aws_secrets.yml
      no_log: true
    - include_vars: requirements.yml
      no_log: true

    - name: Find the ID of Cloud VM in Satellite
      uri:
        url: "https://{{ satserver }}/api/v2/hosts?search=name={{ aws_instance_name }}"
        method: GET
        user: "{{ aws_satuser }}"
        password: "{{ aws_satpw }}"
        force_basic_auth: yes
        validate_certs: no
      register: response_find
      delegate_to: localhost
      changed_when: false
    - debug:
        var=response_find['json']['results'][0]['content_facet_attributes']
        #var=response_find.json.results.0.organization_name
        #var=response_find['json']['results'][0]['certname']

结果:

"content_facet_attributes": {
    "applicable_module_stream_count": 0,"content_source": {
            "id": 17,"url": "https://satcap.rest.example.com:9090"
        },"content_view": {
            "id": 67,"name": "ccv-azure-infra-rhel7"
        },"errata_counts": {
            "bugfix": 0,"total": 0
        },"kickstart_repository": {
            "id": 5772,"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
        },"lifecycle_environment": {
            "id": 5,"name": "Prod"
        },"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
    },

解决方法

如果您想从列出的数据中提取字典,您可以使用过滤器 json_query,它使用 JMESPath 来解析和处理 JSON。

为了提取一个看起来像这样的字典:

{
    "architecture_name": "x86_64","content_source_name": "satcap.rest.example.com","content_source_url": "https://satcap.rest.example.com:9090","content_view_name": "ccv-azure-infra-rhel7","egistered_through": "satcap.rest.example.com","id": 33485,"ip": "192.168.88.88","lifecycle_environment_name": "Prod","name": "invwharn108.test.exampl.com"
}

您可以使用 JMESPath 到 filter multiselect hashes

这是一个 JMESPath 查询,它会给出这个结果:

json.results[*].{
    "architecture_name": architecture_name,"content_source_name": content_facet_attributes.content_source.name,"content_source_url": content_facet_attributes.content_source.url,"content_view_name": content_facet_attributes.content_view.name,"lifecycle_environment_name": content_facet_attributes.lifecycle_environment.name,"id": id,"ip": ip,"name": name,"egistered_through": subscription_facet_attributes.registered_through 
}

这是一个使用它的示例剧本:

- hosts: localhost
  gather_facts: no

  tasks:  
    - debug:
        msg: >-
          {{
            (
              response_find | json_query('
                json.results[*].{
                  "architecture_name": architecture_name,"egistered_through": subscription_facet_attributes.registered_through 
                }
              ')
            ).0
          }}
      vars:
        {
          "response_find": {
            "apipie_checksum": "7533ab625c45a3819647f4fb4c9394c2832c0180","cookies": {
              "_session_id": "25872833d9e2723073797fbd8cfa2d63"
            },"cookies_string": "_session_id=25872833d9e2723073797fbd8cfa2d63","foreman_version": "1.24.1.21","json": {
              "page": 1,"per_page": 20,"results": [{
                "architecture_id": 1,"architecture_name": "x86_64","build": false,"capabilities": [
                  "build"
                ],"certname": "invwharn108.test.exampl.com","comment": null,"content_facet_attributes": {
                  "applicable_module_stream_count": 0,"applicable_package_count": 0,"content_source": {
                    "id": 17,"name": "satcap.rest.example.com","url": "https://satcap.rest.example.com:9090"
                  },"content_source_id": 17,"content_view": {
                    "id": 67,"name": "ccv-azure-infra-rhel7"
                  },"content_view_id": 67,"errata_counts": {
                    "bugfix": 0,"enhancement": 0,"security": 0,"total": 0
                  },"id": 32255,"kickstart_repository": {
                    "id": 5772,"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
                  },"kickstart_repository_id": 5772,"kickstart_repository_name": "5772","lifecycle_environment": {
                    "id": 5,"name": "Prod"
                  },"lifecycle_environment_id": 5,"upgradable_module_stream_count": 0,"upgradable_package_count": 0,"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
                },"created_at": "2020-12-23 13:19:35 UTC","disk": null,"domain_id": 25,"domain_name": "test.example-aws.example.com","enabled": true,"environment_id": null,"environment_name": null,"errata_status": 1,"errata_status_label": "Could not calculate errata status,ensure host is registered and the katello-host-tools package is installed","global_status": 1,"global_status_label": "Warning","hostgroup_id": 982,"hostgroup_name": "infra","hostgroup_title": "NXDI-hg-aws/west-europe/infra","image_file": "","image_id": null,"image_name": null,"installed_at": null,"ip6": null,"last_compile": "2020-12-23 13:19:38 UTC","last_report": null,"location_id": 37,"location_name": "west-europe","mac": "02:78:43:60:ee:fb","managed": false,"medium_id": null,"medium_name": null,"model_id": 25,"model_name": "HVM domU","name": "invwharn108.test.exampl.com","openscap_proxy": null,"openscap_proxy_id": null,"openscap_proxy_name": null,"operatingsystem_id": 21,"operatingsystem_name": "RedHat 7.8","organization_id": 3,"pxe_loader": "PXELinux BIOS","subnet_id": 65,"subnet_name": "aws-west-europe-infra","subscription_facet_attributes": {
                  "autoheal": true,"hypervisor": false,"id": 33593,"last_checkin": "2020-12-23 13:19:42 UTC","purpose_addons": [],"purpose_role": "","purpose_usage": "","registered_at": "2020-12-23 13:19:35 UTC","registered_through": "satcap.rest.example.com"
                },"subscription_global_status": 1,"subscription_status": 1,"subscription_status_label": "Partially entitled"
              }],"search": "name=invwharn108.test.exampl.com","sort": {
                "by": null,"order": null
              },"subtotal": 1,"total": 13121
            },"msg": "OK (unknown bytes)","x_request_id": "e02dd9b3-b2f8-4c39-8bf5-1ce1897d9548"
          }
        }

回顾一下:

PLAY [localhost] *************************************************************************************************

TASK [debug] *****************************************************************************************************
ok: [localhost] => {
    "msg": {
        "architecture_name": "x86_64","name": "invwharn108.test.exampl.com"
    }
}

PLAY RECAP *******************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res