| 1 |
# (c) 2016, Marcos Diez <[email protected]> |
| 2 |
# https://github.com/marcosdiez/ |
| 3 |
# |
| 4 |
# This file is part of Ansible |
| 5 |
# |
| 6 |
# Ansible is free software: you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# Ansible is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
|
| 19 |
from __future__ import (absolute_import, division, print_function) |
| 20 |
|
| 21 |
__metaclass__ = type |
| 22 |
|
| 23 |
DOCUMENTATION = ''' |
| 24 |
name: mongodb |
| 25 |
author: |
| 26 |
- Marcos Diez (@marcosdiez) |
| 27 |
version_added: "1.0.0" |
| 28 |
short_description: lookup info from MongoDB |
| 29 |
description: |
| 30 |
- 'The ``MongoDB`` lookup runs the *find()* command on a given *collection* on a given *MongoDB* server.' |
| 31 |
- 'The result is a list of jsons, so slightly different from what PyMongo returns. In particular, *timestamps* are converted to epoch integers.' |
| 32 |
options: |
| 33 |
connect_string: |
| 34 |
description: |
| 35 |
- Can be any valid MongoDB connection string, supporting authentication, replica sets, etc. |
| 36 |
- "More info at U(https://docs.mongodb.org/manual/reference/connection-string/)" |
| 37 |
default: "mongodb://localhost/" |
| 38 |
database: |
| 39 |
description: |
| 40 |
- Name of the database which the query will be made |
| 41 |
required: True |
| 42 |
collection: |
| 43 |
description: |
| 44 |
- Name of the collection which the query will be made |
| 45 |
required: True |
| 46 |
filter: |
| 47 |
description: |
| 48 |
- Criteria of the output |
| 49 |
type: 'dict' |
| 50 |
default: {} |
| 51 |
projection: |
| 52 |
description: |
| 53 |
- Fields you want returned |
| 54 |
type: dict |
| 55 |
default: {} |
| 56 |
skip: |
| 57 |
description: |
| 58 |
- How many results should be skipped |
| 59 |
type: integer |
| 60 |
limit: |
| 61 |
description: |
| 62 |
- How many results should be shown |
| 63 |
type: integer |
| 64 |
sort: |
| 65 |
description: |
| 66 |
- Sorting rules. |
| 67 |
- Please use the strings C(ASCENDING) and C(DESCENDING) to set the order. |
| 68 |
- Check the example for more information. |
| 69 |
type: list |
| 70 |
elements: list |
| 71 |
default: [] |
| 72 |
extra_connection_parameters: |
| 73 |
description: |
| 74 |
- Extra connection parameters that to be sent to pymongo.MongoClient |
| 75 |
- Check the example to see how to connect to mongo using an SSL certificate. |
| 76 |
- "All possible parameters are here: U(https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient)" |
| 77 |
type: dict |
| 78 |
default: {} |
| 79 |
notes: |
| 80 |
- "Please check https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find for more details." |
| 81 |
requirements: |
| 82 |
- pymongo >= 2.4 (python library) |
| 83 |
''' |
| 84 |
|
| 85 |
EXAMPLES = ''' |
| 86 |
- hosts: localhost |
| 87 |
gather_facts: false |
| 88 |
vars: |
| 89 |
mongodb_parameters: |
| 90 |
#mandatory parameters |
| 91 |
database: 'local' |
| 92 |
collection: "startup_log" |
| 93 |
#optional |
| 94 |
connection_string: "mongodb://localhost/" |
| 95 |
# connection_string: "mongodb://username:[email protected]:27017/" |
| 96 |
# extra_connection_parameters: { "ssl" : True , "ssl_certfile": /etc/self_signed_certificate.pem" } |
| 97 |
#optional query parameters, we accept any parameter from the normal mongodb query. |
| 98 |
# filter: { "hostname": "u18" } |
| 99 |
projection: { "pid": True , "_id" : False , "hostname" : True } |
| 100 |
skip: 0 |
| 101 |
limit: 1 |
| 102 |
sort: [ [ "startTime" , "ASCENDING" ] , [ "age", "DESCENDING" ] ] |
| 103 |
tasks: |
| 104 |
- debug: msg="The PID from MongoDB is {{ lookup('mongodb', mongodb_parameters ).pid }}" |
| 105 |
|
| 106 |
- debug: msg="The HostName from the MongoDB server is {{ lookup('mongodb', mongodb_parameters ).hostname }}" |
| 107 |
|
| 108 |
- debug: msg="Mongo DB is stored at {{ lookup('mongodb', mongodb_parameters_inline )}}" |
| 109 |
vars: |
| 110 |
mongodb_parameters_inline: |
| 111 |
database: 'local' |
| 112 |
collection: "startup_log" |
| 113 |
connection_string: "mongodb://localhost/" |
| 114 |
limit: 1 |
| 115 |
projection: { "cmdline.storage": True } |
| 116 |
|
| 117 |
# lookup syntax, does the same as below |
| 118 |
- debug: msg="The hostname is {{ item.hostname }} and the pid is {{ item.pid }}" |
| 119 |
loop: "{{ lookup('mongodb', mongodb_parameters, wantlist=True) }}" |
| 120 |
|
| 121 |
# query syntax, does the same as above |
| 122 |
- debug: msg="The hostname is {{ item.hostname }} and the pid is {{ item.pid }}" |
| 123 |
loop: "{{ query('mongodb', mongodb_parameters) }}" |
| 124 |
|
| 125 |
- name: "Raw output from the mongodb lookup (a json with pid and hostname )" |
| 126 |
debug: msg="{{ lookup('mongodb', mongodb_parameters) }}" |
| 127 |
|
| 128 |
- name: "Yet another mongodb query, now with the parameters on the task itself" |
| 129 |
debug: msg="pid={{item.pid}} hostname={{item.hostname}} version={{ item.buildinfo.version }}" |
| 130 |
with_mongodb: |
| 131 |
- database: 'local' |
| 132 |
collection: "startup_log" |
| 133 |
connection_string: "mongodb://localhost/" |
| 134 |
limit: 1 |
| 135 |
projection: { "pid": True , "hostname": True , "buildinfo.version": True } |
| 136 |
|
| 137 |
# Please notice this specific query may result more than one result. This is expected |
| 138 |
- name: "Shows the whole output from mongodb" |
| 139 |
debug: msg="{{ item }}" |
| 140 |
with_mongodb: |
| 141 |
- database: 'local' |
| 142 |
collection: "startup_log" |
| 143 |
connection_string: "mongodb://localhost/" |
| 144 |
|
| 145 |
|
| 146 |
''' |
| 147 |
|
| 148 |
RETURN = """ |
| 149 |
_list_of_jsons: |
| 150 |
description: |
| 151 |
- a list of JSONs with the results of the MongoDB query. |
| 152 |
type: list |
| 153 |
""" |
| 154 |
|
| 155 |
import datetime |
| 156 |
|
| 157 |
from ansible.module_utils.six import string_types, integer_types # pylint: disable=ansible-bad-import-from |
| 158 |
from ansible.module_utils._text import to_native |
| 159 |
from ansible.errors import AnsibleError |
| 160 |
from ansible.plugins.lookup import LookupBase |
| 161 |
|
| 162 |
try: |
| 163 |
from pymongo import ASCENDING, DESCENDING |
| 164 |
from pymongo.errors import ConnectionFailure |
| 165 |
from pymongo import MongoClient |
| 166 |
except ImportError: |
| 167 |
try: # for older PyMongo 2.2 |
| 168 |
from pymongo import Connection as MongoClient |
| 169 |
except ImportError: |
| 170 |
pymongo_found = False |
| 171 |
else: |
| 172 |
pymongo_found = True |
| 173 |
else: |
| 174 |
pymongo_found = True |
| 175 |
|
| 176 |
|
| 177 |
class LookupModule(LookupBase): |
| 178 |
|
| 179 |
def _fix_sort_parameter(self, sort_parameter): |
| 180 |
if sort_parameter is None: |
| 181 |
return sort_parameter |
| 182 |
|
| 183 |
if not isinstance(sort_parameter, list): |
| 184 |
raise AnsibleError(u"Error. Sort parameters must be a list, not [ {0} ]".format(sort_parameter)) |
| 185 |
|
| 186 |
for item in sort_parameter: |
| 187 |
self._convert_sort_string_to_constant(item) |
| 188 |
|
| 189 |
return sort_parameter |
| 190 |
|
| 191 |
def _convert_sort_string_to_constant(self, item): |
| 192 |
original_sort_order = item[1] |
| 193 |
sort_order = original_sort_order.upper() |
| 194 |
if sort_order == u"ASCENDING": |
| 195 |
item[1] = ASCENDING |
| 196 |
elif sort_order == u"DESCENDING": |
| 197 |
item[1] = DESCENDING |
| 198 |
# else the user knows what s/he is doing and we won't predict. PyMongo will return an error if necessary |
| 199 |
|
| 200 |
def convert_mongo_result_to_valid_json(self, result): |
| 201 |
if result is None: |
| 202 |
return result |
| 203 |
if isinstance(result, integer_types + (float, bool)): |
| 204 |
return result |
| 205 |
if isinstance(result, string_types): |
| 206 |
return result |
| 207 |
elif isinstance(result, list): |
| 208 |
new_list = [] |
| 209 |
for elem in result: |
| 210 |
new_list.append(self.convert_mongo_result_to_valid_json(elem)) |
| 211 |
return new_list |
| 212 |
elif isinstance(result, dict): |
| 213 |
new_dict = {} |
| 214 |
for key in result.keys(): |
| 215 |
value = result[key] # python2 and 3 compatible.... |
| 216 |
new_dict[key] = self.convert_mongo_result_to_valid_json(value) |
| 217 |
return new_dict |
| 218 |
elif isinstance(result, datetime.datetime): |
| 219 |
# epoch |
| 220 |
return (result - datetime.datetime(1970, 1, 1)). total_seconds() |
| 221 |
else: |
| 222 |
# failsafe |
| 223 |
return u"{0}".format(result) |
| 224 |
|
| 225 |
def run(self, terms, variables, **kwargs): |
| 226 |
try: |
| 227 |
return self._run_helper(terms) |
| 228 |
except Exception as e: |
| 229 |
print(u"There was an exception on the mongodb_lookup: {0}".format(to_native(e))) |
| 230 |
raise e |
| 231 |
|
| 232 |
def _run_helper(self, terms): |
| 233 |
if not pymongo_found: |
| 234 |
raise AnsibleError(u"pymongo is required in the control node (this machine) for mongodb lookup.") |
| 235 |
ret = [] |
| 236 |
for term in terms: |
| 237 |
for required_parameter in [u"database", u"collection"]: |
| 238 |
if required_parameter not in term: |
| 239 |
raise AnsibleError(u"missing mandatory parameter [{0}]".format(required_parameter)) |
| 240 |
|
| 241 |
connection_string = term.get(u'connection_string', u"mongodb://localhost") |
| 242 |
database = term[u"database"] |
| 243 |
collection = term[u'collection'] |
| 244 |
extra_connection_parameters = term.get(u'extra_connection_parameters', {}) |
| 245 |
|
| 246 |
if u"extra_connection_parameters" in term: |
| 247 |
del term[u"extra_connection_parameters"] |
| 248 |
if u"connection_string" in term: |
| 249 |
del term[u"connection_string"] |
| 250 |
del term[u"database"] |
| 251 |
del term[u"collection"] |
| 252 |
|
| 253 |
if u"sort" in term: |
| 254 |
term[u"sort"] = self._fix_sort_parameter(term[u"sort"]) |
| 255 |
|
| 256 |
# all other parameters are sent to mongo, so we are future and past proof |
| 257 |
|
| 258 |
try: |
| 259 |
client = MongoClient(connection_string, **extra_connection_parameters) |
| 260 |
results = client[database][collection].find(**term) |
| 261 |
|
| 262 |
for result in results: |
| 263 |
result = self.convert_mongo_result_to_valid_json(result) |
| 264 |
ret.append(result) |
| 265 |
|
| 266 |
except ConnectionFailure as e: |
| 267 |
raise AnsibleError(u'unable to connect to database: %s' % str(e)) |
| 268 |
|
| 269 |
return ret |