Json parsing in Ansible
58,335
There are quite a bit of helpful filters in Ansible.
Try: when: (output_text.stdout | from_json).ismaster
Related videos on Youtube
Author by
trial999
Updated on July 09, 2022Comments
-
trial999 almost 2 years
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.
-
trial999 over 7 yearsGetting this error when i try to do this: "The conditional check '(output_text.stdout | from_json).ismaster' failed. The error was: No JSON object could be decoded\n\nThe error appears to have been in 'xxxx': line xx, column x, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: Run command on master\n ^ here\n"}
-
Konstantin Suvorov over 7 yearsOuch... you have not pure JSON stuff like
ObjectId()
andISODate()
. Not sure there is an easy fix for this. -
trial999 over 7 yearsHave used a this command instead which outputs a "true". mongo <dbname> --eval "db.isMaster().ismaster". Thanks for guiding.
-
Pier almost 4 yearsMy 2 cents: Usually, at least from my point of view, using the shell module means you are not doing it right...