Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/rds_cluster_param_group.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: rds_cluster_param_group
10 version_added: 7.6.0
11 short_description: Manage RDS cluster parameter groups
12 description:
13 - Creates, modifies, and deletes RDS cluster parameter groups.
14 options:
15 state:
16 description:
17 - Specifies whether the RDS cluster parameter group should be present or absent.
18 default: present
19 choices: [ 'present' , 'absent' ]
20 type: str
21 name:
22 description:
23 - The name of the RDS cluster parameter group to create, modify or delete.
24 required: true
25 type: str
26 description:
27 description:
28 - The description for the RDS cluster parameter group.
29 - Required for O(state=present).
30 type: str
31 db_parameter_group_family:
32 description:
33 - The RDS cluster parameter group family name.
34 - An RDS cluster parameter group can be associated with one and only one RDS cluster parameter group family,
35 and can be applied only to a RDS cluster running a database engine and engine version compatible with that RDS cluster parameter group family.
36 - Please use M(amazon.aws.rds_engine_versions_info) module To list all of the available parameter group families for a DB engine.
37 - The RDS cluster parameter group family is immutable and can't be changed when updating a RDS cluster parameter group.
38 See U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbclusterparametergroup.html)
39 - Required for O(state=present).
40 type: str
41 parameters:
42 description:
43 - A list of parameters to update.
44 type: list
45 elements: dict
46 suboptions:
47 parameter_name:
48 description: Specifies the name of the parameter.
49 type: str
50 required: true
51 parameter_value:
52 description:
53 - Specifies the value of the parameter.
54 type: str
55 required: true
56 apply_method:
57 description:
58 - Indicates when to apply parameter updates.
59 choices:
60 - immediate
61 - pending-reboot
62 type: str
63 required: true
64 author:
65 - "Aubin Bikouo (@abikouo)"
66 extends_documentation_fragment:
67 - amazon.aws.common.modules
68 - amazon.aws.region.modules
69 - amazon.aws.tags
70 - amazon.aws.boto3
71 """
72
73 EXAMPLES = r"""
74 - name: Add or change a parameter group, in this case setting authentication_timeout to 200
75 amazon.aws.rds_cluster_param_group:
76 state: present
77 name: test-cluster-group
78 description: 'My test RDS cluster group'
79 db_parameter_group_family: 'mysql5.6'
80 parameters:
81 - parameter_name: authentication_timeout
82 parameter_value: "200"
83 apply_method: immediate
84 tags:
85 Environment: production
86 Application: parrot
87
88 - name: Remove a parameter group
89 amazon.aws.rds_cluster_param_group:
90 state: absent
91 name: test-cluster-group
92 """
93
94 RETURN = r"""
95 db_cluster_parameter_group:
96 description: dictionary containing all the RDS cluster parameter group information.
97 returned: success
98 type: complex
99 contains:
100 db_cluster_parameter_group_arn:
101 description: The Amazon Resource Name (ARN) for the RDS cluster parameter group.
102 type: str
103 returned: when O(state=present)
104 sample: "arn:aws:rds:us-west-2:123456789012:cluster-pg:ansible-test-123456789012-redhat-cluster-param-group"
105 db_cluster_parameter_group_name:
106 description: The name of the RDS cluster parameter group.
107 type: str
108 returned: when O(state=present)
109 sample: "ansible-test-123456789012-redhat-cluster-param-group"
110 db_parameter_group_family:
111 description: The name of the RDS parameter group family that this RDS cluster parameter group is compatible with.
112 type: str
113 returned: when O(state=present)
114 sample: "postgres16"
115 description:
116 description: Provides the customer-specified description for this RDS cluster parameter group.
117 type: str
118 returned: when O(state=present)
119 sample: "RDS cluster param group"
120 tags:
121 description: A dictionary of tags.
122 type: dict
123 returned: when O(state=present)
124 sample: {
125 "another": "tag",
126 "resource_prefix": "ansible-test-53268383-redhat",
127 "some": "tag"
128 }
129 """
130
131 from itertools import zip_longest
132 from typing import Any
133 from typing import Dict
134 from typing import List
135
136 try:
137 import botocore
138 except ImportError:
139 pass # Handled by AnsibleAWSModule
140
141 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
142 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
143
144 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
145 from ansible_collections.amazon.aws.plugins.module_utils.rds import describe_db_cluster_parameter_groups
146 from ansible_collections.amazon.aws.plugins.module_utils.rds import describe_db_cluster_parameters
147 from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags
148 from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags
149 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
150 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
151
152
153 def modify_parameters(
154 module: AnsibleAWSModule, connection: Any, group_name: str, parameters: List[Dict[str, Any]]
155 ) -> bool:
156 current_params = describe_db_cluster_parameters(module, connection, group_name)
157 parameters = snake_dict_to_camel_dict(parameters, capitalize_first=True)
158 # compare current resource parameters with the value from module parameters
159 changed = False
160 for param in parameters:
161 found = False
162 for current_p in current_params:
163 if param.get("ParameterName") == current_p.get("ParameterName"):
164 found = True
165 if not current_p["IsModifiable"]:
166 module.fail_json(f"The parameter {param.get('ParameterName')} cannot be modified")
167 changed |= any((current_p.get(k) != v for k, v in param.items()))
168 if not found:
169 module.fail_json(msg=f"Could not find parameter with name: {param.get('ParameterName')}")
170 if changed:
171 if not module.check_mode:
172 # When calling modify_db_cluster_parameter_group() function
173 # A maximum of 20 parameters can be modified in a single request.
174 # This is why we are creating chunk containing at max 20 items
175 for chunk in zip_longest(*[iter(parameters)] * 20, fillvalue=None):
176 non_empty_chunk = [item for item in chunk if item]
177 try:
178 connection.modify_db_cluster_parameter_group(
179 aws_retry=True, DBClusterParameterGroupName=group_name, Parameters=non_empty_chunk
180 )
181 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
182 module.fail_json_aws(e, msg="Couldn't update RDS cluster parameters")
183 return changed
184
185
186 def ensure_present(module: AnsibleAWSModule, connection: Any) -> None:
187 group_name = module.params["name"]
188 db_parameter_group_family = module.params["db_parameter_group_family"]
189 tags = module.params.get("tags")
190 purge_tags = module.params.get("purge_tags")
191 changed = False
192
193 response = describe_db_cluster_parameter_groups(module=module, connection=connection, group_name=group_name)
194 if not response:
195 # Create RDS cluster parameter group
196 params = dict(
197 DBClusterParameterGroupName=group_name,
198 DBParameterGroupFamily=db_parameter_group_family,
199 Description=module.params["description"],
200 )
201 if tags:
202 params["Tags"] = ansible_dict_to_boto3_tag_list(tags)
203 if module.check_mode:
204 module.exit_json(changed=True, msg="Would have create RDS parameter group if not in check mode.")
205 try:
206 response = connection.create_db_cluster_parameter_group(aws_retry=True, **params)
207 changed = True
208 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
209 module.fail_json_aws(e, msg="Couldn't create parameter group")
210 else:
211 group = response[0]
212 if db_parameter_group_family != group["DBParameterGroupFamily"]:
213 module.warn(
214 "The RDS cluster parameter group family is immutable and can't be changed when updating a RDS cluster parameter group."
215 )
216
217 if tags:
218 existing_tags = get_tags(connection, module, group["DBClusterParameterGroupArn"])
219 changed = ensure_tags(
220 connection, module, group["DBClusterParameterGroupArn"], existing_tags, tags, purge_tags
221 )
222
223 parameters = module.params.get("parameters")
224 if parameters:
225 changed |= modify_parameters(module, connection, group_name, parameters)
226
227 response = describe_db_cluster_parameter_groups(module=module, connection=connection, group_name=group_name)
228 group = camel_dict_to_snake_dict(response[0])
229 group["tags"] = get_tags(connection, module, group["db_cluster_parameter_group_arn"])
230
231 module.exit_json(changed=changed, db_cluster_parameter_group=group)
232
233
234 def ensure_absent(module: AnsibleAWSModule, connection: Any) -> None:
235 group = module.params["name"]
236 response = describe_db_cluster_parameter_groups(module=module, connection=connection, group_name=group)
237 if not response:
238 module.exit_json(changed=False, msg="The RDS cluster parameter group does not exist.")
239
240 if not module.check_mode:
241 try:
242 response = connection.delete_db_cluster_parameter_group(aws_retry=True, DBClusterParameterGroupName=group)
243 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
244 module.fail_json_aws(e, msg="Couldn't delete RDS cluster parameter group")
245 module.exit_json(changed=True)
246
247
248 def main() -> None:
249 argument_spec = dict(
250 state=dict(default="present", choices=["present", "absent"]),
251 name=dict(required=True),
252 db_parameter_group_family=dict(),
253 description=dict(),
254 tags=dict(type="dict", aliases=["resource_tags"]),
255 purge_tags=dict(type="bool", default=True),
256 parameters=dict(
257 type="list",
258 elements="dict",
259 options=dict(
260 parameter_name=dict(required=True),
261 parameter_value=dict(required=True),
262 apply_method=dict(choices=["immediate", "pending-reboot"], required=True),
263 ),
264 ),
265 )
266 module = AnsibleAWSModule(
267 argument_spec=argument_spec,
268 required_if=[["state", "present", ["description", "db_parameter_group_family"]]],
269 supports_check_mode=True,
270 )
271
272 try:
273 connection = module.client("rds", retry_decorator=AWSRetry.jittered_backoff())
274 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
275 module.fail_json_aws(e, msg="Failed to connect to AWS")
276
277 if module.params.get("state") == "present":
278 ensure_present(module=module, connection=connection)
279 else:
280 ensure_absent(module=module, connection=connection)
281
282
283 if __name__ == "__main__":
284 main()