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.
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.
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.
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.
Network CLI filters The parse_cli filter will load the spec file and pass the command output through it, returning JSON output.
There are quite a bit of helpful filters in Ansible.
Try: when: (output_text.stdout | from_json).ismaster
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With