mongo_status 2.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#!/usr/bin/env python

DOCUMENTATION = """
---
module: mongo_status
short_description: Get the status of a mongo cluster.
description:
  - Get the status of a mongo cluster. Provide the same info as rs.status()
version_added: "1.9"
author: Feanil Patel
options:
  host:
    description:
14
      - The hostname or ip of a server in the mongo cluster.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    required: false
    default: 'localhost'
  port:
    description:
      - The port to connect to mongo on.
    required: false
    default: 27017
  username:
    description:
      - The username of the mongo user to connect as.
    required: false
  password:
    description:
      - The password to use when authenticating.
    required: false
"""

EXAMPLES = '''
- name: Get status for the stage cluster
  mongo_status:
    host: localhost:27017
    username: root
    password: password
  register: mongo_status
'''
# Magic import
from ansible.module_utils.basic import *

try:
    from pymongo import MongoClient
    from bson import json_util
except ImportError:
    pymongo_found = False
else:
    pymongo_found = True

import json

def main():

    arg_spec = dict(
        host=dict(required=False, type='str', default="localhost"),
        port=dict(required=False, type='int', default=27017),
        username=dict(required=False, type='str'),
        password=dict(required=False, type='str'),
    )

    module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=False)

    if not pymongo_found:
        module.fail_json(msg="The python pymongo module is not installed.")

    mongo_uri = 'mongodb://'
    host = module.params.get('host')
    port = module.params.get('port')
    username = module.params.get('username')
    password = module.params.get('password')

    if (username and not password) or (password and not username):
        module.fail_json(msg="Must provide both username and password or neither.")

    if username:
        mongo_uri += "{}:{}@".format(username,password)

    mongo_uri += "{}:{}".format(host,port)

    client = MongoClient(mongo_uri)
    status = client.admin.command("replSetGetStatus")

    # This converts the bson into a python dictionary that ansible's standard
    # jsonify function can process and output without throwing errors on bson
    # types that don't exist in JSON
    clean = json.loads(json_util.dumps(status))
   
    module.exit_json(changed=False, status=clean)

if __name__ == '__main__':
    main()