| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2013, Chatham Financial <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r''' |
| 12 |
--- |
| 13 |
module: rabbitmq_user |
| 14 |
short_description: Manage RabbitMQ users |
| 15 |
description: |
| 16 |
- Add or remove users to RabbitMQ and assign permissions |
| 17 |
author: Chris Hoffman (@chrishoffman) |
| 18 |
options: |
| 19 |
user: |
| 20 |
description: |
| 21 |
- Name of user to add |
| 22 |
type: str |
| 23 |
required: true |
| 24 |
aliases: [username, name] |
| 25 |
password: |
| 26 |
description: |
| 27 |
- Password of user to add. |
| 28 |
- To change the password of an existing user, you must also specify |
| 29 |
C(update_password=always). |
| 30 |
type: str |
| 31 |
tags: |
| 32 |
description: |
| 33 |
- User tags specified as comma delimited. |
| 34 |
- The suggested tags to use are management, policymaker, monitoring and administrator. |
| 35 |
type: str |
| 36 |
permissions: |
| 37 |
description: |
| 38 |
- a list of dicts, each dict contains vhost, configure_priv, write_priv, and read_priv, |
| 39 |
and represents a permission rule for that vhost. |
| 40 |
- This option should be preferable when you care about all permissions of the user. |
| 41 |
- You should use vhost, configure_priv, write_priv, and read_priv options instead |
| 42 |
if you care about permissions for just some vhosts. |
| 43 |
type: list |
| 44 |
elements: dict |
| 45 |
default: [] |
| 46 |
vhost: |
| 47 |
description: |
| 48 |
- vhost to apply access privileges. |
| 49 |
- This option will be ignored when permissions option is used. |
| 50 |
type: str |
| 51 |
default: / |
| 52 |
node: |
| 53 |
description: |
| 54 |
- erlang node name of the rabbit we wish to configure |
| 55 |
type: str |
| 56 |
default: rabbit |
| 57 |
configure_priv: |
| 58 |
description: |
| 59 |
- Regular expression to restrict configure actions on a resource |
| 60 |
for the specified vhost. |
| 61 |
- By default all actions are restricted. |
| 62 |
- This option will be ignored when permissions option is used. |
| 63 |
type: str |
| 64 |
default: '^$' |
| 65 |
write_priv: |
| 66 |
description: |
| 67 |
- Regular expression to restrict configure actions on a resource |
| 68 |
for the specified vhost. |
| 69 |
- By default all actions are restricted. |
| 70 |
- This option will be ignored when permissions option is used. |
| 71 |
type: str |
| 72 |
default: '^$' |
| 73 |
read_priv: |
| 74 |
description: |
| 75 |
- Regular expression to restrict configure actions on a resource |
| 76 |
for the specified vhost. |
| 77 |
- By default all actions are restricted. |
| 78 |
- This option will be ignored when permissions option is used. |
| 79 |
type: str |
| 80 |
default: '^$' |
| 81 |
topic_permissions: |
| 82 |
description: |
| 83 |
- A list of dicts, each dict contains vhost, exchange, read_priv and write_priv, |
| 84 |
and represents a topic permission rule for that vhost. |
| 85 |
- By default vhost is C(/) and exchange is C(amq.topic). |
| 86 |
- Supported since RabbitMQ 3.7.0. If RabbitMQ is older and topic_permissions are |
| 87 |
set, the module will fail. |
| 88 |
type: list |
| 89 |
elements: dict |
| 90 |
default: [] |
| 91 |
version_added: '1.2.0' |
| 92 |
force: |
| 93 |
description: |
| 94 |
- Deletes and recreates the user. |
| 95 |
type: bool |
| 96 |
default: false |
| 97 |
state: |
| 98 |
description: |
| 99 |
- Specify if user is to be added or removed |
| 100 |
type: str |
| 101 |
default: present |
| 102 |
choices: ['present', 'absent'] |
| 103 |
update_password: |
| 104 |
description: |
| 105 |
- C(on_create) will only set the password for newly created users. C(always) will update passwords if they differ. |
| 106 |
type: str |
| 107 |
default: on_create |
| 108 |
choices: ['on_create', 'always'] |
| 109 |
login_protocol: |
| 110 |
description: |
| 111 |
- Specify which TCP/IP protocol will be used. |
| 112 |
type: str |
| 113 |
default: http |
| 114 |
choices: ['http', 'https'] |
| 115 |
version_added: '1.3.0' |
| 116 |
login_host: |
| 117 |
description: |
| 118 |
- Hostname of API. |
| 119 |
type: str |
| 120 |
version_added: '1.3.0' |
| 121 |
login_port: |
| 122 |
description: |
| 123 |
- login_port of access from API. |
| 124 |
type: str |
| 125 |
default: '15672' |
| 126 |
version_added: '1.3.0' |
| 127 |
login_user: |
| 128 |
description: |
| 129 |
- Administrator's username the management API. |
| 130 |
type: str |
| 131 |
version_added: '1.3.0' |
| 132 |
login_password: |
| 133 |
description: |
| 134 |
- Login password of the management API. |
| 135 |
type: str |
| 136 |
version_added: '1.3.0' |
| 137 |
''' |
| 138 |
|
| 139 |
EXAMPLES = r''' |
| 140 |
- name: |- |
| 141 |
Add user to server and assign full access control on / vhost. |
| 142 |
The user might have permission rules for other vhost but you don't care. |
| 143 |
community.rabbitmq.rabbitmq_user: |
| 144 |
user: joe |
| 145 |
password: changeme |
| 146 |
vhost: / |
| 147 |
configure_priv: .* |
| 148 |
read_priv: .* |
| 149 |
write_priv: .* |
| 150 |
state: present |
| 151 |
|
| 152 |
- name: |- |
| 153 |
Add user to server and assign full access control on / vhost. |
| 154 |
The user doesn't have permission rules for other vhosts |
| 155 |
community.rabbitmq.rabbitmq_user: |
| 156 |
user: joe |
| 157 |
password: changeme |
| 158 |
permissions: |
| 159 |
- vhost: / |
| 160 |
configure_priv: .* |
| 161 |
read_priv: .* |
| 162 |
write_priv: .* |
| 163 |
state: present |
| 164 |
|
| 165 |
- name: |- |
| 166 |
Add user to server and assign some topic permissions on / vhost. |
| 167 |
The user doesn't have topic permission rules for other vhosts |
| 168 |
community.rabbitmq.rabbitmq_user: |
| 169 |
user: joe |
| 170 |
password: changeme |
| 171 |
topic_permissions: |
| 172 |
- vhost: / |
| 173 |
exchange: amq.topic |
| 174 |
read_priv: .* |
| 175 |
write_priv: 'prod\\.logging\\..*' |
| 176 |
state: present |
| 177 |
|
| 178 |
- name: Add or Update a user using the API |
| 179 |
community.rabbitmq.rabbitmq_user: |
| 180 |
user: joe |
| 181 |
password: changeme |
| 182 |
tags: monitoring |
| 183 |
login_protocol: https |
| 184 |
login_host: localhost |
| 185 |
login_port: 15672 |
| 186 |
login_user: admin |
| 187 |
login_password: changeadmin |
| 188 |
permissions: |
| 189 |
- vhost: / |
| 190 |
configure_priv: .* |
| 191 |
read_priv: .* |
| 192 |
write_priv: .* |
| 193 |
topic_permissions: |
| 194 |
- vhost: / |
| 195 |
exchange: amq.topic |
| 196 |
read_priv: .* |
| 197 |
write_priv: 'prod\\.logging\\..*' |
| 198 |
state: present |
| 199 |
|
| 200 |
|
| 201 |
- name: Remove a user using the API |
| 202 |
community.rabbitmq.rabbitmq_user: |
| 203 |
user: joe |
| 204 |
password: changeme |
| 205 |
tags: monitoring |
| 206 |
login_protocol: https |
| 207 |
login_host: localhost |
| 208 |
login_port: 15672 |
| 209 |
login_user: admin |
| 210 |
login_password: changeadmin |
| 211 |
state: absent |
| 212 |
|
| 213 |
''' |
| 214 |
|
| 215 |
import ansible_collections.community.rabbitmq.plugins.module_utils.version as Version # noqa: E402 |
| 216 |
import json # noqa: E402 |
| 217 |
import re # noqa: E402 |
| 218 |
|
| 219 |
from ansible.module_utils.six.moves.urllib import parse as urllib_parse |
| 220 |
|
| 221 |
import traceback |
| 222 |
|
| 223 |
REQUESTS_IMP_ERR = None |
| 224 |
try: |
| 225 |
import requests |
| 226 |
|
| 227 |
HAS_REQUESTS = True |
| 228 |
except ImportError: |
| 229 |
REQUESTS_IMP_ERR = traceback.format_exc() |
| 230 |
HAS_REQUESTS = False |
| 231 |
|
| 232 |
from ansible.module_utils.basic import AnsibleModule # noqa: E402 |
| 233 |
from ansible.module_utils.common.collections import count |
| 234 |
|
| 235 |
|
| 236 |
def normalized_permissions(vhost_permission_list): |
| 237 |
"""Older versions of RabbitMQ output permissions with slightly different names. |
| 238 |
|
| 239 |
In older versions of RabbitMQ, the names of the permissions had the `_priv` suffix, which was removed in versions |
| 240 |
>= 3.7.6. For simplicity we only check the `configure` permission. If it's in the old format then all the other |
| 241 |
ones will be wrong too. |
| 242 |
""" |
| 243 |
for vhost_permission in vhost_permission_list: |
| 244 |
if 'configure_priv' in vhost_permission: |
| 245 |
yield { |
| 246 |
'configure': vhost_permission['configure_priv'], |
| 247 |
'read': vhost_permission['read_priv'], |
| 248 |
'write': vhost_permission['write_priv'], |
| 249 |
'vhost': vhost_permission['vhost'] |
| 250 |
} |
| 251 |
else: |
| 252 |
yield vhost_permission |
| 253 |
|
| 254 |
|
| 255 |
def as_permission_dict(vhost_permission_list): |
| 256 |
return dict([(vhost_permission['vhost'], vhost_permission) for vhost_permission |
| 257 |
in normalized_permissions(vhost_permission_list)]) |
| 258 |
|
| 259 |
|
| 260 |
def as_topic_permission_dict(topic_permission_list): |
| 261 |
return dict([((perm['vhost'], perm['exchange']), perm) for perm |
| 262 |
in topic_permission_list]) |
| 263 |
|
| 264 |
|
| 265 |
def only(vhost, vhost_permissions): |
| 266 |
return {vhost: vhost_permissions.get(vhost, {})} |
| 267 |
|
| 268 |
|
| 269 |
def first(iterable): |
| 270 |
return next(iter(iterable)) |
| 271 |
|
| 272 |
|
| 273 |
def treat_permissions_for_api(permissions): |
| 274 |
return { |
| 275 |
"configure": permissions.get('configure') if permissions.get('configure') else '^$', |
| 276 |
"write": permissions.get('write') if permissions.get('write') else '^$', |
| 277 |
"read": permissions.get('read') if permissions.get('read') else '^$' |
| 278 |
} |
| 279 |
|
| 280 |
|
| 281 |
def treat_topic_permissions_for_api(permissions): |
| 282 |
return {"exchange": permissions.get('exchange'), "write": permissions.get('write'), |
| 283 |
"read": permissions.get('read')} |
| 284 |
|
| 285 |
|
| 286 |
class RabbitMqUser(object): |
| 287 |
def __init__(self, module, username, password, tags, permissions, |
| 288 |
topic_permissions, node, bulk_permissions=False, |
| 289 |
login_protocol=None, login_host=None, login_port=None, |
| 290 |
login_user=None, login_password=None): |
| 291 |
self.module = module |
| 292 |
self.username = username |
| 293 |
self.password = password or '' |
| 294 |
self.node = node |
| 295 |
self.tags = list() if not tags else tags.replace(' ', '').split(',') |
| 296 |
self.permissions = as_permission_dict(permissions) |
| 297 |
self.topic_permissions = as_topic_permission_dict(topic_permissions) |
| 298 |
self.bulk_permissions = bulk_permissions |
| 299 |
self.login_protocol = login_protocol |
| 300 |
self.login_host = login_host |
| 301 |
self.login_port = login_port |
| 302 |
self.login_user = login_user |
| 303 |
self.login_password = login_password |
| 304 |
|
| 305 |
self.existing_tags = None |
| 306 |
self.existing_permissions = dict() |
| 307 |
self.existing_topic_permissions = dict() |
| 308 |
if self.login_host is not None: |
| 309 |
self._rabbitmqctl = module.get_bin_path('rabbitmqctl', False) |
| 310 |
self._version = None |
| 311 |
else: |
| 312 |
self._rabbitmqctl = module.get_bin_path('rabbitmqctl', True) |
| 313 |
self._version = self._check_version() |
| 314 |
|
| 315 |
def _check_version(self): |
| 316 |
"""Get the version of the RabbitMQ server.""" |
| 317 |
version = self._rabbitmq_version_post_3_7(fail_on_error=False) |
| 318 |
if not version: |
| 319 |
version = self._rabbitmq_version_pre_3_7(fail_on_error=False) |
| 320 |
if not version: |
| 321 |
self.module.fail_json(msg="Could not determine the version of the RabbitMQ server.") |
| 322 |
return version |
| 323 |
|
| 324 |
def _fail(self, msg, stop_execution=False): |
| 325 |
if stop_execution: |
| 326 |
self.module.fail_json(msg=msg) |
| 327 |
# This is a dummy return to prevent linters from throwing errors. |
| 328 |
return None |
| 329 |
|
| 330 |
def _rabbitmq_version_post_3_7(self, fail_on_error=False): |
| 331 |
"""Use the JSON formatter to get a machine readable output of the version. |
| 332 |
|
| 333 |
At this point we do not know which RabbitMQ server version we are dealing with and which |
| 334 |
version of `rabbitmqctl` we are using, so we will try to use the JSON formatter and see |
| 335 |
what happens. In some versions of |
| 336 |
""" |
| 337 |
|
| 338 |
def int_list_to_str(ints): |
| 339 |
return ''.join([chr(i) for i in ints]) |
| 340 |
|
| 341 |
rc, output, err = self._exec(['status', '--formatter', 'json'], check_rc=False) |
| 342 |
if rc != 0: |
| 343 |
return self._fail(msg="Could not parse the version of the RabbitMQ server, " |
| 344 |
"because `rabbitmqctl status` returned no output.", |
| 345 |
stop_execution=fail_on_error) |
| 346 |
try: |
| 347 |
status_json = json.loads(output) |
| 348 |
if 'rabbitmq_version' in status_json: |
| 349 |
return Version.StrictVersion(status_json['rabbitmq_version']) |
| 350 |
for application in status_json.get('running_applications', list()): |
| 351 |
if application[0] == 'rabbit': |
| 352 |
if isinstance(application[1][0], int): |
| 353 |
return Version.StrictVersion(int_list_to_str(application[2])) |
| 354 |
else: |
| 355 |
return Version.StrictVersion(application[1]) |
| 356 |
return self._fail(msg="Could not find RabbitMQ version of `rabbitmqctl status` command.", |
| 357 |
stop_execution=fail_on_error) |
| 358 |
except ValueError as e: |
| 359 |
return self._fail(msg="Could not parse output of `rabbitmqctl status` as JSON: {exc}.".format(exc=repr(e)), |
| 360 |
stop_execution=fail_on_error) |
| 361 |
|
| 362 |
def _rabbitmq_version_pre_3_7(self, fail_on_error=False): |
| 363 |
"""Get the version of the RabbitMQ Server. |
| 364 |
|
| 365 |
Before version 3.7.6 the `rabbitmqctl` utility did not support the |
| 366 |
`--formatter` flag, so the output has to be parsed using regular expressions. |
| 367 |
""" |
| 368 |
version_reg_ex = r"{rabbit,\"RabbitMQ\",\"([0-9]+\.[0-9]+\.[0-9]+)\"}" |
| 369 |
rc, output, err = self._exec(['status'], check_rc=False) |
| 370 |
if rc != 0: |
| 371 |
if fail_on_error: |
| 372 |
self.module.fail_json(msg="Could not parse the version of the RabbitMQ server, because" |
| 373 |
" `rabbitmqctl status` returned no output.") |
| 374 |
else: |
| 375 |
return None |
| 376 |
reg_ex_res = re.search(version_reg_ex, output, re.IGNORECASE) |
| 377 |
if not reg_ex_res: |
| 378 |
return self._fail(msg="Could not parse the version of the RabbitMQ server from the output of " |
| 379 |
"`rabbitmqctl status` command: {output}.".format(output=output), |
| 380 |
stop_execution=fail_on_error) |
| 381 |
try: |
| 382 |
return Version.StrictVersion(reg_ex_res.group(1)) |
| 383 |
except ValueError as e: |
| 384 |
return self._fail(msg="Could not parse the version of the RabbitMQ server: {exc}.".format(exc=repr(e)), |
| 385 |
stop_execution=fail_on_error) |
| 386 |
|
| 387 |
def _exec(self, args, check_rc=True): |
| 388 |
"""Execute a command using the `rabbitmqctl` utility. |
| 389 |
|
| 390 |
By default the _exec call will cause the module to fail, if the error code is non-zero. If the `check_rc` |
| 391 |
flag is set to False, then the exit_code, stdout and stderr will be returned to the calling function to |
| 392 |
perform whatever error handling it needs. |
| 393 |
|
| 394 |
:param args: the arguments to pass to the `rabbitmqctl` utility |
| 395 |
:param check_rc: when set to True, fail if the utility's exit code is non-zero |
| 396 |
:return: the output of the command or all the outputs plus the error code in case of error |
| 397 |
""" |
| 398 |
cmd = [self._rabbitmqctl, '-q'] |
| 399 |
if self.node: |
| 400 |
cmd.extend(['-n', self.node]) |
| 401 |
rc, out, err = self.module.run_command(cmd + args) |
| 402 |
if check_rc and rc != 0: |
| 403 |
# check_rc is not passed to the `run_command` method directly to allow for more fine grained checking of |
| 404 |
# error messages returned by `rabbitmqctl`. |
| 405 |
user_error_msg_regex = r"(Only root or .* .* run rabbitmqctl)" |
| 406 |
user_error_msg = re.search(user_error_msg_regex, out) |
| 407 |
if user_error_msg: |
| 408 |
self.module.fail_json(msg="Wrong user used to run the `rabbitmqctl` utility: {err}" |
| 409 |
.format(err=user_error_msg.group(1))) |
| 410 |
else: |
| 411 |
self.module.fail_json(msg="rabbitmqctl exited with non-zero code: {err}".format(err=err), |
| 412 |
rc=rc, stdout=out) |
| 413 |
return out if check_rc else (rc, out, err) |
| 414 |
|
| 415 |
def get(self): |
| 416 |
"""Retrieves the list of registered users from the node. |
| 417 |
|
| 418 |
If the user is already present, the node will also be queried for the user's permissions and topic |
| 419 |
permissions. |
| 420 |
If the version of the node is >= 3.7.6 the JSON formatter will be used, otherwise the plaintext will be |
| 421 |
parsed. |
| 422 |
""" |
| 423 |
users = dict() |
| 424 |
if self.login_host is not None: |
| 425 |
response = self.request_users_api('GET') |
| 426 |
if response.status_code == 200: |
| 427 |
if isinstance(response.json(), list): |
| 428 |
users = dict([(user_entry['name'], user_entry['tags']) for user_entry in response.json()]) |
| 429 |
else: |
| 430 |
users = {response.json()['name']: response.json()['tags']} |
| 431 |
elif response.status_code == 404: |
| 432 |
return None |
| 433 |
else: |
| 434 |
self.module.fail_json( |
| 435 |
msg="Error getting the user", |
| 436 |
status=response.status_code, |
| 437 |
details=response.text |
| 438 |
) |
| 439 |
else: |
| 440 |
if self._version >= Version.StrictVersion('3.7.6'): |
| 441 |
users = dict([(user_entry['user'], user_entry['tags']) |
| 442 |
for user_entry in json.loads(self._exec(['list_users', '--formatter', 'json']))]) |
| 443 |
else: |
| 444 |
users = self._exec(['list_users']) |
| 445 |
|
| 446 |
def process_tags(tags): |
| 447 |
if not tags: |
| 448 |
return list() |
| 449 |
return tags.replace('[', '').replace(']', '').replace(' ', '').strip('\t').split(',') |
| 450 |
|
| 451 |
users_and_tags = [user_entry.split('\t') for user_entry in users.strip().split('\n')] |
| 452 |
|
| 453 |
users = dict() |
| 454 |
for user_parts in users_and_tags: |
| 455 |
users[user_parts[0]] = process_tags(user_parts[1]) if len(user_parts) > 1 else [] |
| 456 |
|
| 457 |
self.existing_tags = users.get(self.username, list()) |
| 458 |
self.existing_permissions = self._get_permissions() if self.username in users else dict() |
| 459 |
self.existing_topic_permissions = self._get_topic_permissions() if self.username in users else dict() |
| 460 |
return self.username in users |
| 461 |
|
| 462 |
def _get_permissions(self): |
| 463 |
"""Get permissions of the user from RabbitMQ.""" |
| 464 |
if self.login_host is not None: |
| 465 |
try: |
| 466 |
response = requests.get(self.get_permissions_api_url_builder(self.username), |
| 467 |
auth=(self.login_user, |
| 468 |
self.login_password)) |
| 469 |
except requests.exceptions.RequestException as exception: |
| 470 |
msg = ("Error trying to request topic permissions " |
| 471 |
"of the user %s info in rabbitmq.") % (self.username) |
| 472 |
self.module.fail_json( |
| 473 |
msg=msg, |
| 474 |
exception=exception, |
| 475 |
) |
| 476 |
|
| 477 |
if response.ok or (response.status_code == 204): |
| 478 |
permissions = list() |
| 479 |
for permission in response.json(): |
| 480 |
permissions.append({ |
| 481 |
"vhost": permission.get('vhost'), |
| 482 |
"configure": permission.get('configure'), |
| 483 |
"write": permission.get('write'), |
| 484 |
"read": permission.get('read') |
| 485 |
}) |
| 486 |
elif response.status_code == 404: |
| 487 |
return None |
| 488 |
else: |
| 489 |
self.module.fail_json( |
| 490 |
msg="Error getting the user", |
| 491 |
status=response.status_code, |
| 492 |
details=response.text |
| 493 |
) |
| 494 |
else: |
| 495 |
if self._version >= Version.StrictVersion('3.7.6'): |
| 496 |
permissions = json.loads(self._exec(['list_user_permissions', self.username, '--formatter', 'json'])) |
| 497 |
else: |
| 498 |
output = self._exec(['list_user_permissions', self.username]).strip().split('\n') |
| 499 |
perms_out = [perm.split('\t') for perm in output if perm.strip()] |
| 500 |
# Filter out headers from the output of the command in case they are still present |
| 501 |
perms_out = [perm for perm in perms_out if perm != ["vhost", "configure", "write", "read"]] |
| 502 |
|
| 503 |
permissions = list() |
| 504 |
for vhost, configure, write, read in perms_out: |
| 505 |
permissions.append(dict(vhost=vhost, configure=configure, write=write, read=read)) |
| 506 |
|
| 507 |
if self.bulk_permissions: |
| 508 |
return as_permission_dict(permissions) |
| 509 |
else: |
| 510 |
return only(first(self.permissions.keys()), as_permission_dict(permissions)) |
| 511 |
|
| 512 |
def _get_topic_permissions(self): |
| 513 |
"""Get topic permissions of the user from RabbitMQ.""" |
| 514 |
if self.login_host is not None: |
| 515 |
try: |
| 516 |
response = requests.get(self.get_topic_permissions_api_url_builder(self.username), |
| 517 |
auth=(self.login_user, |
| 518 |
self.login_password)) |
| 519 |
except requests.exceptions.RequestException as exception: |
| 520 |
msg = ("Error trying to request permissions " |
| 521 |
"of the user %s info in rabbitmq.") % (self.username) |
| 522 |
self.module.fail_json( |
| 523 |
msg=msg, |
| 524 |
exception=exception, |
| 525 |
) |
| 526 |
|
| 527 |
if response.ok or (response.status_code == 204): |
| 528 |
permissions = list() |
| 529 |
for permission in response.json(): |
| 530 |
permissions.append({ |
| 531 |
"vhost": permission.get('vhost'), |
| 532 |
"exchange": permission.get('exchange'), |
| 533 |
"write": permission.get('write'), |
| 534 |
"read": permission.get('read') |
| 535 |
}) |
| 536 |
return as_topic_permission_dict(permissions) |
| 537 |
elif response.status_code == 404: |
| 538 |
return None |
| 539 |
else: |
| 540 |
self.module.fail_json( |
| 541 |
msg="Error getting the user", |
| 542 |
status=response.status_code, |
| 543 |
details=response.text |
| 544 |
) |
| 545 |
else: |
| 546 |
if self._version < Version.StrictVersion('3.7.0'): |
| 547 |
return dict() |
| 548 |
if self._version >= Version.StrictVersion('3.7.6'): |
| 549 |
permissions = json.loads( |
| 550 |
self._exec(['list_user_topic_permissions', self.username, '--formatter', 'json'])) |
| 551 |
else: |
| 552 |
output = self._exec(['list_user_topic_permissions', self.username]).strip().split('\n') |
| 553 |
perms_out = [perm.split('\t') for perm in output if perm.strip()] |
| 554 |
permissions = list() |
| 555 |
for vhost, exchange, write, read in perms_out: |
| 556 |
permissions.append(dict(vhost=vhost, exchange=exchange, write=write, read=read)) |
| 557 |
return as_topic_permission_dict(permissions) |
| 558 |
|
| 559 |
def check_password(self): |
| 560 |
"""Return `True` if the user can authenticate successfully.""" |
| 561 |
if self.login_host is not None: |
| 562 |
url = "%s://%s:%s/api/whoami" % ( |
| 563 |
self.login_protocol, |
| 564 |
self.login_host, |
| 565 |
self.login_port) |
| 566 |
try: |
| 567 |
response = requests.get(url, auth=(self.username, self.password)) |
| 568 |
except requests.exceptions.RequestException as exception: |
| 569 |
msg = ("Error trying to request permissions " |
| 570 |
"of the user %s info in rabbitmq.") % (self.username) |
| 571 |
self.module.fail_json( |
| 572 |
msg=msg, |
| 573 |
exception=exception, |
| 574 |
) |
| 575 |
|
| 576 |
if response.ok or response.json().get('reason') == "Not management user": |
| 577 |
return True |
| 578 |
else: |
| 579 |
return False |
| 580 |
else: |
| 581 |
rc, out, err = self._exec(['authenticate_user', self.username, self.password], check_rc=False) |
| 582 |
return rc == 0 |
| 583 |
|
| 584 |
def add(self): |
| 585 |
if self.login_host is not None: |
| 586 |
data = {"password": self.password, "tags": self.treat_tags_for_api() or ""} |
| 587 |
response = self.request_users_api('PUT', data) |
| 588 |
|
| 589 |
if not response.ok or (response.status_code == 204): |
| 590 |
msg = ("Error trying to create user %s in rabbitmq. " |
| 591 |
"Status code '%s'.") % (self.username, response.status_code) |
| 592 |
self.module.fail_json(msg=msg) |
| 593 |
else: |
| 594 |
self._exec(['add_user', self.username, self.password or '']) |
| 595 |
if not self.password: |
| 596 |
self._exec(['clear_password', self.username]) |
| 597 |
|
| 598 |
def delete(self): |
| 599 |
if self.login_host is not None: |
| 600 |
response = self.request_users_api('DELETE') |
| 601 |
if response.status_code != 204: |
| 602 |
msg = ("Error trying to remove user %s in rabbitmq. " |
| 603 |
"Status code '%s'.") % (self.username, response.status_code) |
| 604 |
self.module.fail_json(msg=msg) |
| 605 |
else: |
| 606 |
self._exec(['delete_user', self.username]) |
| 607 |
|
| 608 |
def change_password(self): |
| 609 |
if self.login_host is not None: |
| 610 |
data = {"password": self.password or "", "tags": self.tags or ""} |
| 611 |
response = self.request_users_api('PUT', data) |
| 612 |
|
| 613 |
if not response.ok or (response.status_code == 204): |
| 614 |
msg = ("Error trying to set tags for the user %s in rabbitmq. " |
| 615 |
"Status code '%s'.") % (self.username, response.status_code) |
| 616 |
self.module.fail_json(msg=msg) |
| 617 |
else: |
| 618 |
self.module.fail_json( |
| 619 |
msg="Error setting tags for the user", |
| 620 |
status=response.status_code, |
| 621 |
details=response.text |
| 622 |
) |
| 623 |
else: |
| 624 |
if self.password: |
| 625 |
self._exec(['change_password', self.username, self.password]) |
| 626 |
else: |
| 627 |
self._exec(['clear_password', self.username]) |
| 628 |
|
| 629 |
def set_tags(self): |
| 630 |
if self.login_host is not None: |
| 631 |
data = {"password": self.password, "tags": self.treat_tags_for_api() or ""} |
| 632 |
response = self.request_users_api('PUT', data) |
| 633 |
|
| 634 |
if not response.status_code == 204: |
| 635 |
msg = ("Error trying to set tags for the user %s in rabbitmq. " |
| 636 |
"Status code '%s'.") % (self.username, response.status_code) |
| 637 |
self.module.fail_json(msg=msg) |
| 638 |
|
| 639 |
else: |
| 640 |
self._exec(['set_user_tags', self.username] + self.tags) |
| 641 |
|
| 642 |
def set_permissions(self): |
| 643 |
permissions_to_add = list() |
| 644 |
for vhost, permission_dict in self.permissions.items(): |
| 645 |
if permission_dict != self.existing_permissions.get(vhost, {}): |
| 646 |
permissions_to_add.append(permission_dict) |
| 647 |
permissions_to_clear = list() |
| 648 |
for vhost in self.existing_permissions.keys(): |
| 649 |
if vhost not in self.permissions: |
| 650 |
permissions_to_clear.append(vhost) |
| 651 |
|
| 652 |
for vhost in permissions_to_clear: |
| 653 |
if self.login_host is not None: |
| 654 |
response = self.request_permissions_api('DELETE', vhost) |
| 655 |
if response.status_code != 204: |
| 656 |
msg = ("Error trying to remove permission from user %s in rabbitmq. " |
| 657 |
"Status code '%s'.") % (self.username, response.status_code) |
| 658 |
self.module.fail_json(msg=msg) |
| 659 |
else: |
| 660 |
cmd = 'clear_permissions -p {vhost} {username}'.format(username=self.username, vhost=vhost) |
| 661 |
self._exec(cmd.split(' ')) |
| 662 |
for permissions in permissions_to_add: |
| 663 |
if self.login_host is not None: |
| 664 |
response = self.request_permissions_api('PUT', permissions.get('vhost'), |
| 665 |
data=treat_permissions_for_api(permissions)) |
| 666 |
if response.status_code not in (201, 204): |
| 667 |
msg = ("Error trying to add permission to user %s in rabbitmq. " |
| 668 |
"Status code '%s'.") % (self.username, response.status_code) |
| 669 |
self.module.fail_json(msg=msg) |
| 670 |
else: |
| 671 |
cmd = ('set_permissions -p {vhost} {username} {configure} {write} {read}' |
| 672 |
.format(username=self.username, **permissions)) |
| 673 |
self._exec(cmd.split(' ')) |
| 674 |
self.existing_permissions = self._get_permissions() |
| 675 |
|
| 676 |
def set_topic_permissions(self): |
| 677 |
permissions_to_add = list() |
| 678 |
for vhost_exchange, permission_dict in self.topic_permissions.items(): |
| 679 |
if permission_dict != self.existing_topic_permissions.get(vhost_exchange, {}): |
| 680 |
permissions_to_add.append(permission_dict) |
| 681 |
|
| 682 |
permissions_to_clear = list() |
| 683 |
for vhost_exchange in self.existing_topic_permissions.keys(): |
| 684 |
if vhost_exchange not in self.topic_permissions: |
| 685 |
permissions_to_clear.append(vhost_exchange) |
| 686 |
|
| 687 |
for vhost_exchange in permissions_to_clear: |
| 688 |
vhost, exchange = vhost_exchange |
| 689 |
if self.login_host is not None: |
| 690 |
response = self.request_topic_permissions_api('DELETE', vhost) |
| 691 |
if response.status_code != 204: |
| 692 |
msg = ("Error trying to remove topic permission from user %s in rabbitmq. " |
| 693 |
"Status code '%s'.") % (self.username, response.status_code) |
| 694 |
self.module.fail_json(msg=msg) |
| 695 |
else: |
| 696 |
cmd = ('clear_topic_permissions -p {vhost} {username} {exchange}' |
| 697 |
.format(username=self.username, vhost=vhost, exchange=exchange)) |
| 698 |
self._exec(cmd.split(' ')) |
| 699 |
for permissions in permissions_to_add: |
| 700 |
if self.login_host is not None: |
| 701 |
response = self.request_topic_permissions_api('PUT', permissions.get('vhost'), |
| 702 |
data=treat_topic_permissions_for_api(permissions)) |
| 703 |
if response.status_code not in (201, 204): |
| 704 |
msg = ("Error trying to add topic permission to user %s in rabbitmq. " |
| 705 |
"Status code '%s'.") % (self.username, response.status_code) |
| 706 |
self.module.fail_json(msg=msg) |
| 707 |
else: |
| 708 |
cmd = ('set_topic_permissions -p {vhost} {username} {exchange} {write} {read}' |
| 709 |
.format(username=self.username, **permissions)) |
| 710 |
self._exec(cmd.split(' ')) |
| 711 |
self.existing_topic_permissions = self._get_topic_permissions() |
| 712 |
|
| 713 |
def has_tags_modifications(self): |
| 714 |
return set(self.tags) != set(self.existing_tags) |
| 715 |
|
| 716 |
def has_permissions_modifications(self): |
| 717 |
return self.existing_permissions != self.permissions |
| 718 |
|
| 719 |
def has_topic_permissions_modifications(self): |
| 720 |
return self.existing_topic_permissions != self.topic_permissions |
| 721 |
|
| 722 |
def users_api_url_builder(self, username): |
| 723 |
return "%s://%s:%s/api/users/%s" % ( |
| 724 |
self.login_protocol, |
| 725 |
self.login_host, |
| 726 |
self.login_port, |
| 727 |
# Ensure provided data is safe to use in a URL. |
| 728 |
# https://docs.python.org/3/library/urllib.parse.html#url-quoting |
| 729 |
# NOTE: This will also encode '/' characters, as they are required |
| 730 |
# to be percent encoded in the RabbitMQ management API. |
| 731 |
urllib_parse.quote(username, safe=''), |
| 732 |
) |
| 733 |
|
| 734 |
def get_permissions_api_url_builder(self, username): |
| 735 |
return "%s://%s:%s/api/users/%s/permissions" % ( |
| 736 |
self.login_protocol, |
| 737 |
self.login_host, |
| 738 |
self.login_port, |
| 739 |
# Ensure provided data is safe to use in a URL. |
| 740 |
# https://docs.python.org/3/library/urllib.parse.html#url-quoting |
| 741 |
# NOTE: This will also encode '/' characters, as they are required |
| 742 |
# to be percent encoded in the RabbitMQ management API. |
| 743 |
urllib_parse.quote(username, safe=''), |
| 744 |
) |
| 745 |
|
| 746 |
def get_topic_permissions_api_url_builder(self, username): |
| 747 |
return "%s://%s:%s/api/users/%s/topic-permissions" % ( |
| 748 |
self.login_protocol, |
| 749 |
self.login_host, |
| 750 |
self.login_port, |
| 751 |
# Ensure provided data is safe to use in a URL. |
| 752 |
# https://docs.python.org/3/library/urllib.parse.html#url-quoting |
| 753 |
# NOTE: This will also encode '/' characters, as they are required |
| 754 |
# to be percent encoded in the RabbitMQ management API. |
| 755 |
urllib_parse.quote(username, safe=''), |
| 756 |
) |
| 757 |
|
| 758 |
def permissions_api_url_builder(self, username, vhost): |
| 759 |
if vhost is None: |
| 760 |
vhost = "/" |
| 761 |
return "%s://%s:%s/api/permissions/%s/%s" % ( |
| 762 |
self.login_protocol, |
| 763 |
self.login_host, |
| 764 |
self.login_port, |
| 765 |
# Ensure provided data is safe to use in a URL. |
| 766 |
# https://docs.python.org/3/library/urllib.parse.html#url-quoting |
| 767 |
# NOTE: This will also encode '/' characters, as they are required |
| 768 |
# to be percent encoded in the RabbitMQ management API. |
| 769 |
urllib_parse.quote(vhost, safe=''), |
| 770 |
urllib_parse.quote(username, safe=''), |
| 771 |
) |
| 772 |
|
| 773 |
def topic_permissions_api_url_builder(self, username, vhost): |
| 774 |
if vhost is None: |
| 775 |
vhost = "/" |
| 776 |
return "%s://%s:%s/api/topic-permissions/%s/%s" % ( |
| 777 |
self.login_protocol, |
| 778 |
self.login_host, |
| 779 |
self.login_port, |
| 780 |
# Ensure provided data is safe to use in a URL. |
| 781 |
# https://docs.python.org/3/library/urllib.parse.html#url-quoting |
| 782 |
# NOTE: This will also encode '/' characters, as they are required |
| 783 |
# to be percent encoded in the RabbitMQ management API. |
| 784 |
urllib_parse.quote(vhost, safe=''), |
| 785 |
urllib_parse.quote(username, safe=''), |
| 786 |
) |
| 787 |
|
| 788 |
def treat_tags_for_api(self): |
| 789 |
return ','.join(tag for tag in self.tags) |
| 790 |
|
| 791 |
def request_users_api(self, method, data=None): |
| 792 |
try: |
| 793 |
response = requests.request(method, self.users_api_url_builder(self.username), |
| 794 |
auth=(self.login_user, self.login_password), json=data) |
| 795 |
except requests.exceptions.RequestException as exception: |
| 796 |
msg = "Error in HTTP request (method %s) for user %s in rabbitmq." % ( |
| 797 |
method.lower(), |
| 798 |
self.username, |
| 799 |
) |
| 800 |
self.module.fail_json(msg=msg, exception=exception) |
| 801 |
return response |
| 802 |
|
| 803 |
def request_permissions_api(self, method, vhost=None, data=None): |
| 804 |
try: |
| 805 |
response = requests.request(method, self.permissions_api_url_builder(self.username, vhost), |
| 806 |
auth=(self.login_user, self.login_password), json=data) |
| 807 |
except requests.exceptions.RequestException as exception: |
| 808 |
msg = "Error in HTTP request (method %s) for user's permission %s in rabbitmq." % ( |
| 809 |
method.lower(), |
| 810 |
self.username, |
| 811 |
) |
| 812 |
self.module.fail_json(msg=msg, exception=exception) |
| 813 |
return response |
| 814 |
|
| 815 |
def request_topic_permissions_api(self, method, vhost=None, data=None): |
| 816 |
try: |
| 817 |
response = requests.request(method, self.topic_permissions_api_url_builder(self.username, vhost), |
| 818 |
auth=(self.login_user, self.login_password), json=data) |
| 819 |
except requests.exceptions.RequestException as exception: |
| 820 |
msg = "Error in HTTP request (method %s) for topic permission for user %s in rabbitmq." % ( |
| 821 |
method.lower(), |
| 822 |
self.username, |
| 823 |
) |
| 824 |
self.module.fail_json(msg=msg, exception=exception) |
| 825 |
return response |
| 826 |
|
| 827 |
|
| 828 |
def main(): |
| 829 |
arg_spec = dict( |
| 830 |
user=dict(required=True, aliases=['username', 'name']), |
| 831 |
password=dict(default=None, no_log=True), |
| 832 |
tags=dict(default=None), |
| 833 |
permissions=dict(default=list(), type='list', elements='dict'), |
| 834 |
vhost=dict(default='/'), |
| 835 |
configure_priv=dict(default='^$'), |
| 836 |
write_priv=dict(default='^$'), |
| 837 |
read_priv=dict(default='^$'), |
| 838 |
topic_permissions=dict(default=list(), type='list', elements='dict'), |
| 839 |
force=dict(default='no', type='bool'), |
| 840 |
state=dict(default='present', choices=['present', 'absent']), |
| 841 |
node=dict(default='rabbit'), |
| 842 |
update_password=dict(default='on_create', choices=['on_create', 'always'], no_log=False), |
| 843 |
login_protocol=dict(type="str", default="http", choices=["http", "https"]), |
| 844 |
login_host=dict(type="str"), |
| 845 |
login_port=dict(type="str", default="15672"), |
| 846 |
login_user=dict(type="str", no_log=True), |
| 847 |
login_password=dict(type="str", no_log=True) |
| 848 |
) |
| 849 |
module = AnsibleModule( |
| 850 |
argument_spec=arg_spec, |
| 851 |
supports_check_mode=False |
| 852 |
) |
| 853 |
|
| 854 |
username = module.params['user'] |
| 855 |
password = module.params['password'] |
| 856 |
tags = module.params['tags'] |
| 857 |
permissions = module.params['permissions'] |
| 858 |
vhost = module.params['vhost'] |
| 859 |
configure_priv = module.params['configure_priv'] |
| 860 |
write_priv = module.params['write_priv'] |
| 861 |
read_priv = module.params['read_priv'] |
| 862 |
topic_permissions = module.params['topic_permissions'] |
| 863 |
force = module.params['force'] |
| 864 |
state = module.params['state'] |
| 865 |
node = module.params['node'] |
| 866 |
update_password = module.params['update_password'] |
| 867 |
login_protocol = module.params['login_protocol'] |
| 868 |
login_host = module.params['login_host'] |
| 869 |
login_port = module.params['login_port'] |
| 870 |
login_user = module.params['login_user'] |
| 871 |
login_password = module.params['login_password'] |
| 872 |
|
| 873 |
if permissions: |
| 874 |
vhosts = [permission.get('vhost', '/') for permission in permissions] |
| 875 |
if any(vhost_count > 1 for vhost_count in count(vhosts).values()): |
| 876 |
module.fail_json(msg="Error parsing vhost permissions: You can't " |
| 877 |
"have two permission dicts for the same vhost") |
| 878 |
bulk_permissions = True |
| 879 |
else: |
| 880 |
perm = { |
| 881 |
'vhost': vhost, |
| 882 |
'configure_priv': configure_priv, |
| 883 |
'write_priv': write_priv, |
| 884 |
'read_priv': read_priv |
| 885 |
} |
| 886 |
permissions.append(perm) |
| 887 |
bulk_permissions = False |
| 888 |
|
| 889 |
if topic_permissions: |
| 890 |
vhost_exchanges = [ |
| 891 |
(permission.get('vhost', '/'), permission.get('exchange')) |
| 892 |
for permission in topic_permissions |
| 893 |
] |
| 894 |
if any(ve_count > 1 for ve_count in count(vhost_exchanges).values()): |
| 895 |
module.fail_json(msg="Error parsing vhost topic_permissions: You can't " |
| 896 |
"have two topic permission dicts for the same vhost " |
| 897 |
"and the same exchange") |
| 898 |
|
| 899 |
for permission in permissions: |
| 900 |
if not permission['vhost']: |
| 901 |
module.fail_json(msg="Error parsing vhost permissions: You can't " |
| 902 |
"have an empty vhost when setting permissions") |
| 903 |
|
| 904 |
for permission in topic_permissions: |
| 905 |
permission.setdefault('vhost', '/') |
| 906 |
permission.setdefault('exchange', 'amq.topic') |
| 907 |
# Normalize the arguments |
| 908 |
for perm_name in ("read", "write"): |
| 909 |
suffixed_perm_name = "{perm_name}_priv".format(perm_name=perm_name) |
| 910 |
if suffixed_perm_name in permission: |
| 911 |
permission[perm_name] = permission.pop(suffixed_perm_name) |
| 912 |
|
| 913 |
rabbitmq_user = RabbitMqUser(module, username, password, tags, permissions, |
| 914 |
topic_permissions, node, |
| 915 |
bulk_permissions=bulk_permissions, login_protocol=login_protocol, |
| 916 |
login_host=login_host, login_port=login_port, login_user=login_user, |
| 917 |
login_password=login_password) |
| 918 |
|
| 919 |
result = dict(changed=False, user=username, state=state) |
| 920 |
if rabbitmq_user.get(): |
| 921 |
if state == 'absent': |
| 922 |
rabbitmq_user.delete() |
| 923 |
result['changed'] = True |
| 924 |
else: |
| 925 |
if force: |
| 926 |
rabbitmq_user.delete() |
| 927 |
rabbitmq_user.add() |
| 928 |
rabbitmq_user.get() |
| 929 |
result['changed'] = True |
| 930 |
elif update_password == 'always': |
| 931 |
if not rabbitmq_user.check_password(): |
| 932 |
rabbitmq_user.change_password() |
| 933 |
result['changed'] = True |
| 934 |
|
| 935 |
if rabbitmq_user.has_tags_modifications(): |
| 936 |
rabbitmq_user.set_tags() |
| 937 |
result['changed'] = True |
| 938 |
|
| 939 |
if rabbitmq_user.has_permissions_modifications(): |
| 940 |
rabbitmq_user.set_permissions() |
| 941 |
result['changed'] = True |
| 942 |
|
| 943 |
if rabbitmq_user.has_topic_permissions_modifications(): |
| 944 |
rabbitmq_user.set_topic_permissions() |
| 945 |
result['changed'] = True |
| 946 |
elif state == 'present': |
| 947 |
rabbitmq_user.add() |
| 948 |
rabbitmq_user.set_tags() |
| 949 |
rabbitmq_user.set_permissions() |
| 950 |
rabbitmq_user.set_topic_permissions() |
| 951 |
result['changed'] = True |
| 952 |
|
| 953 |
module.exit_json(**result) |
| 954 |
|
| 955 |
|
| 956 |
if __name__ == '__main__': |
| 957 |
main() |