json - 在ansible中提取json对象值

标签 json ansible

我想从 Ansible 中的以下 json 对象中提取一个值:

"msg": {
       "NatGateway": {
           "CreateTime": "2016-10-03T17:46:07.548Z",
           "NatGatewayAddresses": [
               {
                   "AllocationId": "eipalloc-a22b9bc5"
               }
           ],
           "NatGatewayId": "nat-0d3b5a556c8a1c261",
           "State": "pending",
           "SubnetId": "subnet-5d353039",
           "VpcId": "vpc-eee3fe8a"
       }
   }
}

从上面的 json 中,我只想提取值“0d3b5a556c8a1c261”。我怎么做?我尝试使用正则表达式,但到目前为止运气不好。

最佳答案

如果这个 json 对象是从一个模块返回给你的,那么你可以使用“register”。有一个使用设置模块的例子:

- hosts: myhost
  gather_facts: false  # turn off automatic setup invocation for this example
  tasks:
    - name: my setup
      setup:
      register: myvar  # register setup module json output to variable

    - name: getting inside json structure for a string
      debug: msg="{{ myvar.ansible_facts.ansible_kernel }}"

    - name: using substring replacement
      debug: msg="{{ myvar.ansible_facts.ansible_kernel|replace('3.13.0-', '') }}"

    - name: using string slicing
      debug: msg="{{ myvar.ansible_facts.ansible_kernel[7:] }}"

输出将是:

[admin@agromov test]$ ansible-playbook book.yml 

PLAY [myhost] ******************************************************************

TASK [my setup] ****************************************************************
ok: [myhost]

TASK [getting inside json structure for a string] ******************************
ok: [myhost] => {
    "msg": "3.13.0-96-generic"
}

TASK [using substring replacement] *********************************************
ok: [myhost] => {
    "msg": "96-generic"
}

TASK [using string slicing] ****************************************************
ok: [myhost] => {
    "msg": "96-generic"
}

PLAY RECAP *********************************************************************
myhost                     : ok=4    changed=0    unreachable=0    failed=0   

关于json - 在ansible中提取json对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39844374/

相关文章:

python - 在ansible中运行python函数

javascript - Sheetjs - Sheet 添加 Json 忽略日期格式

java - 应为 BEGIN_ARRAY,但在第 1 行第 1 列处为 STRING : getting JSON from PHP to Java with Gson

javascript - 如何在 MarkLogic 中的 JSON 文档中插入行 [更新]

javascript - JSON 中的多行元素?

ansible - Ansible如何循环执行一系列任务?

linux - ansible 重启 2.1.1.0 失败

使用 include_vars 的 Ansible Vault 和加密变量

linux - 使用 Ansible 永久设置环境变量

json - Spring MVC : jackson-mapper-asl not work with Spring 4