mongodb_rs_status 3.91 KB
Newer Older
1 2 3 4
#!/usr/bin/env python

DOCUMENTATION = """
---
5 6
module: mongodb_rs_status
short_description: Get the status of a replica set of a mongo cluster.
7
description:
8
  - Get the status of the replica set of a mongo cluster. Provide the same info as rs.status() or replSetGetStatus.
9 10 11
    Returns a status dictionary key containing the replica set JSON document from Mongo, or no status key if there
    was no status found.  This usually indicates that either Mongo was configured to run without replica sets or
    that the replica set has not been initiated yet.
12
version_added: "1.9"
13 14 15
author:
  - Feanil Patel
  - Kevin Falcone
16 17 18
options:
  host:
    description:
19
      - The hostname or ip of a server in the mongo cluster.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
    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
35 36 37 38
  auth_database:
    description:
      - The database to authenticate against.
    required: false
39 40 41 42
"""

EXAMPLES = '''
- name: Get status for the stage cluster
43
  mongodb_rs_status:
44 45 46 47
    host: localhost:27017
    username: root
    password: password
  register: mongo_status
48 49 50 51 52 53 54 55

Note that you're testing for the presence of the status member of the dictionary not the contents of it

- debug: msg="I don't have a replica set available"
  when: mongo_status.status is not defined

- debug: var=mongo_status.status

56 57 58 59 60 61
'''
# Magic import
from ansible.module_utils.basic import *

try:
    from pymongo import MongoClient
62
    from pymongo.errors import OperationFailure
63 64 65 66 67 68 69
    from bson import json_util
except ImportError:
    pymongo_found = False
else:
    pymongo_found = True

import json
70
from urllib import quote_plus
71 72 73 74 75 76 77 78

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'),
79
        auth_database=dict(required=False, type='str')
80 81 82 83 84 85 86 87 88 89 90 91
    )

    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')
92
    auth_database = module.params.get('auth_database')
93 94 95 96 97

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

    if username:
98
        mongo_uri += "{}:{}@".format(*map(quote_plus, [username,password]))
99

100 101 102 103
    mongo_uri += "{}:{}".format(quote_plus(host),port)

    if auth_database:
        mongo_uri += '/{}'.format(quote_plus(auth_database))
104 105

    client = MongoClient(mongo_uri)
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

    # This checks to see if you have a replSetName configured
    # This generally means that /etc/mongod.conf has been changed
    # from the default to use a replica set and mongo has been
    # restarted to use it.

    try:
        repl_set = client.admin.command('getCmdLineOpts')['parsed']['replication']['replSetName']
    except (OperationFailure, KeyError):
        module.exit_json(changed=False)

    # If mongo was started with a repl_set, it is safe to run replSetGetStatus
    if repl_set:
        status = client.admin.command("replSetGetStatus")
    else:
        module.exit_json(changed=False)
122 123 124 125 126

    # 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))
127

128 129 130 131
    module.exit_json(changed=False, status=clean)

if __name__ == '__main__':
    main()