Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json parsing in Ansible

Tags:

I have to parse the output of the following command:

mongo <dbname> --eval "db.isMaster()" 

which gives output as follows:

 {     "hosts" : [         "xxx:<port>",         "xxx:<port>",         "xxx:<port>"     ],     "setName" : "xxx",     "setVersion" : xxx,     "ismaster" : true,     "secondary" : false,     "primary" : "xxx",     "me" : "xxx",     "electionId" : ObjectId("xxxx"),     "maxBsonObjectSize" : xxx,     "maxMessageSizeBytes" : xxxx,     "maxWriteBatchSize" : xxx,     "localTime" : ISODate("xxx"),     "maxWireVersion" : 4,     "minWireVersion" : 0,     "ok" : 1 } 

I need to parse the above output to check the value of "ismaster" is true. Please let me know how i can do this in ansible.

At the moment i am simply checking that the text "ismaster" : true is shown in the output using the following code:

  tasks:      - name: Check if the mongo node is primary        shell: mongo <dbname> --eval "db.isMaster()"        register: output_text       - name: Run command on master        shell: <command to execute>        when: "'\"ismaster\\\" : true,' in output_text.stdout" 

However it would be nice to use Ansible's json processing to check the same. Please advise.

like image 219
trial999 Avatar asked Nov 28 '16 12:11

trial999


People also ask

Can Ansible read JSON?

The data for these models is exchanged as key/value pairs and encoded using different formats. JSON, which is widely used in Ansible, is one of them.

Can Ansible use JSON format?

By default, an Ansible inventory file uses the INI configuration format. You can also use JSON (JavaScript Object Notation) configuration format for Ansible inventory files as well.

What is JSON query Ansible?

The json_query filter lets you query a complex JSON structure and iterate over it using a loop structure. Note. You must manually install the jmespath dependency on the Ansible controller before using this filter. This filter is built upon jmespath, and you can use the same syntax. For examples, see jmespath examples.

Which filter can be used to output Network Device CLI command into a structured JSON output?

Network CLI filters The parse_cli filter will load the spec file and pass the command output through it, returning JSON output.


1 Answers

There are quite a bit of helpful filters in Ansible.

Try: when: (output_text.stdout | from_json).ismaster

like image 91
Konstantin Suvorov Avatar answered Sep 19 '22 12:09

Konstantin Suvorov