Debian Codegraph @

ansible_collections/community/aws/plugins/modules/mq_broker.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: mq_broker
10 version_added: 6.0.0
11 short_description: MQ broker management
12 description:
13 - Create/update/delete a broker.
14 - Reboot a broker.
15 author:
16 - FCO (@fotto)
17 options:
18 broker_name:
19 description:
20 - The Name of the MQ broker to work on.
21 type: str
22 required: true
23 state:
24 description:
25 - "C(present): Create/update broker."
26 - "C(absent): Delete broker."
27 - "C(restarted): Reboot broker."
28 choices: [ 'present', 'absent', 'restarted' ]
29 default: present
30 type: str
31 deployment_mode:
32 description:
33 - Set broker deployment type.
34 - Can be used only during creation.
35 - Defaults to C(SINGLE_INSTANCE).
36 choices: [ 'SINGLE_INSTANCE', 'ACTIVE_STANDBY_MULTI_AZ', 'CLUSTER_MULTI_AZ' ]
37 type: str
38 use_aws_owned_key:
39 description:
40 - Must be set to C(false) if I(kms_key_id) is provided as well.
41 - Can be used only during creation.
42 - Defaults to C(true).
43 type: bool
44 kms_key_id:
45 description:
46 - Use referenced key to encrypt broker data at rest.
47 - Can be used only during creation.
48 type: str
49 engine_type:
50 description:
51 - Set broker engine type.
52 - Can be used only during creation.
53 - Defaults to C(ACTIVEMQ).
54 choices: [ 'ACTIVEMQ', 'RABBITMQ' ]
55 type: str
56 maintenance_window_start_time:
57 description:
58 - Set maintenance window for automatic minor upgrades.
59 - Can be used only during creation.
60 - Not providing any value means "no maintenance window".
61 type: dict
62 publicly_accessible:
63 description:
64 - Allow/disallow public access.
65 - Can be used only during creation.
66 - Defaults to C(false).
67 type: bool
68 storage_type:
69 description:
70 - Set underlying storage type.
71 - Can be used only during creation.
72 - Defaults to C(EFS).
73 choices: [ 'EBS', 'EFS' ]
74 type: str
75 subnet_ids:
76 description:
77 - Defines where deploy broker instances to.
78 - Minimum required number depends on deployment type.
79 - Can be used only during creation.
80 type: list
81 elements: str
82 users:
83 description:
84 - This parameter allows to use a custom set of initial user(s).
85 - M(community.aws.mq_user) is the preferred way to manage (local) users
86 however a broker cannot be created without any user.
87 - If nothing is specified a default C(admin) user will be created along with brokers.
88 - Can be used only during creation. Use M(community.aws.mq_user) module for updates.
89 type: list
90 elements: dict
91 tags:
92 description:
93 - Tag newly created brokers.
94 - Can be used only during creation.
95 type: dict
96 authentication_strategy:
97 description: Choose between locally and remotely managed users.
98 choices: [ 'SIMPLE', 'LDAP' ]
99 type: str
100 auto_minor_version_upgrade:
101 description: Allow/disallow automatic minor version upgrades.
102 type: bool
103 default: true
104 engine_version:
105 description:
106 - Set engine version of broker.
107 - The special value C(latest) will pick the latest available version.
108 - The special value C(latest) is ignored on update.
109 type: str
110 host_instance_type:
111 description: Instance type of broker instances.
112 type: str
113 enable_audit_log:
114 description: Enable/disable to push audit logs to AWS CloudWatch.
115 type: bool
116 default: false
117 enable_general_log:
118 description: Enable/disable to push general logs to AWS CloudWatch.
119 type: bool
120 default: false
121 security_groups:
122 description:
123 - Associate security groups with broker.
124 - At least one must be provided during creation.
125 type: list
126 elements: str
127 wait:
128 description:
129 - Specifies whether the module waits for the desired C(state).
130 - The time to wait can be controlled by setting I(wait_timeout).
131 type: bool
132 default: false
133 version_added: 7.1.0
134 wait_timeout:
135 description:
136 - How long to wait (in seconds) for the broker to reach the desired state if I(wait=true).
137 default: 900
138 type: int
139 version_added: 7.1.0
140
141 extends_documentation_fragment:
142 - amazon.aws.boto3
143 - amazon.aws.common.modules
144 - amazon.aws.region.modules
145 """
146
147
148 EXAMPLES = r"""
149 - name: create broker (if missing) with minimal required parameters
150 community.aws.mq_broker:
151 broker_name: "{{ broker_name }}"
152 security_groups:
153 - sg_xxxxxxx
154 subnet_ids:
155 - subnet_xxx
156 - subnet_yyy
157 register: result
158
159 - set_fact:
160 broker_id: "{{ result.broker['BrokerId'] }}"
161
162 - name: use mq_broker_info to wait until broker is ready
163 community.aws.mq_broker_info:
164 broker_id: "{{ broker_id }}"
165 register: result
166 until: "result.broker['BrokerState'] == 'RUNNING'"
167 retries: 15
168 delay: 60
169
170 - name: create or update broker with almost all parameter set including credentials
171 community.aws.mq_broker:
172 broker_name: "my_broker_2"
173 state: present
174 deployment_mode: 'ACTIVE_STANDBY_MULTI_AZ'
175 use_aws_owned_key: false
176 kms_key_id: 'my-precreted-key-id'
177 engine_type: 'ACTIVEMQ'
178 maintenance_window_start_time:
179 DayOfWeek: 'MONDAY'
180 TimeOfDay: '03:15'
181 TimeZone: 'Europe/Berlin'
182 publicly_accessible: true
183 storage_type: 'EFS'
184 security_groups:
185 - sg_xxxxxxx
186 subnet_ids:
187 - subnet_xxx
188 - subnet_yyy
189 users:
190 - Username: 'initial-user'
191 Password': 'plain-text-password'
192 ConsoleAccess: true
193 tags:
194 env: Test
195 creator: ansible
196 authentication_strategy: 'SIMPLE'
197 auto_minor_version_upgrade: true
198 engine_version: "5.15.13"
199 host_instance_type: 'mq.t3.micro'
200 enable_audit_log: true
201 enable_general_log: true
202
203 - name: reboot a broker
204 community.aws.mq_broker:
205 broker_name: "my_broker_2"
206 state: restarted
207
208 - name: delete a broker
209 community.aws.mq_broker:
210 broker_name: "my_broker_2"
211 state: absent
212 """
213
214 RETURN = r"""
215 broker:
216 description:
217 - "All API responses are converted to snake yaml except 'Tags'"
218 - "'state=present': API response of create_broker() or update_broker() call"
219 - "'state=absent': result of describe_broker() call before delete_broker() is triggerd"
220 - "'state=restarted': result of describe_broker() after reboot has been triggered"
221 type: dict
222 returned: success
223 """
224
225 try:
226 import botocore
227 except ImportError:
228 # handled by AnsibleAWSModule
229 pass
230
231 from time import sleep
232 from time import time
233
234 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
235
236 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
237
238 PARAMS_MAP = {
239 "authentication_strategy": "AuthenticationStrategy",
240 "auto_minor_version_upgrade": "AutoMinorVersionUpgrade",
241 "broker_name": "BrokerName",
242 "deployment_mode": "DeploymentMode",
243 "use_aws_owned_key": "EncryptionOptions/UseAwsOwnedKey",
244 "kms_key_id": "EncryptionOptions/KmsKeyId",
245 "engine_type": "EngineType",
246 "engine_version": "EngineVersion",
247 "host_instance_type": "HostInstanceType",
248 "enable_audit_log": "Logs/Audit",
249 "enable_general_log": "Logs/General",
250 "maintenance_window_start_time": "MaintenanceWindowStartTime",
251 "publicly_accessible": "PubliclyAccessible",
252 "security_groups": "SecurityGroups",
253 "storage_type": "StorageType",
254 "subnet_ids": "SubnetIds",
255 "users": "Users",
256 "tags": "Tags",
257 }
258
259
260 DEFAULTS = {
261 "authentication_strategy": "SIMPLE",
262 "auto_minor_version_upgrade": False,
263 "deployment_mode": "SINGLE_INSTANCE",
264 "use_aws_owned_key": True,
265 "engine_type": "ACTIVEMQ",
266 "engine_version": "latest",
267 "host_instance_type": "mq.t3.micro",
268 "enable_audit_log": False,
269 "enable_general_log": False,
270 "publicly_accessible": False,
271 "storage_type": "EFS",
272 }
273
274 CREATE_ONLY_PARAMS = [
275 "deployment_mode",
276 "use_aws_owned_key",
277 "kms_key_id",
278 "engine_type",
279 "maintenance_window_start_time",
280 "publicly_accessible",
281 "storage_type",
282 "subnet_ids",
283 "users",
284 "tags",
285 ]
286
287
288 def _set_kwarg(kwargs, key, value):
289 mapped_key = PARAMS_MAP[key]
290 if "/" in mapped_key:
291 key_list = mapped_key.split("/")
292 key_list.reverse()
293 else:
294 key_list = [mapped_key]
295 data = kwargs
296 while len(key_list) > 1:
297 this_key = key_list.pop()
298 if this_key not in data:
299 data[this_key] = {}
300 #
301 data = data[this_key]
302 data[key_list[0]] = value
303
304
305 def _fill_kwargs(module, apply_defaults=True, ignore_create_params=False):
306 kwargs = {}
307 if apply_defaults:
308 for p_name, p_value in DEFAULTS.items():
309 _set_kwarg(kwargs, p_name, p_value)
310 for p_name in module.params:
311 if ignore_create_params and p_name in CREATE_ONLY_PARAMS:
312 # silently ignore CREATE_ONLY_PARAMS on update to
313 # make playbooks idempotent
314 continue
315 if p_name in PARAMS_MAP and module.params[p_name] is not None:
316 _set_kwarg(kwargs, p_name, module.params[p_name])
317 else:
318 # ignore
319 pass
320 return kwargs
321
322
323 def __list_needs_change(current, desired):
324 if len(current) != len(desired):
325 return True
326 for index, value in enumerate(current):
327 if value != desired[index]:
328 return True
329 #
330 return False
331
332
333 def __dict_needs_change(current, desired):
334 # values contained in 'current' but not specified in 'desired' are ignored
335 # value contained in 'desired' but not in 'current' (unsupported attributes) are ignored
336 for key in desired:
337 if key in current:
338 if desired[key] != current[key]:
339 return True
340 #
341 return False
342
343
344 def _needs_change(current, desired):
345 needs_change = False
346 for key in desired:
347 current_value = current[key]
348 desired_value = desired[key]
349 if isinstance(current_value, (int, str, bool)):
350 if current_value != desired_value:
351 needs_change = True
352 break
353 elif isinstance(current_value, list):
354 # assumption: all 'list' type settings we allow changes for have scalar values
355 if __list_needs_change(current_value, desired_value):
356 needs_change = True
357 break
358 elif isinstance(current_value, dict):
359 # assumption: all 'dict' type settings we allow changes for have scalar values
360 if __dict_needs_change(current_value, desired_value):
361 needs_change = True
362 break
363 else:
364 # unexpected type
365 needs_change = True
366 break
367 #
368 return needs_change
369
370
371 def get_latest_engine_version(conn, module, engine_type):
372 try:
373 response = conn.describe_broker_engine_types(EngineType=engine_type)
374 return response["BrokerEngineTypes"][0]["EngineVersions"][0]["Name"]
375 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
376 module.fail_json_aws(e, msg="Couldn't list engine versions")
377
378
379 def get_broker_id(conn, module):
380 try:
381 broker_name = module.params["broker_name"]
382 broker_id = None
383 response = conn.list_brokers(MaxResults=100)
384 for broker in response["BrokerSummaries"]:
385 if broker["BrokerName"] == broker_name:
386 broker_id = broker["BrokerId"]
387 break
388 return broker_id
389 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
390 module.fail_json_aws(e, msg="Couldn't list broker brokers.")
391
392
393 def get_broker_info(conn, module, broker_id):
394 try:
395 return conn.describe_broker(BrokerId=broker_id)
396 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
397 module.fail_json_aws(e, msg="Couldn't get broker details.")
398
399
400 def wait_for_status(conn, module):
401 interval_secs = 5
402 timeout = module.params.get("wait_timeout", 900)
403 broker_name = module.params.get("broker_name")
404 desired_state = module.params.get("state")
405 done = False
406
407 paginator = conn.get_paginator("list_brokers")
408 page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 100, "PageSize": 100, "StartingToken": ""})
409 wait_timeout = time() + timeout
410
411 while wait_timeout > time():
412 try:
413 filtered_iterator = page_iterator.search(f"BrokerSummaries[?BrokerName == `{broker_name}`][]")
414 broker_list = list(filtered_iterator)
415
416 if module.check_mode:
417 return
418
419 if len(broker_list) < 1 and desired_state == "absent":
420 done = True
421 break
422
423 if desired_state in ["present", "rebooted"] and broker_list[0]["BrokerState"] == "RUNNING":
424 done = True
425 break
426
427 if broker_list[0]["BrokerState"] == "CREATION_FAILED":
428 break
429
430 sleep(interval_secs)
431
432 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
433 module.fail_json_aws(e, msg="Couldn't paginate brokers.")
434
435 if not done:
436 module.fail_json(msg="desired state not reached")
437
438
439 def reboot_broker(conn, module, broker_id):
440 wait = module.params.get("wait")
441
442 try:
443 response = conn.reboot_broker(BrokerId=broker_id)
444 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
445 module.fail_json_aws(e, msg="Couldn't reboot broker.")
446
447 if wait:
448 wait_for_status(conn, module)
449
450 return response
451
452
453 def delete_broker(conn, module, broker_id):
454 wait = module.params.get("wait")
455
456 try:
457 response = conn.delete_broker(BrokerId=broker_id)
458 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
459 module.fail_json_aws(e, msg="Couldn't delete broker.")
460
461 if wait:
462 wait_for_status(conn, module)
463
464 return response
465
466
467 def create_broker(conn, module):
468 kwargs = _fill_kwargs(module)
469 wait = module.params.get("wait")
470
471 if "EngineVersion" in kwargs and kwargs["EngineVersion"] == "latest":
472 kwargs["EngineVersion"] = get_latest_engine_version(conn, module, kwargs["EngineType"])
473 if kwargs["AuthenticationStrategy"] == "LDAP":
474 module.fail_json(msg="'AuthenticationStrategy=LDAP' not supported, yet")
475 if "Users" not in kwargs:
476 # add some stupid default (cannot create broker without any users)
477 kwargs["Users"] = [{"Username": "admin", "Password": "adminPassword", "ConsoleAccess": True, "Groups": []}]
478 if "EncryptionOptions" in kwargs and "UseAwsOwnedKey" in kwargs["EncryptionOptions"]:
479 kwargs["EncryptionOptions"]["UseAwsOwnedKey"] = False
480 #
481 if "SecurityGroups" not in kwargs or len(kwargs["SecurityGroups"]) == 0:
482 module.fail_json(msg="At least one security group must be specified on broker creation")
483 #
484 changed = True
485 result = conn.create_broker(**kwargs)
486 #
487 if wait:
488 wait_for_status(conn, module)
489
490 return {"broker": camel_dict_to_snake_dict(result, ignore_list=["Tags"]), "changed": changed}
491
492
493 def update_broker(conn, module, broker_id):
494 kwargs = _fill_kwargs(module, apply_defaults=False, ignore_create_params=True)
495 wait = module.params.get("wait")
496 # replace name with id
497 broker_name = kwargs["BrokerName"]
498 del kwargs["BrokerName"]
499 kwargs["BrokerId"] = broker_id
500 # get current state for comparison:
501 api_result = get_broker_info(conn, module, broker_id)
502 if api_result["BrokerState"] != "RUNNING":
503 module.fail_json(
504 msg=f"Cannot trigger update while broker ({broker_id}) is in state {api_result['BrokerState']}",
505 )
506 # engine version of 'latest' is taken as "keep current one"
507 # i.e. do not request upgrade on playbook rerun
508 if "EngineVersion" in kwargs and kwargs["EngineVersion"] == "latest":
509 kwargs["EngineVersion"] = api_result["EngineVersion"]
510 result = {"broker_id": broker_id, "broker_name": broker_name}
511 changed = False
512 if _needs_change(api_result, kwargs):
513 changed = True
514 if not module.check_mode:
515 api_result = conn.update_broker(**kwargs)
516 #
517 #
518 if wait:
519 wait_for_status(conn, module)
520
521 return {"broker": result, "changed": changed}
522
523
524 def ensure_absent(conn, module):
525 result = {"broker_name": module.params["broker_name"], "broker_id": None}
526 if module.check_mode:
527 return {"broker": camel_dict_to_snake_dict(result, ignore_list=["Tags"]), "changed": True}
528 broker_id = get_broker_id(conn, module)
529 result["broker_id"] = broker_id
530
531 if not broker_id:
532 # silently ignore delete of unknown broker (to make it idempotent)
533 return {"broker": result, "changed": False}
534
535 try:
536 # check for pending delete (small race condition possible here
537 api_result = get_broker_info(conn, module, broker_id)
538 if api_result["BrokerState"] == "DELETION_IN_PROGRESS":
539 return {"broker": result, "changed": False}
540 delete_broker(conn, module, broker_id)
541 except botocore.exceptions.ClientError as e:
542 module.fail_json_aws(e)
543
544 return {"broker": result, "changed": True}
545
546
547 def ensure_present(conn, module):
548 if module.check_mode:
549 return {"broker": {"broker_arn": "fakeArn", "broker_id": "fakeId"}, "changed": True}
550
551 broker_id = get_broker_id(conn, module)
552 if broker_id:
553 return update_broker(conn, module, broker_id)
554
555 return create_broker(conn, module)
556
557
558 def main():
559 argument_spec = dict(
560 broker_name=dict(required=True, type="str"),
561 state=dict(default="present", choices=["present", "absent", "restarted"]),
562 wait=dict(default=False, type="bool"),
563 wait_timeout=dict(default=900, type="int"),
564 # parameters only allowed on create
565 deployment_mode=dict(choices=["SINGLE_INSTANCE", "ACTIVE_STANDBY_MULTI_AZ", "CLUSTER_MULTI_AZ"]),
566 use_aws_owned_key=dict(type="bool"),
567 kms_key_id=dict(type="str"),
568 engine_type=dict(choices=["ACTIVEMQ", "RABBITMQ"], type="str"),
569 maintenance_window_start_time=dict(type="dict"),
570 publicly_accessible=dict(type="bool"),
571 storage_type=dict(choices=["EBS", "EFS"]),
572 subnet_ids=dict(type="list", elements="str"),
573 users=dict(type="list", elements="dict"),
574 tags=dict(type="dict"),
575 # parameters allowed on update as well
576 authentication_strategy=dict(choices=["SIMPLE", "LDAP"]),
577 auto_minor_version_upgrade=dict(default=True, type="bool"),
578 engine_version=dict(type="str"),
579 host_instance_type=dict(type="str"),
580 enable_audit_log=dict(default=False, type="bool"),
581 enable_general_log=dict(default=False, type="bool"),
582 security_groups=dict(type="list", elements="str"),
583 )
584
585 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
586
587 connection = module.client("mq")
588
589 if module.params["state"] == "present":
590 try:
591 compound_result = ensure_present(connection, module)
592 except botocore.exceptions.ClientError as e:
593 module.fail_json_aws(e)
594 #
595 module.exit_json(**compound_result)
596
597 if module.params["state"] == "absent":
598 try:
599 compound_result = ensure_absent(connection, module)
600 except botocore.exceptions.ClientError as e:
601 module.fail_json_aws(e)
602 #
603 module.exit_json(**compound_result)
604
605 if module.params["state"] == "restarted":
606 broker_id = get_broker_id(connection, module)
607 if module.check_mode:
608 module.exit_json(broker={"broker_id": broker_id if broker_id else "fakeId"}, changed=True)
609 if not broker_id:
610 module.fail_json(
611 msg="Cannot find broker with name {module.params['broker_name']}.",
612 )
613 try:
614 changed = True
615 if not module.check_mode:
616 reboot_broker(connection, module, broker_id)
617 #
618 result = get_broker_info(connection, module, broker_id)
619 except botocore.exceptions.ClientError as e:
620 module.fail_json_aws(e)
621 module.exit_json(broker=result, changed=changed)
622
623
624 if __name__ == "__main__":
625 main()