Debian Codegraph @

ansible_collections/community/aws/plugins/modules/mq_broker_config.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_config
10 version_added: 6.0.0
11 short_description: Update Amazon MQ broker configuration
12 description:
13 - Update configuration for an MQ broker.
14 - If new configuration differs from the current one a new configuration
15 is created and the new version is assigned to the broker.
16 - Optionally allows broker reboot to make changes effective immediately.
17 author:
18 - FCO (@fotto)
19 options:
20 broker_id:
21 description:
22 - The ID of the MQ broker to work on.
23 type: str
24 required: true
25 config_xml:
26 description:
27 - The maximum number of results to return.
28 type: str
29 required: true
30 config_description:
31 description:
32 - Description to set on new configuration revision.
33 type: str
34 reboot:
35 description:
36 - Reboot broker after new config has been applied.
37 type: bool
38 default: false
39 extends_documentation_fragment:
40 - amazon.aws.boto3
41 - amazon.aws.common.modules
42 - amazon.aws.region.modules
43 """
44
45 EXAMPLES = r"""
46 - name: send new XML config to broker relying on credentials from environment
47 community.aws.mq_broker_config:
48 broker_id: "aws-mq-broker-id"
49 config_xml: "{{ lookup('file', 'activemq.xml' )}}"
50 region: "{{ aws_region }}"
51
52 - name: send new XML config to broker and reboot if necessary
53 community.aws.mq_broker_config:
54 broker_id: "aws-mq-broker-id"
55 config_xml: "{{ lookup('file', 'activemq2.xml' )}}"
56 reboot: true
57
58 - name: send new broker config and set all credentials explicitly
59 community.aws.mq_broker_config:
60 broker_id: "{{ broker_id }}"
61 config_xml: "{{ lookup('file', 'activemq3.xml')}}"
62 config_description: "custom description for configuration object"
63 register: result
64 """
65
66 RETURN = r"""
67 broker:
68 description: API response of describe_broker() converted to snake yaml after changes have been applied.
69 type: dict
70 returned: success
71 configuration:
72 description: Details about new configuration object.
73 returned: I(changed=true)
74 type: complex
75 contains:
76 id:
77 description: Configuration ID of broker configuration.
78 type: str
79 example: c-386541b8-3139-42c2-9c2c-a4c267c1714f
80 revision:
81 description: Revision of the configuration that will be active after next reboot.
82 type: int
83 example: 4
84 """
85
86 import base64
87 import re
88
89 try:
90 import botocore
91 except ImportError:
92 # handled by AnsibleAWSModule
93 pass
94
95 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
96
97 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
98
99 DEFAULTS = {"reboot": False}
100 FULL_DEBUG = False
101
102
103 def is_same_config(old, new):
104 # we a simple comparision here: strip down spaces and compare the rest
105 # TODO: use same XML normalizer on new as used by AWS before comparing strings
106 old_stripped = re.sub(r"\s+", " ", old, flags=re.S).rstrip()
107 new_stripped = re.sub(r"\s+", " ", new, flags=re.S).rstrip()
108 return old_stripped == new_stripped
109
110
111 def get_broker_info(conn, module):
112 try:
113 return conn.describe_broker(BrokerId=module.params["broker_id"])
114 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
115 if module.check_mode:
116 return {
117 "broker_id": module.params["broker_id"],
118 }
119 module.fail_json_aws(e, msg="Couldn't get broker details.")
120
121
122 def get_current_configuration(conn, module, cfg_id, cfg_revision):
123 try:
124 return conn.describe_configuration_revision(ConfigurationId=cfg_id, ConfigurationRevision=str(cfg_revision))
125 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
126 module.fail_json_aws(e, msg="Couldn't get configuration revision.")
127
128
129 def create_and_assign_config(conn, module, broker_id, cfg_id, cfg_xml_encoded):
130 kwargs = {"ConfigurationId": cfg_id, "Data": cfg_xml_encoded}
131 if "config_description" in module.params and module.params["config_description"]:
132 kwargs["Description"] = module.params["config_description"]
133 else:
134 kwargs["Description"] = "Updated through community.aws.mq_broker_config ansible module"
135 #
136 try:
137 c_response = conn.update_configuration(**kwargs)
138 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
139 module.fail_json_aws(e, msg="Couldn't create new configuration revision.")
140 #
141 new_config_revision = c_response["LatestRevision"]["Revision"]
142 try:
143 b_response = conn.update_broker(
144 BrokerId=broker_id, Configuration={"Id": cfg_id, "Revision": new_config_revision}
145 )
146 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
147 module.fail_json_aws(e, msg="Couldn't assign new configuration revision to broker.")
148 #
149 return (c_response, b_response)
150
151
152 def reboot_broker(conn, module, broker_id):
153 try:
154 return conn.reboot_broker(BrokerId=broker_id)
155 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
156 module.fail_json_aws(e, msg="Couldn't reboot broker.")
157
158
159 def ensure_config(conn, module):
160 broker_id = module.params["broker_id"]
161 broker_info = get_broker_info(conn, module)
162 changed = False
163 if module.check_mode and "Configurations" not in broker_info:
164 # not result from get_broker_info(). use requeste config
165 current_cfg_decoded = module.params["config_xml"]
166 else:
167 current_cfg = broker_info["Configurations"]["Current"]
168 if "Pending" in broker_info["Configurations"]:
169 current_cfg = broker_info["Configurations"]["Pending"]
170 current_cfg_encoded = get_current_configuration(conn, module, current_cfg["Id"], current_cfg["Revision"])[
171 "Data"
172 ]
173 current_cfg_decoded = base64.b64decode(current_cfg_encoded.encode()).decode()
174
175 if is_same_config(current_cfg_decoded, module.params["config_xml"]):
176 return {"changed": changed, "broker": camel_dict_to_snake_dict(broker_info, ignore_list=["Tags"])}
177
178 (c_response, _b_response) = (None, None)
179 if not module.check_mode:
180 new_cfg_encoded = base64.b64encode(module.params["config_xml"].encode()).decode()
181 (c_response, _b_response) = create_and_assign_config(
182 conn, module, broker_id, current_cfg["Id"], new_cfg_encoded
183 )
184 #
185 changed = True
186
187 if changed and module.params["reboot"] and not module.check_mode:
188 reboot_broker(conn, module, broker_id)
189 #
190 broker_info = get_broker_info(conn, module)
191 return_struct = {
192 "changed": changed,
193 "broker": camel_dict_to_snake_dict(broker_info, ignore_list=["Tags"]),
194 "configuration": {"id": c_response["Id"], "revision": c_response["LatestRevision"]["Revision"]},
195 }
196 if FULL_DEBUG:
197 return_struct["old_config_xml"] = base64.b64decode(current_cfg_encoded)
198 return_struct["new_config_xml"] = module.params["config_xml"]
199 return_struct["old_config_revision"] = current_cfg["Revision"]
200 return return_struct
201
202
203 def main():
204 argument_spec = dict(
205 broker_id=dict(required=True, type="str"),
206 config_xml=dict(required=True, type="str"),
207 config_description=dict(required=False, type="str"),
208 reboot=dict(required=False, type="bool", default=DEFAULTS["reboot"]),
209 )
210
211 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
212
213 connection = module.client("mq")
214
215 try:
216 result = ensure_config(connection, module)
217 except botocore.exceptions.ClientError as e:
218 module.fail_json_aws(e)
219
220 module.exit_json(**result)
221
222
223 if __name__ == "__main__":
224 main()