|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +# (c) 2012, Elliott Foster <[email protected]> |
| 4 | +# Sponsored by Four Kitchens http://fourkitchens.com. |
| 5 | +# (c) 2014, Epic Games, Inc. |
| 6 | +# |
| 7 | +# This file is part of Ansible |
| 8 | +# |
| 9 | +# Ansible is free software: you can redistribute it and/or modify |
| 10 | +# it under the terms of the GNU General Public License as published by |
| 11 | +# the Free Software Foundation, either version 3 of the License, or |
| 12 | +# (at your option) any later version. |
| 13 | +# |
| 14 | +# Ansible is distributed in the hope that it will be useful, |
| 15 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | +# GNU General Public License for more details. |
| 18 | +# |
| 19 | +# You should have received a copy of the GNU General Public License |
| 20 | +# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 21 | + |
| 22 | +DOCUMENTATION = ''' |
| 23 | +--- |
| 24 | +module: mongodb_user |
| 25 | +short_description: Adds or removes a user from a MongoDB database. |
| 26 | +description: |
| 27 | + - Adds or removes a user from a MongoDB database. |
| 28 | +version_added: "1.1" |
| 29 | +options: |
| 30 | + login_user: |
| 31 | + description: |
| 32 | + - The username used to authenticate with |
| 33 | + required: false |
| 34 | + default: null |
| 35 | + login_password: |
| 36 | + description: |
| 37 | + - The password used to authenticate with |
| 38 | + required: false |
| 39 | + default: null |
| 40 | + login_host: |
| 41 | + description: |
| 42 | + - The host running the database |
| 43 | + required: false |
| 44 | + default: localhost |
| 45 | + login_port: |
| 46 | + description: |
| 47 | + - The port to connect to |
| 48 | + required: false |
| 49 | + default: 27017 |
| 50 | + login_database: |
| 51 | + version_added: "2.0" |
| 52 | + description: |
| 53 | + - The database where login credentials are stored |
| 54 | + required: false |
| 55 | + default: null |
| 56 | + replica_set: |
| 57 | + version_added: "1.6" |
| 58 | + description: |
| 59 | + - Replica set to connect to (automatically connects to primary for writes) |
| 60 | + required: false |
| 61 | + default: null |
| 62 | + database: |
| 63 | + description: |
| 64 | + - The name of the database to add/remove the user from |
| 65 | + required: true |
| 66 | + name: |
| 67 | + description: |
| 68 | + - The name of the user to add or remove |
| 69 | + required: true |
| 70 | + default: null |
| 71 | + aliases: [ 'user' ] |
| 72 | + password: |
| 73 | + description: |
| 74 | + - The password to use for the user |
| 75 | + required: false |
| 76 | + default: null |
| 77 | + ssl: |
| 78 | + version_added: "1.8" |
| 79 | + description: |
| 80 | + - Whether to use an SSL connection when connecting to the database |
| 81 | + default: False |
| 82 | + roles: |
| 83 | + version_added: "1.3" |
| 84 | + description: |
| 85 | + - "The database user roles valid values are one or more of the following: read, 'readWrite', 'dbAdmin', 'userAdmin', 'clusterAdmin', 'readAnyDatabase', 'readWriteAnyDatabase', 'userAdminAnyDatabase', 'dbAdminAnyDatabase'" |
| 86 | + - This param requires mongodb 2.4+ and pymongo 2.5+ |
| 87 | + required: false |
| 88 | + default: "readWrite" |
| 89 | + state: |
| 90 | + state: |
| 91 | + description: |
| 92 | + - The database user state |
| 93 | + required: false |
| 94 | + default: present |
| 95 | + choices: [ "present", "absent" ] |
| 96 | + update_password: |
| 97 | + required: false |
| 98 | + default: always |
| 99 | + choices: ['always', 'on_create'] |
| 100 | + version_added: "2.1" |
| 101 | + description: |
| 102 | + - C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users. |
| 103 | +
|
| 104 | +notes: |
| 105 | + - Requires the pymongo Python package on the remote host, version 2.4.2+. This |
| 106 | + can be installed using pip or the OS package manager. @see http://api.mongodb.org/python/current/installation.html |
| 107 | +requirements: [ "pymongo" ] |
| 108 | +author: "Elliott Foster (@elliotttf)" |
| 109 | +''' |
| 110 | + |
| 111 | +EXAMPLES = ''' |
| 112 | +# Create 'burgers' database user with name 'bob' and password '12345'. |
| 113 | +- mongodb_user: database=burgers name=bob password=12345 state=present |
| 114 | +
|
| 115 | +# Create a database user via SSL (MongoDB must be compiled with the SSL option and configured properly) |
| 116 | +- mongodb_user: database=burgers name=bob password=12345 state=present ssl=True |
| 117 | +
|
| 118 | +# Delete 'burgers' database user with name 'bob'. |
| 119 | +- mongodb_user: database=burgers name=bob state=absent |
| 120 | +
|
| 121 | +# Define more users with various specific roles (if not defined, no roles is assigned, and the user will be added via pre mongo 2.2 style) |
| 122 | +- mongodb_user: database=burgers name=ben password=12345 roles='read' state=present |
| 123 | +- mongodb_user: database=burgers name=jim password=12345 roles='readWrite,dbAdmin,userAdmin' state=present |
| 124 | +- mongodb_user: database=burgers name=joe password=12345 roles='readWriteAnyDatabase' state=present |
| 125 | +
|
| 126 | +# add a user to database in a replica set, the primary server is automatically discovered and written to |
| 127 | +- mongodb_user: database=burgers name=bob replica_set=blecher password=12345 roles='readWriteAnyDatabase' state=present |
| 128 | +''' |
| 129 | + |
| 130 | +import ConfigParser |
| 131 | +from distutils.version import LooseVersion |
| 132 | +try: |
| 133 | + from pymongo.errors import ConnectionFailure |
| 134 | + from pymongo.errors import OperationFailure |
| 135 | + from pymongo import version as PyMongoVersion |
| 136 | + from pymongo import MongoClient |
| 137 | +except ImportError: |
| 138 | + try: # for older PyMongo 2.2 |
| 139 | + from pymongo import Connection as MongoClient |
| 140 | + except ImportError: |
| 141 | + pymongo_found = False |
| 142 | + else: |
| 143 | + pymongo_found = True |
| 144 | +else: |
| 145 | + pymongo_found = True |
| 146 | + |
| 147 | +# ========================================= |
| 148 | +# MongoDB module specific support methods. |
| 149 | +# |
| 150 | + |
| 151 | +def user_find(client, user): |
| 152 | + for mongo_user in client["admin"].system.users.find(): |
| 153 | + if mongo_user['user'] == user: |
| 154 | + return mongo_user |
| 155 | + return False |
| 156 | + |
| 157 | +def user_add(module, client, db_name, user, password, roles): |
| 158 | + #pymono's user_add is a _create_or_update_user so we won't know if it was changed or updated |
| 159 | + #without reproducing a lot of the logic in database.py of pymongo |
| 160 | + db = client[db_name] |
| 161 | + if roles is None: |
| 162 | + db.add_user(user, password, False) |
| 163 | + else: |
| 164 | + try: |
| 165 | + db.add_user(user, password, None, roles=roles) |
| 166 | + except OperationFailure, e: |
| 167 | + err_msg = str(e) |
| 168 | + srv_info = client.server_info() |
| 169 | + if LooseVersion(srv_info['version']) >= LooseVersion('3.0') and LooseVersion(PyMongoVersion) <= LooseVersion('3.0'): |
| 170 | + err_msg = err_msg + ' (Note: you must use pymongo 3.0+ with MongoDB >= 3.0)' |
| 171 | + elif LooseVersion(srv_info['version']) >= LooseVersion('2.6') and LooseVersion(PyMongoVersion) <= LooseVersion('2.7'): |
| 172 | + err_msg = err_msg + ' (Note: you must use pymongo 2.7.x-2.9.x with MongoDB 2.6)' |
| 173 | + elif LooseVersion(PyMongoVersion) <= LooseVersion('2.5'): |
| 174 | + err_msg = err_msg + ' (Note: you must be on mongodb 2.4+ and pymongo 2.5+ to use the roles param)' |
| 175 | + module.fail_json(msg=err_msg) |
| 176 | + |
| 177 | +def user_remove(module, client, db_name, user): |
| 178 | + exists = user_find(client, user) |
| 179 | + if exists: |
| 180 | + db = client[db_name] |
| 181 | + db.remove_user(user) |
| 182 | + else: |
| 183 | + module.exit_json(changed=False, user=user) |
| 184 | + |
| 185 | +def load_mongocnf(): |
| 186 | + config = ConfigParser.RawConfigParser() |
| 187 | + mongocnf = os.path.expanduser('~/.mongodb.cnf') |
| 188 | + |
| 189 | + try: |
| 190 | + config.readfp(open(mongocnf)) |
| 191 | + creds = dict( |
| 192 | + user=config.get('client', 'user'), |
| 193 | + password=config.get('client', 'pass') |
| 194 | + ) |
| 195 | + except (ConfigParser.NoOptionError, IOError): |
| 196 | + return False |
| 197 | + |
| 198 | + return creds |
| 199 | + |
| 200 | +# ========================================= |
| 201 | +# Module execution. |
| 202 | +# |
| 203 | + |
| 204 | +def main(): |
| 205 | + module = AnsibleModule( |
| 206 | + argument_spec = dict( |
| 207 | + login_user=dict(default=None), |
| 208 | + login_password=dict(default=None), |
| 209 | + login_host=dict(default='localhost'), |
| 210 | + login_port=dict(default='27017'), |
| 211 | + login_database=dict(default=None), |
| 212 | + replica_set=dict(default=None), |
| 213 | + database=dict(required=True, aliases=['db']), |
| 214 | + name=dict(required=True, aliases=['user']), |
| 215 | + password=dict(aliases=['pass']), |
| 216 | + ssl=dict(default=False), |
| 217 | + roles=dict(default=None, type='list'), |
| 218 | + state=dict(default='present', choices=['absent', 'present']), |
| 219 | + update_password=dict(default="always", choices=["always", "on_create"]), |
| 220 | + ) |
| 221 | + ) |
| 222 | + |
| 223 | + if not pymongo_found: |
| 224 | + module.fail_json(msg='the python pymongo module is required') |
| 225 | + |
| 226 | + login_user = module.params['login_user'] |
| 227 | + login_password = module.params['login_password'] |
| 228 | + login_host = module.params['login_host'] |
| 229 | + login_port = module.params['login_port'] |
| 230 | + login_database = module.params['login_database'] |
| 231 | + |
| 232 | + replica_set = module.params['replica_set'] |
| 233 | + db_name = module.params['database'] |
| 234 | + user = module.params['name'] |
| 235 | + password = module.params['password'] |
| 236 | + ssl = module.params['ssl'] |
| 237 | + roles = module.params['roles'] |
| 238 | + state = module.params['state'] |
| 239 | + update_password = module.params['update_password'] |
| 240 | + |
| 241 | + try: |
| 242 | + if replica_set: |
| 243 | + client = MongoClient(login_host, int(login_port), replicaset=replica_set, ssl=ssl) |
| 244 | + else: |
| 245 | + client = MongoClient(login_host, int(login_port), ssl=ssl) |
| 246 | + |
| 247 | + if login_user is None and login_password is None: |
| 248 | + mongocnf_creds = load_mongocnf() |
| 249 | + if mongocnf_creds is not False: |
| 250 | + login_user = mongocnf_creds['user'] |
| 251 | + login_password = mongocnf_creds['password'] |
| 252 | + elif login_password is None or login_user is None: |
| 253 | + module.fail_json(msg='when supplying login arguments, both login_user and login_password must be provided') |
| 254 | + |
| 255 | + if login_user is not None and login_password is not None: |
| 256 | + client.admin.authenticate(login_user, login_password, source=login_database) |
| 257 | + elif LooseVersion(PyMongoVersion) >= LooseVersion('3.0'): |
| 258 | + if db_name != "admin": |
| 259 | + module.fail_json(msg='The localhost login exception only allows the first admin account to be created') |
| 260 | + #else: this has to be the first admin user added |
| 261 | + |
| 262 | + except ConnectionFailure, e: |
| 263 | + module.fail_json(msg='unable to connect to database: %s' % str(e)) |
| 264 | + |
| 265 | + if state == 'present': |
| 266 | + if password is None and update_password == 'always': |
| 267 | + module.fail_json(msg='password parameter required when adding a user unless update_password is set to on_create') |
| 268 | + |
| 269 | + if update_password != 'always' and user_find(client, user): |
| 270 | + password = None |
| 271 | + |
| 272 | + try: |
| 273 | + user_add(module, client, db_name, user, password, roles) |
| 274 | + except OperationFailure, e: |
| 275 | + module.fail_json(msg='Unable to add or update user: %s' % str(e)) |
| 276 | + |
| 277 | + elif state == 'absent': |
| 278 | + try: |
| 279 | + user_remove(module, client, db_name, user) |
| 280 | + except OperationFailure, e: |
| 281 | + module.fail_json(msg='Unable to remove user: %s' % str(e)) |
| 282 | + |
| 283 | + module.exit_json(changed=True, user=user) |
| 284 | + |
| 285 | +# import module snippets |
| 286 | +from ansible.module_utils.basic import * |
| 287 | +main() |
0 commit comments