Debian Codegraph @

ansible_collections/community/aws/plugins/modules/dynamodb_table.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: dynamodb_table
10 version_added: 1.0.0
11 short_description: Create, update or delete AWS Dynamo DB tables
12 description:
13 - Create or delete AWS Dynamo DB tables.
14 - Can update the provisioned throughput on existing tables.
15 - Returns the status of the specified table.
16 author:
17 - Alan Loi (@loia)
18 options:
19 state:
20 description:
21 - Create or delete the table.
22 choices: ['present', 'absent']
23 default: 'present'
24 type: str
25 name:
26 description:
27 - Name of the table.
28 required: true
29 type: str
30 hash_key_name:
31 description:
32 - Name of the hash key.
33 - Required when I(state=present) and table doesn't exist.
34 type: str
35 hash_key_type:
36 description:
37 - Type of the hash key.
38 - Defaults to C('STRING') when creating a new table.
39 choices: ['STRING', 'NUMBER', 'BINARY']
40 type: str
41 range_key_name:
42 description:
43 - Name of the range key.
44 type: str
45 range_key_type:
46 description:
47 - Type of the range key.
48 - Defaults to C('STRING') when creating a new range key.
49 choices: ['STRING', 'NUMBER', 'BINARY']
50 type: str
51 billing_mode:
52 description:
53 - Controls whether provisoned pr on-demand tables are created.
54 choices: ['PROVISIONED', 'PAY_PER_REQUEST']
55 type: str
56 read_capacity:
57 description:
58 - Read throughput capacity (units) to provision.
59 - Defaults to C(1) when creating a new table.
60 type: int
61 write_capacity:
62 description:
63 - Write throughput capacity (units) to provision.
64 - Defaults to C(1) when creating a new table.
65 type: int
66 indexes:
67 description:
68 - list of dictionaries describing indexes to add to the table. global indexes can be updated. local indexes don't support updates or have throughput.
69 - "required options: ['name', 'type', 'hash_key_name']"
70 - "other options: ['hash_key_type', 'range_key_name', 'range_key_type', 'includes', 'read_capacity', 'write_capacity']"
71 suboptions:
72 name:
73 description: The name of the index.
74 type: str
75 required: true
76 type:
77 description:
78 - The type of index.
79 type: str
80 required: true
81 choices: ['all', 'global_all', 'global_include', 'global_keys_only', 'include', 'keys_only']
82 hash_key_name:
83 description:
84 - The name of the hash-based key.
85 - Required if index doesn't already exist.
86 - Can not be modified once the index has been created.
87 required: false
88 type: str
89 hash_key_type:
90 description:
91 - The type of the hash-based key.
92 - Defaults to C('STRING') when creating a new index.
93 - Can not be modified once the index has been created.
94 type: str
95 choices: ['STRING', 'NUMBER', 'BINARY']
96 range_key_name:
97 description:
98 - The name of the range-based key.
99 - Can not be modified once the index has been created.
100 type: str
101 range_key_type:
102 type: str
103 description:
104 - The type of the range-based key.
105 - Defaults to C('STRING') when creating a new index.
106 - Can not be modified once the index has been created.
107 choices: ['STRING', 'NUMBER', 'BINARY']
108 includes:
109 type: list
110 description: A list of fields to include when using C(global_include) or C(include) indexes.
111 elements: str
112 read_capacity:
113 description:
114 - Read throughput capacity (units) to provision for the index.
115 type: int
116 write_capacity:
117 description:
118 - Write throughput capacity (units) to provision for the index.
119 type: int
120 default: []
121 type: list
122 elements: dict
123 table_class:
124 description:
125 - The class of the table.
126 choices: ['STANDARD', 'STANDARD_INFREQUENT_ACCESS']
127 type: str
128 version_added: 3.1.0
129 wait_timeout:
130 description:
131 - How long (in seconds) to wait for creation / update / deletion to complete.
132 - AWS only allows secondary indexies to be updated one at a time, this module will automatically update them
133 in serial, and the timeout will be separately applied for each index.
134 aliases: ['wait_for_active_timeout']
135 default: 900
136 type: int
137 wait:
138 description:
139 - When I(wait=True) the module will wait for up to I(wait_timeout) seconds
140 for index updates, table creation or deletion to complete before returning.
141 default: True
142 type: bool
143 extends_documentation_fragment:
144 - amazon.aws.common.modules
145 - amazon.aws.region.modules
146 - amazon.aws.tags
147 - amazon.aws.boto3
148 """
149
150 EXAMPLES = r"""
151 - name: Create dynamo table with hash and range primary key
152 community.aws.dynamodb_table:
153 name: my-table
154 region: us-east-1
155 hash_key_name: id
156 hash_key_type: STRING
157 range_key_name: create_time
158 range_key_type: NUMBER
159 read_capacity: 2
160 write_capacity: 2
161 tags:
162 tag_name: tag_value
163
164 - name: Update capacity on existing dynamo table
165 community.aws.dynamodb_table:
166 name: my-table
167 region: us-east-1
168 read_capacity: 10
169 write_capacity: 10
170
171 - name: Create pay-per-request table
172 community.aws.dynamodb_table:
173 name: my-table
174 region: us-east-1
175 hash_key_name: id
176 hash_key_type: STRING
177 billing_mode: PAY_PER_REQUEST
178
179 - name: set index on existing dynamo table
180 community.aws.dynamodb_table:
181 name: my-table
182 region: us-east-1
183 indexes:
184 - name: NamedIndex
185 type: global_include
186 hash_key_name: id
187 range_key_name: create_time
188 includes:
189 - other_field
190 - other_field2
191 read_capacity: 10
192 write_capacity: 10
193
194 - name: Delete dynamo table
195 community.aws.dynamodb_table:
196 name: my-table
197 region: us-east-1
198 state: absent
199 """
200
201 RETURN = r"""
202 table:
203 description: The returned table params from the describe API call.
204 returned: success
205 type: complex
206 contains: {}
207 sample: {
208 "arn": "arn:aws:dynamodb:us-east-1:721066863947:table/ansible-test-table",
209 "attribute_definitions": [
210 {
211 "attribute_name": "id",
212 "attribute_type": "N"
213 }
214 ],
215 "billing_mode": "PROVISIONED",
216 "creation_date_time": "2022-02-04T13:36:01.578000+00:00",
217 "id": "533b45fe-0870-4b66-9b00-d2afcfe96f19",
218 "item_count": 0,
219 "key_schema": [
220 {
221 "attribute_name": "id",
222 "key_type": "HASH"
223 }
224 ],
225 "name": "ansible-test-14482047-alinas-mbp",
226 "provisioned_throughput": {
227 "number_of_decreases_today": 0,
228 "read_capacity_units": 1,
229 "write_capacity_units": 1
230 },
231 "size": 0,
232 "status": "ACTIVE",
233 "table_arn": "arn:aws:dynamodb:us-east-1:721066863947:table/ansible-test-table",
234 "table_id": "533b45fe-0870-4b66-9b00-d2afcfe96f19",
235 "table_name": "ansible-test-table",
236 "table_size_bytes": 0,
237 "table_status": "ACTIVE",
238 "tags": {}
239 }
240 table_status:
241 description: The current status of the table.
242 returned: success
243 type: str
244 sample: ACTIVE
245 """
246
247 try:
248 import botocore
249 except ImportError:
250 pass # Handled by AnsibleAWSModule
251
252 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
253
254 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
255 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
256 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
257 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
258 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
259
260 from ansible_collections.community.aws.plugins.module_utils.dynamodb import wait_indexes_active
261 from ansible_collections.community.aws.plugins.module_utils.dynamodb import wait_table_exists
262 from ansible_collections.community.aws.plugins.module_utils.dynamodb import wait_table_not_exists
263 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
264
265 DYNAMO_TYPE_DEFAULT = "STRING"
266 INDEX_REQUIRED_OPTIONS = ["name", "type", "hash_key_name"]
267 INDEX_OPTIONS = INDEX_REQUIRED_OPTIONS + [
268 "hash_key_type",
269 "range_key_name",
270 "range_key_type",
271 "includes",
272 "read_capacity",
273 "write_capacity",
274 ]
275 INDEX_TYPE_OPTIONS = ["all", "global_all", "global_include", "global_keys_only", "include", "keys_only"]
276 # Map in both directions
277 DYNAMO_TYPE_MAP_LONG = {"STRING": "S", "NUMBER": "N", "BINARY": "B"}
278 DYNAMO_TYPE_MAP_SHORT = dict((v, k) for k, v in DYNAMO_TYPE_MAP_LONG.items())
279 KEY_TYPE_CHOICES = list(DYNAMO_TYPE_MAP_LONG.keys())
280
281
282 # If you try to update an index while another index is updating, it throws
283 # LimitExceededException/ResourceInUseException exceptions at you. This can be
284 # pretty slow, so add plenty of retries...
285 @AWSRetry.jittered_backoff(
286 retries=45,
287 delay=5,
288 max_delay=30,
289 catch_extra_error_codes=["ResourceInUseException", "ResourceNotFoundException"],
290 )
291 def _update_table_with_long_retry(**changes):
292 return client.update_table(TableName=module.params.get("name"), **changes)
293
294
295 # ResourceNotFoundException is expected here if the table doesn't exist
296 @AWSRetry.jittered_backoff(catch_extra_error_codes=["LimitExceededException", "ResourceInUseException"])
297 def _describe_table(**params):
298 return client.describe_table(**params)
299
300
301 def wait_exists():
302 wait_table_exists(
303 module,
304 module.params.get("wait_timeout"),
305 module.params.get("name"),
306 )
307
308
309 def wait_not_exists():
310 wait_table_not_exists(
311 module,
312 module.params.get("wait_timeout"),
313 module.params.get("name"),
314 )
315
316
317 def wait_indexes():
318 wait_indexes_active(
319 module,
320 module.params.get("wait_timeout"),
321 module.params.get("name"),
322 )
323
324
325 def _short_type_to_long(short_key):
326 if not short_key:
327 return None
328 return DYNAMO_TYPE_MAP_SHORT.get(short_key, None)
329
330
331 def _long_type_to_short(long_key):
332 if not long_key:
333 return None
334 return DYNAMO_TYPE_MAP_LONG.get(long_key, None)
335
336
337 def _schema_dict(key_name, key_type):
338 return dict(
339 AttributeName=key_name,
340 KeyType=key_type,
341 )
342
343
344 def _merge_index_params(index, current_index):
345 idx = dict(current_index)
346 idx.update(index)
347 return idx
348
349
350 def _decode_primary_index(current_table):
351 """
352 Decodes the primary index info from the current table definition
353 splitting it up into the keys we use as parameters
354 """
355 # The schema/attribute definitions are a list of dicts which need the same
356 # treatment as boto3's tag lists
357 schema = boto3_tag_list_to_ansible_dict(
358 current_table.get("key_schema", []),
359 # Map from 'HASH'/'RANGE' to attribute name
360 tag_name_key_name="key_type",
361 tag_value_key_name="attribute_name",
362 )
363 attributes = boto3_tag_list_to_ansible_dict(
364 current_table.get("attribute_definitions", []),
365 # Map from attribute name to 'S'/'N'/'B'.
366 tag_name_key_name="attribute_name",
367 tag_value_key_name="attribute_type",
368 )
369
370 hash_key_name = schema.get("HASH")
371 hash_key_type = _short_type_to_long(attributes.get(hash_key_name, None))
372 range_key_name = schema.get("RANGE", None)
373 range_key_type = _short_type_to_long(attributes.get(range_key_name, None))
374
375 return dict(
376 hash_key_name=hash_key_name,
377 hash_key_type=hash_key_type,
378 range_key_name=range_key_name,
379 range_key_type=range_key_type,
380 )
381
382
383 def _decode_index(index_data, attributes, type_prefix=""):
384 try:
385 index_map = dict(
386 name=index_data["index_name"],
387 )
388
389 index_data = dict(index_data)
390 index_data["attribute_definitions"] = attributes
391
392 index_map.update(_decode_primary_index(index_data))
393
394 throughput = index_data.get("provisioned_throughput", {})
395 index_map["provisioned_throughput"] = throughput
396 if throughput:
397 index_map["read_capacity"] = throughput.get("read_capacity_units")
398 index_map["write_capacity"] = throughput.get("write_capacity_units")
399
400 projection = index_data.get("projection", {})
401 if projection:
402 index_map["type"] = type_prefix + projection.get("projection_type")
403 index_map["includes"] = projection.get("non_key_attributes", [])
404
405 return index_map
406 except Exception as e:
407 module.fail_json_aws(e, msg="Decode failure", index_data=index_data)
408
409
410 def compatability_results(current_table):
411 if not current_table:
412 return dict()
413
414 billing_mode = current_table.get("billing_mode")
415
416 primary_indexes = _decode_primary_index(current_table)
417
418 hash_key_name = primary_indexes.get("hash_key_name")
419 hash_key_type = primary_indexes.get("hash_key_type")
420 range_key_name = primary_indexes.get("range_key_name")
421 range_key_type = primary_indexes.get("range_key_type")
422
423 indexes = list()
424 global_indexes = current_table.get("_global_index_map", {})
425 local_indexes = current_table.get("_local_index_map", {})
426 for index in global_indexes:
427 idx = dict(global_indexes[index])
428 idx.pop("provisioned_throughput", None)
429 indexes.append(idx)
430 for index in local_indexes:
431 idx = dict(local_indexes[index])
432 idx.pop("provisioned_throughput", None)
433 indexes.append(idx)
434
435 compat_results = dict(
436 hash_key_name=hash_key_name,
437 hash_key_type=hash_key_type,
438 range_key_name=range_key_name,
439 range_key_type=range_key_type,
440 indexes=indexes,
441 billing_mode=billing_mode,
442 region=module.region,
443 table_name=current_table.get("table_name", None),
444 table_class=current_table.get("table_class_summary", {}).get("table_class", None),
445 table_status=current_table.get("table_status", None),
446 tags=current_table.get("tags", {}),
447 )
448
449 if billing_mode == "PROVISIONED":
450 throughput = current_table.get("provisioned_throughput", {})
451 compat_results["read_capacity"] = throughput.get("read_capacity_units", None)
452 compat_results["write_capacity"] = throughput.get("write_capacity_units", None)
453
454 return compat_results
455
456
457 def get_dynamodb_table():
458 table_name = module.params.get("name")
459 try:
460 table = _describe_table(TableName=table_name)
461 except is_boto3_error_code("ResourceNotFoundException"):
462 return None
463 except (
464 botocore.exceptions.ClientError,
465 botocore.exceptions.BotoCoreError,
466 ) as e: # pylint: disable=duplicate-except
467 module.fail_json_aws(e, msg="Failed to describe table")
468
469 table = table["Table"]
470 try:
471 tags = client.list_tags_of_resource(aws_retry=True, ResourceArn=table["TableArn"])["Tags"]
472 except is_boto3_error_code("AccessDeniedException"):
473 module.warn("Permission denied when listing tags")
474 tags = []
475 except (
476 botocore.exceptions.ClientError,
477 botocore.exceptions.BotoCoreError,
478 ) as e: # pylint: disable=duplicate-except
479 module.fail_json_aws(e, msg="Failed to list table tags")
480
481 tags = boto3_tag_list_to_ansible_dict(tags)
482
483 table = camel_dict_to_snake_dict(table)
484
485 # Put some of the values into places people will expect them
486 table["arn"] = table["table_arn"]
487 table["name"] = table["table_name"]
488 table["status"] = table["table_status"]
489 table["id"] = table["table_id"]
490 table["size"] = table["table_size_bytes"]
491 table["tags"] = tags
492
493 if "table_class_summary" in table:
494 table["table_class"] = table["table_class_summary"]["table_class"]
495
496 # billing_mode_summary doesn't always seem to be set but is always set for PAY_PER_REQUEST
497 # and when updating the billing_mode
498 if "billing_mode_summary" in table:
499 table["billing_mode"] = table["billing_mode_summary"]["billing_mode"]
500 else:
501 table["billing_mode"] = "PROVISIONED"
502
503 # convert indexes into something we can easily search against
504 attributes = table["attribute_definitions"]
505 global_index_map = dict()
506 local_index_map = dict()
507 for index in table.get("global_secondary_indexes", []):
508 idx = _decode_index(index, attributes, type_prefix="global_")
509 global_index_map[idx["name"]] = idx
510 for index in table.get("local_secondary_indexes", []):
511 idx = _decode_index(index, attributes)
512 local_index_map[idx["name"]] = idx
513 table["_global_index_map"] = global_index_map
514 table["_local_index_map"] = local_index_map
515
516 return table
517
518
519 def _generate_attribute_map():
520 """
521 Builds a map of Key Names to Type
522 """
523 attributes = dict()
524
525 for index in (module.params, *module.params.get("indexes")):
526 # run through hash_key_name and range_key_name
527 for t in ["hash", "range"]:
528 key_name = index.get(t + "_key_name")
529 if not key_name:
530 continue
531 key_type = index.get(t + "_key_type") or DYNAMO_TYPE_DEFAULT
532 _type = _long_type_to_short(key_type)
533 if key_name in attributes:
534 if _type != attributes[key_name]:
535 module.fail_json(
536 msg="Conflicting attribute type", type_1=_type, type_2=attributes[key_name], key_name=key_name
537 )
538 else:
539 attributes[key_name] = _type
540
541 return attributes
542
543
544 def _generate_attributes():
545 attributes = _generate_attribute_map()
546
547 # Use ansible_dict_to_boto3_tag_list to generate the list of dicts
548 # format we need
549 attrs = ansible_dict_to_boto3_tag_list(
550 attributes, tag_name_key_name="AttributeName", tag_value_key_name="AttributeType"
551 )
552 return list(attrs)
553
554
555 def _generate_throughput(params=None):
556 if not params:
557 params = module.params
558
559 read_capacity = params.get("read_capacity") or 1
560 write_capacity = params.get("write_capacity") or 1
561 throughput = dict(
562 ReadCapacityUnits=read_capacity,
563 WriteCapacityUnits=write_capacity,
564 )
565
566 return throughput
567
568
569 def _generate_schema(params=None):
570 if not params:
571 params = module.params
572
573 schema = list()
574 hash_key_name = params.get("hash_key_name")
575 range_key_name = params.get("range_key_name")
576
577 if hash_key_name:
578 entry = _schema_dict(hash_key_name, "HASH")
579 schema.append(entry)
580 if range_key_name:
581 entry = _schema_dict(range_key_name, "RANGE")
582 schema.append(entry)
583
584 return schema
585
586
587 def _primary_index_changes(current_table):
588 primary_index = _decode_primary_index(current_table)
589
590 hash_key_name = primary_index.get("hash_key_name")
591 _hash_key_name = module.params.get("hash_key_name")
592 hash_key_type = primary_index.get("hash_key_type")
593 _hash_key_type = module.params.get("hash_key_type")
594 range_key_name = primary_index.get("range_key_name")
595 _range_key_name = module.params.get("range_key_name")
596 range_key_type = primary_index.get("range_key_type")
597 _range_key_type = module.params.get("range_key_type")
598
599 changed = list()
600
601 if _hash_key_name and (_hash_key_name != hash_key_name):
602 changed.append("hash_key_name")
603 if _hash_key_type and (_hash_key_type != hash_key_type):
604 changed.append("hash_key_type")
605 if _range_key_name and (_range_key_name != range_key_name):
606 changed.append("range_key_name")
607 if _range_key_type and (_range_key_type != range_key_type):
608 changed.append("range_key_type")
609
610 return changed
611
612
613 def _throughput_changes(current_table, params=None):
614 if not params:
615 params = module.params
616
617 throughput = current_table.get("provisioned_throughput", {})
618 read_capacity = throughput.get("read_capacity_units", None)
619 _read_capacity = params.get("read_capacity") or read_capacity
620 write_capacity = throughput.get("write_capacity_units", None)
621 _write_capacity = params.get("write_capacity") or write_capacity
622
623 if (read_capacity != _read_capacity) or (write_capacity != _write_capacity):
624 return dict(
625 ReadCapacityUnits=_read_capacity,
626 WriteCapacityUnits=_write_capacity,
627 )
628
629 return dict()
630
631
632 def _generate_global_indexes(billing_mode):
633 index_exists = dict()
634 indexes = list()
635
636 include_throughput = True
637
638 if billing_mode == "PAY_PER_REQUEST":
639 include_throughput = False
640
641 for index in module.params.get("indexes"):
642 if index.get("type") not in ["global_all", "global_include", "global_keys_only"]:
643 continue
644 name = index.get("name")
645 if name in index_exists:
646 module.fail_json(msg=f"Duplicate key {name} in list of global indexes")
647 # Convert the type name to upper case and remove the global_
648 index["type"] = index["type"].upper()[7:]
649 index = _generate_index(index, include_throughput)
650 index_exists[name] = True
651 indexes.append(index)
652
653 return indexes
654
655
656 def _generate_local_indexes():
657 index_exists = dict()
658 indexes = list()
659
660 for index in module.params.get("indexes"):
661 if index.get("type") not in ["all", "include", "keys_only"]:
662 continue
663 name = index.get("name")
664 if name in index_exists:
665 module.fail_json(msg=f"Duplicate key {name} in list of local indexes")
666 index["type"] = index["type"].upper()
667 index = _generate_index(index, False)
668 index_exists[name] = True
669 indexes.append(index)
670
671 return indexes
672
673
674 def _generate_global_index_map(current_table):
675 global_index_map = dict()
676 existing_indexes = current_table["_global_index_map"]
677 for index in module.params.get("indexes"):
678 if index.get("type") not in ["global_all", "global_include", "global_keys_only"]:
679 continue
680 name = index.get("name")
681 if name in global_index_map:
682 module.fail_json(msg=f"Duplicate key {name} in list of global indexes")
683 idx = _merge_index_params(index, existing_indexes.get(name, {}))
684 # Convert the type name to upper case and remove the global_
685 idx["type"] = idx["type"].upper()[7:]
686 global_index_map[name] = idx
687 return global_index_map
688
689
690 def _generate_local_index_map(current_table):
691 local_index_map = dict()
692 existing_indexes = current_table["_local_index_map"]
693 for index in module.params.get("indexes"):
694 if index.get("type") not in ["all", "include", "keys_only"]:
695 continue
696 name = index.get("name")
697 if name in local_index_map:
698 module.fail_json(msg=f"Duplicate key {name} in list of local indexes")
699 idx = _merge_index_params(index, existing_indexes.get(name, {}))
700 # Convert the type name to upper case
701 idx["type"] = idx["type"].upper()
702 local_index_map[name] = idx
703 return local_index_map
704
705
706 def _generate_index(index, include_throughput=True):
707 key_schema = _generate_schema(index)
708 throughput = _generate_throughput(index)
709 non_key_attributes = index["includes"] or []
710 projection = dict(
711 ProjectionType=index["type"],
712 )
713 if index["type"] != "ALL":
714 if non_key_attributes:
715 projection["NonKeyAttributes"] = non_key_attributes
716 else:
717 if non_key_attributes:
718 module.fail_json(
719 "DynamoDB does not support specifying non-key-attributes ('includes') for indexes of type 'all'. Index"
720 f" name: {index['name']}"
721 )
722
723 idx = dict(
724 IndexName=index["name"],
725 KeySchema=key_schema,
726 Projection=projection,
727 )
728
729 if include_throughput:
730 idx["ProvisionedThroughput"] = throughput
731
732 return idx
733
734
735 def _attribute_changes(current_table):
736 # TODO (future) It would be nice to catch attempts to change types here.
737 return _generate_attributes()
738
739
740 def _global_index_changes(current_table):
741 current_global_index_map = current_table["_global_index_map"]
742 global_index_map = _generate_global_index_map(current_table)
743
744 current_billing_mode = current_table.get("billing_mode")
745
746 if module.params.get("billing_mode") is None:
747 billing_mode = current_billing_mode
748 else:
749 billing_mode = module.params.get("billing_mode")
750
751 include_throughput = True
752
753 if billing_mode == "PAY_PER_REQUEST":
754 include_throughput = False
755
756 index_changes = list()
757
758 # TODO (future) it would be nice to add support for deleting an index
759 for name, current_value in global_index_map.items():
760 idx = dict(_generate_index(current_value, include_throughput=include_throughput))
761 if name not in current_global_index_map:
762 index_changes.append(dict(Create=idx))
763 else:
764 # The only thing we can change is the provisioned throughput.
765 # TODO (future) it would be nice to throw a deprecation here
766 # rather than dropping other changes on the floor
767 _current = current_global_index_map[name]
768 _new = current_value
769
770 if include_throughput:
771 change = dict(_throughput_changes(_current, _new))
772 if change:
773 update = dict(
774 IndexName=name,
775 ProvisionedThroughput=change,
776 )
777 index_changes.append(dict(Update=update))
778
779 return index_changes
780
781
782 def _local_index_changes(current_table):
783 # TODO (future) Changes to Local Indexes aren't possible after creation,
784 # we should probably throw a deprecation warning here (original module
785 # also just dropped these changes on the floor)
786 return []
787
788
789 def _update_table(current_table):
790 changes = dict()
791 additional_global_index_changes = list()
792
793 # Get throughput / billing_mode changes
794 throughput_changes = _throughput_changes(current_table)
795 if throughput_changes:
796 changes["ProvisionedThroughput"] = throughput_changes
797
798 current_billing_mode = current_table.get("billing_mode")
799 new_billing_mode = module.params.get("billing_mode")
800
801 if new_billing_mode is None:
802 new_billing_mode = current_billing_mode
803
804 if current_billing_mode != new_billing_mode:
805 changes["BillingMode"] = new_billing_mode
806
807 # Update table_class use exisiting if none is defined
808 if module.params.get("table_class"):
809 if module.params.get("table_class") != current_table.get("table_class"):
810 changes["TableClass"] = module.params.get("table_class")
811
812 global_index_changes = _global_index_changes(current_table)
813 if global_index_changes:
814 changes["GlobalSecondaryIndexUpdates"] = global_index_changes
815 # Only one index can be changed at a time except if changing the billing mode, pass the first during the
816 # main update and deal with the others on a slow retry to wait for
817 # completion
818
819 if current_billing_mode == new_billing_mode:
820 if len(global_index_changes) > 1:
821 changes["GlobalSecondaryIndexUpdates"] = [global_index_changes[0]]
822 additional_global_index_changes = global_index_changes[1:]
823
824 local_index_changes = _local_index_changes(current_table)
825 if local_index_changes:
826 changes["LocalSecondaryIndexUpdates"] = local_index_changes
827
828 if not changes:
829 return False
830
831 if module.check_mode:
832 return True
833
834 if global_index_changes or local_index_changes:
835 changes["AttributeDefinitions"] = _generate_attributes()
836
837 try:
838 client.update_table(aws_retry=True, TableName=module.params.get("name"), **changes)
839 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
840 module.fail_json_aws(e, msg="Failed to update table")
841
842 if additional_global_index_changes:
843 for index in additional_global_index_changes:
844 wait_indexes()
845 try:
846 _update_table_with_long_retry(
847 GlobalSecondaryIndexUpdates=[index], AttributeDefinitions=changes["AttributeDefinitions"]
848 )
849 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
850 module.fail_json_aws(
851 e,
852 msg="Failed to update table",
853 changes=changes,
854 additional_global_index_changes=additional_global_index_changes,
855 )
856
857 return True
858
859
860 def _update_tags(current_table):
861 _tags = module.params.get("tags")
862 if _tags is None:
863 return False
864
865 tags_to_add, tags_to_remove = compare_aws_tags(
866 current_table["tags"], module.params.get("tags"), purge_tags=module.params.get("purge_tags")
867 )
868
869 # If neither need updating we can return already
870 if not (tags_to_add or tags_to_remove):
871 return False
872
873 if module.check_mode:
874 return True
875
876 if tags_to_add:
877 try:
878 client.tag_resource(
879 aws_retry=True,
880 ResourceArn=current_table["arn"],
881 Tags=ansible_dict_to_boto3_tag_list(tags_to_add),
882 )
883 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
884 module.fail_json_aws(e, msg="Failed to tag table")
885 if tags_to_remove:
886 try:
887 client.untag_resource(
888 aws_retry=True,
889 ResourceArn=current_table["arn"],
890 TagKeys=tags_to_remove,
891 )
892 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
893 module.fail_json_aws(e, msg="Failed to untag table")
894
895 return True
896
897
898 def update_table(current_table):
899 primary_index_changes = _primary_index_changes(current_table)
900 if primary_index_changes:
901 module.fail_json(
902 f"DynamoDB does not support updating the Primary keys on a table. Changed paramters are: {primary_index_changes}"
903 )
904
905 changed = False
906 changed |= _update_table(current_table)
907 changed |= _update_tags(current_table)
908
909 if module.params.get("wait"):
910 wait_exists()
911 wait_indexes()
912
913 return changed
914
915
916 def create_table():
917 table_name = module.params.get("name")
918 table_class = module.params.get("table_class")
919 hash_key_name = module.params.get("hash_key_name")
920 billing_mode = module.params.get("billing_mode")
921
922 if billing_mode is None:
923 billing_mode = "PROVISIONED"
924
925 tags = ansible_dict_to_boto3_tag_list(module.params.get("tags") or {})
926
927 if not hash_key_name:
928 module.fail_json('"hash_key_name" must be provided when creating a new table.')
929
930 if module.check_mode:
931 return True
932
933 if billing_mode == "PROVISIONED":
934 throughput = _generate_throughput()
935
936 attributes = _generate_attributes()
937 key_schema = _generate_schema()
938 local_indexes = _generate_local_indexes()
939 global_indexes = _generate_global_indexes(billing_mode)
940
941 params = dict(
942 TableName=table_name,
943 AttributeDefinitions=attributes,
944 KeySchema=key_schema,
945 Tags=tags,
946 BillingMode=billing_mode,
947 # TODO (future)
948 # StreamSpecification,
949 # SSESpecification,
950 )
951
952 if table_class:
953 params["TableClass"] = table_class
954 if billing_mode == "PROVISIONED":
955 params["ProvisionedThroughput"] = throughput
956 if local_indexes:
957 params["LocalSecondaryIndexes"] = local_indexes
958 if global_indexes:
959 params["GlobalSecondaryIndexes"] = global_indexes
960
961 try:
962 client.create_table(aws_retry=True, **params)
963 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
964 module.fail_json_aws(e, msg="Failed to create table")
965
966 if module.params.get("wait"):
967 wait_exists()
968 wait_indexes()
969
970 return True
971
972
973 def delete_table(current_table):
974 if not current_table:
975 return False
976
977 if module.check_mode:
978 return True
979
980 table_name = module.params.get("name")
981
982 # If an index is mid-update then we have to wait for the update to complete
983 # before deletion will succeed
984 long_retry = AWSRetry.jittered_backoff(
985 retries=45,
986 delay=5,
987 max_delay=30,
988 catch_extra_error_codes=["LimitExceededException", "ResourceInUseException"],
989 )
990
991 try:
992 long_retry(client.delete_table)(TableName=table_name)
993 except is_boto3_error_code("ResourceNotFoundException"):
994 return False
995 except (
996 botocore.exceptions.ClientError,
997 botocore.exceptions.BotoCoreError,
998 ) as e: # pylint: disable=duplicate-except
999 module.fail_json_aws(e, msg="Failed to delete table")
1000
1001 if module.params.get("wait"):
1002 wait_not_exists()
1003
1004 return True
1005
1006
1007 def main():
1008 global module
1009 global client
1010
1011 # TODO (future) It would be good to split global and local indexes. They have
1012 # different parameters, use a separate namespace for names,
1013 # and local indexes can't be updated.
1014 index_options = dict(
1015 name=dict(type="str", required=True),
1016 # It would be nice to make this optional, but because Local and Global
1017 # indexes are mixed in here we need this to be able to tell to which
1018 # group of indexes the index belongs.
1019 type=dict(type="str", required=True, choices=INDEX_TYPE_OPTIONS),
1020 hash_key_name=dict(type="str", required=False),
1021 hash_key_type=dict(type="str", required=False, choices=KEY_TYPE_CHOICES),
1022 range_key_name=dict(type="str", required=False),
1023 range_key_type=dict(type="str", required=False, choices=KEY_TYPE_CHOICES),
1024 includes=dict(type="list", required=False, elements="str"),
1025 read_capacity=dict(type="int", required=False),
1026 write_capacity=dict(type="int", required=False),
1027 )
1028
1029 argument_spec = dict(
1030 state=dict(default="present", choices=["present", "absent"]),
1031 name=dict(required=True, type="str"),
1032 hash_key_name=dict(type="str"),
1033 hash_key_type=dict(type="str", choices=KEY_TYPE_CHOICES),
1034 range_key_name=dict(type="str"),
1035 range_key_type=dict(type="str", choices=KEY_TYPE_CHOICES),
1036 billing_mode=dict(type="str", choices=["PROVISIONED", "PAY_PER_REQUEST"]),
1037 read_capacity=dict(type="int"),
1038 write_capacity=dict(type="int"),
1039 indexes=dict(default=[], type="list", elements="dict", options=index_options),
1040 table_class=dict(type="str", choices=["STANDARD", "STANDARD_INFREQUENT_ACCESS"]),
1041 tags=dict(type="dict", aliases=["resource_tags"]),
1042 purge_tags=dict(type="bool", default=True),
1043 wait=dict(type="bool", default=True),
1044 wait_timeout=dict(default=900, type="int", aliases=["wait_for_active_timeout"]),
1045 )
1046
1047 module = AnsibleAWSModule(
1048 argument_spec=argument_spec,
1049 supports_check_mode=True,
1050 check_boto3=False,
1051 )
1052
1053 retry_decorator = AWSRetry.jittered_backoff(
1054 catch_extra_error_codes=["LimitExceededException", "ResourceInUseException", "ResourceNotFoundException"],
1055 )
1056 client = module.client("dynamodb", retry_decorator=retry_decorator)
1057
1058 current_table = get_dynamodb_table()
1059 changed = False
1060 table = None
1061 results = dict()
1062
1063 state = module.params.get("state")
1064 if state == "present":
1065 if current_table:
1066 changed |= update_table(current_table)
1067 else:
1068 changed |= create_table()
1069 table = get_dynamodb_table()
1070 elif state == "absent":
1071 changed |= delete_table(current_table)
1072
1073 compat_results = compatability_results(table)
1074 if compat_results:
1075 results.update(compat_results)
1076
1077 results["changed"] = changed
1078 if table:
1079 # These are used to pass computed data about, not needed for users
1080 table.pop("_global_index_map", None)
1081 table.pop("_local_index_map", None)
1082 results["table"] = table
1083
1084 module.exit_json(**results)
1085
1086
1087 if __name__ == "__main__":
1088 main()