简体   繁体   English

Ansible:with_dict访问从json文件创建的字典的特定键

[英]Ansible: with_dict to access particular key for the dictionary created from json file

I am fairly new to ansible, and trying to explore the dictionary plug options. 我对ansible相当陌生,并尝试探索字典插件选项。 below is my playbook, I am trying to convert a json file to dictionary using the from_json module and then i am want to print particular keys only. 下面是我的剧本,我试图使用from_json模块将json文件转换为字典,然后我只想打印特定的键。 Not able to achieve the 2nd part. 无法实现第二部分。

here's the code: 这是代码:

hosts: localhost
vars:
  jsonVar: "{{ lookup('file', 'ConfigData.json') | from_json }}"

tasks:
  - name: print numbers
    debug: msg=" {{ jsonVar.cpsSiteName }}"
    debug: msg=" {{ jsonVar.dmsDataCacheAddress }}"
    debug: msg=" {{ jsonVar.htsHttpClientIdleConnectionTimeout }}"
    debug: msg=" {{ jsonVar.palConsulServerList }}"
    debug: msg=" {{ jsonVar.prsMaxIncoReqProcTime }}"
    debug: msg=" {{ jsonVar.prsMaxNumberOfExecutedScriptInstructions }}"
    debug: msg=" {{ jsonVar.prsmschapv2Password }}"

the output only displays the last debug statement. 输出仅显示最后的调试语句。 Eager to know if there is smarter way to access particular variable from the converted dictionary and then print it at the output. 渴望知道是否有更聪明的方法来访问转换后的词典中的特定变量,然后将其打印在输出中。

I tried using with_items, but doesn't work. 我尝试使用with_items,但不起作用。 Thanks for the help in advance. 我在这里先向您的帮助表示感谢。

Below is a sample json file: 以下是一个示例json文件:

    root@BVSETL04:/etc/ansible# less ConfigData.json 
    {
      "appSupCommonPullSendProxyAuthInfo":0,
      "appSupCommonPullSendWebAuthInfo":0,
      "appSupDdcSupervisionEnabled":1,
      "appSupDdcSupervisionInterval":15,
      "appSupDdcSupervisionMaxNoOfFailures":4,
      "appSupDNS_number_consequtive_failures":5,
      "appSupDNS_supervision_interval":60,
    }

Your playbook syntax is incorrect – there is only one task defined (each task should start as a new list item (dash symbol)). 您的剧本语法不正确–仅定义了一个任务(每个任务应从一个新的列表项(破折号)开始)。

Not sure what your problem is, but to print all vars with different tasks you can use: 不确定您的问题是什么,但是要打印具有不同任务的所有变量,可以使用:

- hosts: localhost
  vars:
    jsonVar: "{{ lookup('file', 'ConfigData.json') | from_json }}"
  tasks:
    - debug: msg=" {{ jsonVar.cpsSiteName }}"
    - debug: msg=" {{ jsonVar.dmsDataCacheAddress }}"
    - debug: msg=" {{ jsonVar.htsHttpClientIdleConnectionTimeout }}"
    # etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM