Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/rds_subnet_group.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: 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_subnet_group
10 version_added: 5.0.0
11 short_description: manage RDS database subnet groups
12 description:
13 - Creates, modifies, and deletes RDS database subnet groups.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 options:
16 state:
17 description:
18 - Specifies whether the subnet should be present or absent.
19 required: true
20 choices: [ 'present' , 'absent' ]
21 type: str
22 name:
23 description:
24 - Database subnet group identifier.
25 required: true
26 type: str
27 description:
28 description:
29 - Database subnet group description.
30 - Required when I(state=present).
31 type: str
32 subnets:
33 description:
34 - List of subnet IDs that make up the database subnet group.
35 - Required when O(state=present).
36 type: list
37 elements: str
38 notes:
39 - Support for O(tags) and O(purge_tags) was added in release 3.2.0.
40 author:
41 - "Scott Anderson (@tastychutney)"
42 - "Alina Buzachis (@alinabuzachis)"
43 extends_documentation_fragment:
44 - amazon.aws.common.modules
45 - amazon.aws.region.modules
46 - amazon.aws.tags
47 - amazon.aws.boto3
48 """
49
50 EXAMPLES = r"""
51 - name: Add or change a subnet group
52 amazon.aws.rds_subnet_group:
53 state: present
54 name: norwegian-blue
55 description: My Fancy Ex Parrot Subnet Group
56 subnets:
57 - subnet-aaaaaaaa
58 - subnet-bbbbbbbb
59
60 - name: Add or change a subnet group and associate tags
61 amazon.aws.rds_subnet_group:
62 state: present
63 name: norwegian-blue
64 description: My Fancy Ex Parrot Subnet Group
65 subnets:
66 - subnet-aaaaaaaa
67 - subnet-bbbbbbbb
68 tags:
69 tag1: Tag1
70 tag2: Tag2
71
72 - name: Remove a subnet group
73 amazon.aws.rds_subnet_group:
74 state: absent
75 name: norwegian-blue
76 """
77
78 RETURN = r"""
79 changed:
80 description: True if listing the RDS subnet group succeeds.
81 type: bool
82 returned: always
83 sample: false
84 subnet_group:
85 description: Dictionary of DB subnet group values,
86 returned: O(state=present)
87 type: complex
88 contains:
89 name:
90 description: The name of the DB subnet group (maintained for backward compatibility).
91 returned: O(state=present)
92 type: str
93 sample: "ansible-test-mbp-13950442"
94 db_subnet_group_name:
95 description: The name of the DB subnet group.
96 returned: O(state=present)
97 type: str
98 sample: "ansible-test-mbp-13950442"
99 description:
100 description: The description of the DB subnet group (maintained for backward compatibility).
101 returned: O(state=present)
102 type: str
103 sample: "Simple description."
104 db_subnet_group_description:
105 description: The description of the DB subnet group.
106 returned: O(state=present)
107 type: str
108 sample: "Simple description."
109 vpc_id:
110 description: The VPC Id of the DB subnet group.
111 returned: O(state=present)
112 type: str
113 sample: "vpc-0acb0ba033ff2119c"
114 subnet_ids:
115 description: Contains a list of Subnet IDs.
116 returned: O(state=present)
117 type: list
118 sample:
119 "subnet-08c94870f4480797e"
120 subnets:
121 description: Contains a list of Subnet elements (@see https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_subnet_groups). # noqa
122 returned: O(state=present)
123 type: list
124 contains:
125 subnet_availability_zone:
126 description: Contains Availability Zone information.
127 returned: O(state=present)
128 type: dict
129 version_added: 3.2.0
130 version_added_collection: community.aws
131 sample:
132 name: "eu-north-1b"
133 subnet_identifier:
134 description: The identifier of the subnet.
135 returned: O(state=present)
136 type: str
137 version_added: 3.2.0
138 version_added_collection: community.aws
139 sample: "subnet-08c94870f4480797e"
140 subnet_outpost:
141 description: This value specifies the Outpost.
142 returned: O(state=present)
143 type: dict
144 version_added: 3.2.0
145 version_added_collection: community.aws
146 sample: {}
147 subnet_status:
148 description: The status of the subnet.
149 returned: O(state=present)
150 type: str
151 version_added: 3.2.0
152 version_added_collection: community.aws
153 sample: "Active"
154 status:
155 description: The status of the DB subnet group (maintained for backward compatibility).
156 returned: O(state=present)
157 type: str
158 sample: "Complete"
159 subnet_group_status:
160 description: The status of the DB subnet group.
161 returned: O(state=present)
162 type: str
163 sample: "Complete"
164 db_subnet_group_arn:
165 description: The ARN of the DB subnet group.
166 returned: O(state=present)
167 type: str
168 sample: "arn:aws:rds:eu-north-1:123456789012:subgrp:ansible-test-13950442"
169 tags:
170 description: The tags associated with the subnet group.
171 returned: O(state=present)
172 type: dict
173 version_added: 3.2.0
174 version_added_collection: community.aws
175 sample:
176 tag1: Tag1
177 tag2: Tag2
178 """
179
180 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
181
182 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
183 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
184 from ansible_collections.amazon.aws.plugins.module_utils.rds import ensure_tags
185 from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags
186 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
187 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
188
189 try:
190 import botocore
191 except ImportError:
192 pass # Handled by AnsibleAWSModule
193
194
195 def create_result(changed, subnet_group=None):
196 if subnet_group is None:
197 return dict(changed=changed)
198 result_subnet_group = dict(subnet_group)
199 result_subnet_group["name"] = result_subnet_group.get("db_subnet_group_name")
200 result_subnet_group["description"] = result_subnet_group.get("db_subnet_group_description")
201 result_subnet_group["status"] = result_subnet_group.get("subnet_group_status")
202 result_subnet_group["subnet_ids"] = create_subnet_list(subnet_group.get("subnets"))
203 return dict(changed=changed, subnet_group=result_subnet_group)
204
205
206 @AWSRetry.jittered_backoff()
207 def _describe_db_subnet_groups_with_backoff(client, **kwargs):
208 paginator = client.get_paginator("describe_db_subnet_groups")
209 return paginator.paginate(**kwargs).build_full_result()
210
211
212 def get_subnet_group(client, module):
213 params = dict()
214 params["DBSubnetGroupName"] = module.params.get("name").lower()
215
216 try:
217 _result = _describe_db_subnet_groups_with_backoff(client, **params)
218 except is_boto3_error_code("DBSubnetGroupNotFoundFault"):
219 return None
220 except (
221 botocore.exceptions.ClientError,
222 botocore.exceptions.BotoCoreError,
223 ) as e: # pylint: disable=duplicate-except
224 module.fail_json_aws(e, msg="Couldn't describe subnet groups.")
225
226 if _result:
227 result = camel_dict_to_snake_dict(_result["DBSubnetGroups"][0])
228 result["tags"] = get_tags(client, module, result["db_subnet_group_arn"])
229
230 return result
231
232
233 def create_subnet_list(subnets):
234 r"""
235 Construct a list of subnet ids from a list of subnets dicts returned by boto3.
236 Parameters:
237 subnets (list): A list of subnets definitions.
238 @see https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_subnet_groups
239 Returns:
240 (list): List of subnet ids (str)
241 """
242 subnets_ids = []
243 for subnet in subnets:
244 subnets_ids.append(subnet.get("subnet_identifier"))
245 return subnets_ids
246
247
248 def main():
249 argument_spec = dict(
250 state=dict(required=True, choices=["present", "absent"]),
251 name=dict(required=True),
252 description=dict(required=False),
253 subnets=dict(required=False, type="list", elements="str"),
254 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
255 purge_tags=dict(type="bool", default=True),
256 )
257 required_if = [("state", "present", ["description", "subnets"])]
258
259 module = AnsibleAWSModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True)
260
261 state = module.params.get("state")
262 group_name = module.params.get("name").lower()
263 group_description = module.params.get("description")
264 group_subnets = module.params.get("subnets") or []
265
266 try:
267 connection = module.client("rds", retry_decorator=AWSRetry.jittered_backoff())
268 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
269 module.fail_json_aws(e, "Failed to instantiate AWS connection.")
270
271 # Default.
272 changed = None
273 result = create_result(False)
274 tags_update = False
275 subnet_update = False
276
277 if module.params.get("tags") is not None:
278 _tags = ansible_dict_to_boto3_tag_list(module.params.get("tags"))
279 else:
280 _tags = list()
281
282 matching_groups = get_subnet_group(connection, module)
283
284 if state == "present":
285 if matching_groups:
286 # We have one or more subnets at this point.
287
288 # Check if there is any tags update
289 tags_update = ensure_tags(
290 connection,
291 module,
292 matching_groups["db_subnet_group_arn"],
293 matching_groups["tags"],
294 module.params.get("tags"),
295 module.params["purge_tags"],
296 )
297
298 # Sort the subnet groups before we compare them
299 existing_subnets = create_subnet_list(matching_groups["subnets"])
300 existing_subnets.sort()
301 group_subnets.sort()
302
303 # See if anything changed.
304 if (
305 matching_groups["db_subnet_group_name"] != group_name
306 or matching_groups["db_subnet_group_description"] != group_description
307 or existing_subnets != group_subnets
308 ):
309 if not module.check_mode:
310 # Modify existing group.
311 try:
312 connection.modify_db_subnet_group(
313 aws_retry=True,
314 DBSubnetGroupName=group_name,
315 DBSubnetGroupDescription=group_description,
316 SubnetIds=group_subnets,
317 )
318 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
319 module.fail_json_aws(e, "Failed to update a subnet group.")
320 subnet_update = True
321 else:
322 if not module.check_mode:
323 try:
324 connection.create_db_subnet_group(
325 aws_retry=True,
326 DBSubnetGroupName=group_name,
327 DBSubnetGroupDescription=group_description,
328 SubnetIds=group_subnets,
329 Tags=_tags,
330 )
331 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
332 module.fail_json_aws(e, "Failed to create a new subnet group.")
333 subnet_update = True
334 elif state == "absent":
335 if not module.check_mode:
336 try:
337 connection.delete_db_subnet_group(aws_retry=True, DBSubnetGroupName=group_name)
338 except is_boto3_error_code("DBSubnetGroupNotFoundFault"):
339 module.exit_json(**result)
340 except (
341 botocore.exceptions.BotoCoreError,
342 botocore.exceptions.ClientError,
343 ) as e: # pylint: disable=duplicate-except
344 module.fail_json_aws(e, "Failed to delete a subnet group.")
345 else:
346 subnet_group = get_subnet_group(connection, module)
347 if subnet_group:
348 subnet_update = True
349 result = create_result(subnet_update, subnet_group)
350 module.exit_json(**result)
351
352 subnet_update = True
353
354 subnet_group = get_subnet_group(connection, module)
355 changed = tags_update or subnet_update
356 result = create_result(changed, subnet_group)
357 module.exit_json(**result)
358
359
360 if __name__ == "__main__":
361 main()