trial999 trial999 - 8 months ago 80
JSON Question

Json parsing in Ansible

I have to parse the output of the following command:

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

which gives output as follows:

"hosts" : [
"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:

- 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.

Answer Source

There are quite a bit of helpful filters in Ansible.

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