Debian Codegraph @

ansible_collections/community/aws/plugins/modules/dms_endpoint.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: dms_endpoint
10 version_added: 1.0.0
11 short_description: Creates or destroys a data migration services endpoint
12 description:
13 - Creates or destroys a data migration services endpoint,
14 that can be used to replicate data.
15 options:
16 state:
17 description:
18 - State of the endpoint.
19 default: present
20 choices: ['present', 'absent']
21 type: str
22 endpointidentifier:
23 description:
24 - An identifier name for the endpoint.
25 type: str
26 required: true
27 endpointtype:
28 description:
29 - Type of endpoint we want to manage.
30 - Required when I(state=present).
31 choices: ['source', 'target']
32 type: str
33 enginename:
34 description:
35 - Database engine that we want to use, please refer to
36 the AWS DMS for more information on the supported
37 engines and their limitations.
38 - Required when I(state=present).
39 choices: ['mysql', 'oracle', 'postgres', 'mariadb', 'aurora',
40 'redshift', 's3', 'db2', 'azuredb', 'sybase',
41 'dynamodb', 'mongodb', 'sqlserver']
42 type: str
43 username:
44 description:
45 - Username our endpoint will use to connect to the database.
46 type: str
47 password:
48 description:
49 - Password used to connect to the database
50 this attribute can only be written
51 the AWS API does not return this parameter.
52 type: str
53 servername:
54 description:
55 - Servername that the endpoint will connect to.
56 type: str
57 port:
58 description:
59 - TCP port for access to the database.
60 type: int
61 databasename:
62 description:
63 - Name for the database on the origin or target side.
64 type: str
65 extraconnectionattributes:
66 description:
67 - Extra attributes for the database connection, the AWS documentation
68 states " For more information about extra connection attributes,
69 see the documentation section for your data store."
70 type: str
71 kmskeyid:
72 description:
73 - Encryption key to use to encrypt replication storage and
74 connection information.
75 type: str
76 tags:
77 description:
78 - A list of tags to add to the endpoint.
79 type: dict
80 certificatearn:
81 description:
82 - Amazon Resource Name (ARN) for the certificate.
83 type: str
84 sslmode:
85 description:
86 - Mode used for the SSL connection.
87 default: none
88 choices: ['none', 'require', 'verify-ca', 'verify-full']
89 type: str
90 serviceaccessrolearn:
91 description:
92 - Amazon Resource Name (ARN) for the service access role that you
93 want to use to create the endpoint.
94 type: str
95 externaltabledefinition:
96 description:
97 - The external table definition.
98 type: str
99 dynamodbsettings:
100 description:
101 - Settings in JSON format for the target Amazon DynamoDB endpoint
102 if source or target is dynamodb.
103 type: dict
104 s3settings:
105 description:
106 - S3 buckets settings for the target Amazon S3 endpoint.
107 type: dict
108 dmstransfersettings:
109 description:
110 - The settings in JSON format for the DMS transfer type of
111 source endpoint.
112 type: dict
113 mongodbsettings:
114 description:
115 - Settings in JSON format for the source MongoDB endpoint.
116 type: dict
117 kinesissettings:
118 description:
119 - Settings in JSON format for the target Amazon Kinesis
120 Data Streams endpoint.
121 type: dict
122 elasticsearchsettings:
123 description:
124 - Settings in JSON format for the target Elasticsearch endpoint.
125 type: dict
126 wait:
127 description:
128 - Whether Ansible should wait for the object to be deleted when I(state=absent).
129 type: bool
130 default: false
131 timeout:
132 description:
133 - Time in seconds we should wait for when deleting a resource.
134 - Required when I(wait=true).
135 type: int
136 retries:
137 description:
138 - number of times we should retry when deleting a resource
139 - Required when I(wait=true).
140 type: int
141 author:
142 - "Rui Moreira (@ruimoreira)"
143 extends_documentation_fragment:
144 - amazon.aws.common.modules
145 - amazon.aws.region.modules
146 - amazon.aws.boto3
147 - amazon.aws.tags
148 """
149
150 EXAMPLES = r"""
151 # Note: These examples do not set authentication details
152 - name: Endpoint Creation
153 community.aws.dms_endpoint:
154 state: absent
155 endpointidentifier: 'testsource'
156 endpointtype: source
157 enginename: aurora
158 username: testing1
159 password: testint1234
160 servername: testing.domain.com
161 port: 3306
162 databasename: 'testdb'
163 sslmode: none
164 wait: false
165 """
166
167 RETURN = r"""
168 endpoint:
169 description:
170 - A description of the DMS endpoint.
171 returned: success
172 type: dict
173 contains:
174 database_name:
175 description:
176 - The name of the database at the endpoint.
177 type: str
178 returned: success
179 example: "exampledb"
180 endpoint_arn:
181 description:
182 - The ARN that uniquely identifies the endpoint.
183 type: str
184 returned: success
185 example: "arn:aws:dms:us-east-1:123456789012:endpoint:1234556789ABCDEFGHIJKLMNOPQRSTUVWXYZ012"
186 endpoint_identifier:
187 description:
188 - The database endpoint identifier.
189 type: str
190 returned: success
191 example: "ansible-test-12345678-dms"
192 endpoint_type:
193 description:
194 - The type of endpoint. Valid values are C(SOURCE) and C(TARGET).
195 type: str
196 returned: success
197 example: "SOURCE"
198 engine_display_name:
199 description:
200 - The expanded name for the engine name.
201 type: str
202 returned: success
203 example: "Amazon Aurora MySQL"
204 engine_name:
205 description:
206 - The database engine name.
207 type: str
208 returned: success
209 example: "aurora"
210 kms_key_id:
211 description:
212 - An KMS key ID that is used to encrypt the connection parameters for the endpoint.
213 type: str
214 returned: success
215 example: "arn:aws:kms:us-east-1:123456789012:key/01234567-abcd-12ab-98fe-123456789abc"
216 port:
217 description:
218 - The port used to access the endpoint.
219 type: str
220 returned: success
221 example: 3306
222 server_name:
223 description:
224 - The name of the server at the endpoint.
225 type: str
226 returned: success
227 example: "ansible-test-123456789.example.com"
228 ssl_mode:
229 description:
230 - The SSL mode used to connect to the endpoint.
231 type: str
232 returned: success
233 example: "none"
234 tags:
235 description:
236 - A dictionary representing the tags attached to the endpoint.
237 type: dict
238 returned: success
239 example: {"MyTagKey": "MyTagValue"}
240 username:
241 description:
242 - The user name used to connect to the endpoint.
243 type: str
244 returned: success
245 example: "example-username"
246 dms_transfer_settings:
247 description:
248 - Additional transfer related settings.
249 type: dict
250 returned: when additional DMS Transfer settings have been configured.
251 s3_settings:
252 description:
253 - Additional settings for S3 endpoints.
254 type: dict
255 returned: when the I(endpoint_type) is C(s3)
256 mongo_db_settings:
257 description:
258 - Additional settings for MongoDB endpoints.
259 type: dict
260 returned: when the I(endpoint_type) is C(mongodb)
261 kinesis_settings:
262 description:
263 - Additional settings for Kinesis endpoints.
264 type: dict
265 returned: when the I(endpoint_type) is C(kinesis)
266 kafka_settings:
267 description:
268 - Additional settings for Kafka endpoints.
269 type: dict
270 returned: when the I(endpoint_type) is C(kafka)
271 elasticsearch_settings:
272 description:
273 - Additional settings for Elasticsearch endpoints.
274 type: dict
275 returned: when the I(endpoint_type) is C(elasticsearch)
276 neptune_settings:
277 description:
278 - Additional settings for Amazon Neptune endpoints.
279 type: dict
280 returned: when the I(endpoint_type) is C(neptune)
281 redshift_settings:
282 description:
283 - Additional settings for Redshift endpoints.
284 type: dict
285 returned: when the I(endpoint_type) is C(redshift)
286 postgre_sql_settings:
287 description:
288 - Additional settings for PostgrSQL endpoints.
289 type: dict
290 returned: when the I(endpoint_type) is C(postgres)
291 my_sql_settings:
292 description:
293 - Additional settings for MySQL endpoints.
294 type: dict
295 returned: when the I(endpoint_type) is C(mysql)
296 oracle_settings:
297 description:
298 - Additional settings for Oracle endpoints.
299 type: dict
300 returned: when the I(endpoint_type) is C(oracle)
301 sybase_settings:
302 description:
303 - Additional settings for Sybase endpoints.
304 type: dict
305 returned: when the I(endpoint_type) is C(sybase)
306 microsoft_sql_server_settings:
307 description:
308 - Additional settings for Microsoft SQL Server endpoints.
309 type: dict
310 returned: when the I(endpoint_type) is C(sqlserver)
311 i_b_m_db_settings:
312 description:
313 - Additional settings for IBM DB2 endpoints.
314 type: dict
315 returned: when the I(endpoint_type) is C(db2)
316 doc_db_settings:
317 description:
318 - Additional settings for DocumentDB endpoints.
319 type: dict
320 returned: when the I(endpoint_type) is C(documentdb)
321 redis_settings:
322 description:
323 - Additional settings for Redis endpoints.
324 type: dict
325 returned: when the I(endpoint_type) is C(redshift)
326 """
327
328 try:
329 import botocore
330 except ImportError:
331 pass # caught by AnsibleAWSModule
332
333 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
334
335 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
336 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
337 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
338 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
339 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
340
341 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
342
343 backoff_params = dict(retries=5, delay=1, backoff=1.5)
344
345
346 @AWSRetry.jittered_backoff(**backoff_params)
347 def dms_describe_tags(connection, **params):
348 """checks if the endpoint exists"""
349 tags = connection.list_tags_for_resource(**params).get("TagList", [])
350 return boto3_tag_list_to_ansible_dict(tags)
351
352
353 @AWSRetry.jittered_backoff(**backoff_params)
354 def dms_describe_endpoints(connection, **params):
355 try:
356 endpoints = connection.describe_endpoints(**params)
357 except is_boto3_error_code("ResourceNotFoundFault"):
358 return None
359 return endpoints.get("Endpoints", None)
360
361
362 def describe_endpoint(connection, endpoint_identifier):
363 """checks if the endpoint exists"""
364 endpoint_filter = dict(Name="endpoint-id", Values=[endpoint_identifier])
365 try:
366 endpoints = dms_describe_endpoints(connection, Filters=[endpoint_filter])
367 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
368 module.fail_json_aws(e, msg="Failed to describe the DMS endpoint.")
369
370 if not endpoints:
371 return None
372
373 endpoint = endpoints[0]
374 try:
375 tags = dms_describe_tags(connection, ResourceArn=endpoint["EndpointArn"])
376 endpoint["tags"] = tags
377 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
378 module.fail_json_aws(e, msg="Failed to describe the DMS endpoint tags")
379 return endpoint
380
381
382 @AWSRetry.jittered_backoff(**backoff_params)
383 def dms_delete_endpoint(client, **params):
384 """deletes the DMS endpoint based on the EndpointArn"""
385 if module.params.get("wait"):
386 return delete_dms_endpoint(client)
387 else:
388 return client.delete_endpoint(**params)
389
390
391 @AWSRetry.jittered_backoff(**backoff_params)
392 def dms_create_endpoint(client, **params):
393 """creates the DMS endpoint"""
394 return client.create_endpoint(**params)
395
396
397 @AWSRetry.jittered_backoff(**backoff_params)
398 def dms_modify_endpoint(client, **params):
399 """updates the endpoint"""
400 return client.modify_endpoint(**params)
401
402
403 @AWSRetry.jittered_backoff(**backoff_params)
404 def get_endpoint_deleted_waiter(client):
405 return client.get_waiter("endpoint_deleted")
406
407
408 @AWSRetry.jittered_backoff(**backoff_params)
409 def dms_remove_tags(client, **params):
410 return client.remove_tags_from_resource(**params)
411
412
413 @AWSRetry.jittered_backoff(**backoff_params)
414 def dms_add_tags(client, **params):
415 return client.add_tags_to_resource(**params)
416
417
418 def endpoint_exists(endpoint):
419 """Returns boolean based on the existence of the endpoint
420 :param endpoint: dict containing the described endpoint
421 :return: bool
422 """
423 return bool(len(endpoint["Endpoints"]))
424
425
426 def delete_dms_endpoint(connection, endpoint_arn):
427 try:
428 delete_arn = dict(EndpointArn=endpoint_arn)
429 if module.params.get("wait"):
430 delete_output = connection.delete_endpoint(**delete_arn)
431 delete_waiter = get_endpoint_deleted_waiter(connection)
432 delete_waiter.wait(
433 Filters=[{"Name": "endpoint-arn", "Values": [endpoint_arn]}],
434 WaiterConfig={"Delay": module.params.get("timeout"), "MaxAttempts": module.params.get("retries")},
435 )
436 return delete_output
437 else:
438 return connection.delete_endpoint(**delete_arn)
439 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
440 module.fail_json_aws(e, msg="Failed to delete the DMS endpoint.")
441
442
443 def create_module_params():
444 """
445 Reads the module parameters and returns a dict
446 :return: dict
447 """
448 endpoint_parameters = dict(
449 EndpointIdentifier=module.params.get("endpointidentifier"),
450 EndpointType=module.params.get("endpointtype"),
451 EngineName=module.params.get("enginename"),
452 Username=module.params.get("username"),
453 Password=module.params.get("password"),
454 ServerName=module.params.get("servername"),
455 Port=module.params.get("port"),
456 DatabaseName=module.params.get("databasename"),
457 SslMode=module.params.get("sslmode"),
458 )
459 if module.params.get("EndpointArn"):
460 endpoint_parameters["EndpointArn"] = module.params.get("EndpointArn")
461 if module.params.get("certificatearn"):
462 endpoint_parameters["CertificateArn"] = module.params.get("certificatearn")
463
464 if module.params.get("dmstransfersettings"):
465 endpoint_parameters["DmsTransferSettings"] = module.params.get("dmstransfersettings")
466
467 if module.params.get("extraconnectionattributes"):
468 endpoint_parameters["ExtraConnectionAttributes"] = module.params.get("extraconnectionattributes")
469
470 if module.params.get("kmskeyid"):
471 endpoint_parameters["KmsKeyId"] = module.params.get("kmskeyid")
472
473 if module.params.get("tags"):
474 endpoint_parameters["Tags"] = module.params.get("tags")
475
476 if module.params.get("serviceaccessrolearn"):
477 endpoint_parameters["ServiceAccessRoleArn"] = module.params.get("serviceaccessrolearn")
478
479 if module.params.get("externaltabledefinition"):
480 endpoint_parameters["ExternalTableDefinition"] = module.params.get("externaltabledefinition")
481
482 if module.params.get("dynamodbsettings"):
483 endpoint_parameters["DynamoDbSettings"] = module.params.get("dynamodbsettings")
484
485 if module.params.get("s3settings"):
486 endpoint_parameters["S3Settings"] = module.params.get("s3settings")
487
488 if module.params.get("mongodbsettings"):
489 endpoint_parameters["MongoDbSettings"] = module.params.get("mongodbsettings")
490
491 if module.params.get("kinesissettings"):
492 endpoint_parameters["KinesisSettings"] = module.params.get("kinesissettings")
493
494 if module.params.get("elasticsearchsettings"):
495 endpoint_parameters["ElasticsearchSettings"] = module.params.get("elasticsearchsettings")
496
497 if module.params.get("wait"):
498 endpoint_parameters["wait"] = module.boolean(module.params.get("wait"))
499
500 if module.params.get("timeout"):
501 endpoint_parameters["timeout"] = module.params.get("timeout")
502
503 if module.params.get("retries"):
504 endpoint_parameters["retries"] = module.params.get("retries")
505
506 return endpoint_parameters
507
508
509 def compare_params(param_described):
510 """
511 Compares the dict obtained from the describe DMS endpoint and
512 what we are reading from the values in the template We can
513 never compare the password as boto3's method for describing
514 a DMS endpoint does not return the value for
515 the password for security reasons ( I assume )
516 """
517 param_described = dict(param_described)
518 modparams = create_module_params()
519
520 # Note: this currently isn't as relaxed for the nested settings, (eg. S3Settings)
521 for param_name, param_value in modparams.items():
522 # modify can't update tags or password
523 if param_name in ["Tags", "Password"]:
524 continue
525 if param_name not in param_described:
526 return True
527 if param_described[param_name] != param_value and str(param_described[param_name]).lower() != param_value:
528 return True
529 return False
530
531
532 def modify_dms_endpoint(connection, endpoint):
533 arn = endpoint["EndpointArn"]
534 try:
535 params = create_module_params()
536 # modify can't update tags
537 params.pop("Tags", None)
538 return dms_modify_endpoint(connection, EndpointArn=arn, **params)
539 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
540 module.fail_json_aws(e, msg="Failed to update DMS endpoint.", params=params)
541
542
543 def ensure_tags(connection, endpoint):
544 desired_tags = module.params.get("tags", None)
545 if desired_tags is None:
546 return False
547
548 current_tags = endpoint.get("tags", {})
549
550 tags_to_add, tags_to_remove = compare_aws_tags(current_tags, desired_tags, module.params.get("purge_tags"))
551
552 if not tags_to_remove and not tags_to_add:
553 return False
554
555 if module.check_mode:
556 return True
557
558 arn = endpoint.get("EndpointArn")
559
560 try:
561 if tags_to_remove:
562 dms_remove_tags(connection, ResourceArn=arn, TagKeys=tags_to_remove)
563 if tags_to_add:
564 tag_list = ansible_dict_to_boto3_tag_list(tags_to_add)
565 dms_add_tags(connection, ResourceArn=arn, Tags=tag_list)
566 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
567 module.fail_json_aws(e, msg="Failed to update DMS endpoint tags.")
568
569 return True
570
571
572 def create_dms_endpoint(connection):
573 """
574 Function to create the dms endpoint
575 :param connection: boto3 aws connection
576 :return: information about the dms endpoint object
577 """
578
579 try:
580 params = create_module_params()
581 return dms_create_endpoint(connection, **params)
582 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
583 module.fail_json_aws(e, msg="Failed to create DMS endpoint.")
584
585
586 def main():
587 argument_spec = dict(
588 state=dict(choices=["present", "absent"], default="present"),
589 endpointidentifier=dict(required=True),
590 endpointtype=dict(choices=["source", "target"]),
591 enginename=dict(
592 choices=[
593 "mysql",
594 "oracle",
595 "postgres",
596 "mariadb",
597 "aurora",
598 "redshift",
599 "s3",
600 "db2",
601 "azuredb",
602 "sybase",
603 "dynamodb",
604 "mongodb",
605 "sqlserver",
606 ],
607 required=False,
608 ),
609 username=dict(),
610 password=dict(no_log=True),
611 servername=dict(),
612 port=dict(type="int"),
613 databasename=dict(),
614 extraconnectionattributes=dict(),
615 kmskeyid=dict(no_log=False),
616 tags=dict(type="dict", aliases=["resource_tags"]),
617 purge_tags=dict(type="bool", default=True),
618 certificatearn=dict(),
619 sslmode=dict(choices=["none", "require", "verify-ca", "verify-full"], default="none"),
620 serviceaccessrolearn=dict(),
621 externaltabledefinition=dict(),
622 dynamodbsettings=dict(type="dict"),
623 s3settings=dict(type="dict"),
624 dmstransfersettings=dict(type="dict"),
625 mongodbsettings=dict(type="dict"),
626 kinesissettings=dict(type="dict"),
627 elasticsearchsettings=dict(type="dict"),
628 wait=dict(type="bool", default=False),
629 timeout=dict(type="int"),
630 retries=dict(type="int"),
631 )
632 global module
633 module = AnsibleAWSModule(
634 argument_spec=argument_spec,
635 required_if=[
636 ["state", "present", ["endpointtype"]],
637 ["state", "present", ["enginename"]],
638 ["state", "absent", ["wait"]],
639 ["wait", "True", ["timeout"]],
640 ["wait", "True", ["retries"]],
641 ],
642 supports_check_mode=False,
643 )
644 exit_message = None
645 changed = False
646
647 state = module.params.get("state")
648
649 dmsclient = module.client("dms")
650 endpoint = describe_endpoint(dmsclient, module.params.get("endpointidentifier"))
651 if state == "present":
652 if endpoint:
653 changed |= ensure_tags(dmsclient, endpoint)
654 params_changed = compare_params(endpoint)
655 if params_changed:
656 updated_dms = modify_dms_endpoint(dmsclient, endpoint)
657 exit_message = updated_dms
658 endpoint = exit_message.get("Endpoint")
659 changed = True
660 else:
661 exit_message = "Endpoint Already Exists"
662 else:
663 exit_message = create_dms_endpoint(dmsclient)
664 endpoint = exit_message.get("Endpoint")
665 changed = True
666
667 if changed:
668 # modify and create don't return tags
669 tags = dms_describe_tags(dmsclient, ResourceArn=endpoint["EndpointArn"])
670 endpoint["tags"] = tags
671 elif state == "absent":
672 if endpoint:
673 delete_results = delete_dms_endpoint(dmsclient, endpoint["EndpointArn"])
674 exit_message = delete_results
675 endpoint = None
676 changed = True
677 else:
678 changed = False
679 exit_message = "DMS Endpoint does not exist"
680
681 endpoint = camel_dict_to_snake_dict(endpoint or {}, ignore_list=["tags"])
682 module.exit_json(changed=changed, endpoint=endpoint, msg=exit_message)
683
684
685 if __name__ == "__main__":
686 main()