Debian Codegraph @

ansible_collections/community/aws/plugins/modules/dynamodb_ttl.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_ttl
10 version_added: 1.0.0
11 short_description: Set TTL for a given DynamoDB table
12 description:
13 - Sets the TTL for a given DynamoDB table.
14 options:
15 state:
16 description:
17 - State to set DynamoDB table to.
18 choices: ['enable', 'disable']
19 required: false
20 type: str
21 table_name:
22 description:
23 - Name of the DynamoDB table to work on.
24 required: true
25 type: str
26 attribute_name:
27 description:
28 - The name of the Time To Live attribute used to store the expiration time for items in the table.
29 - This appears to be required by the API even when disabling TTL.
30 required: true
31 type: str
32
33 author:
34 - Ted Timmons (@tedder)
35 extends_documentation_fragment:
36 - amazon.aws.common.modules
37 - amazon.aws.region.modules
38 - amazon.aws.boto3
39 """
40
41 EXAMPLES = r"""
42 - name: enable TTL on my cowfacts table
43 community.aws.dynamodb_ttl:
44 state: enable
45 table_name: cowfacts
46 attribute_name: cow_deleted_date
47
48 - name: disable TTL on my cowfacts table
49 community.aws.dynamodb_ttl:
50 state: disable
51 table_name: cowfacts
52 attribute_name: cow_deleted_date
53 """
54
55 RETURN = r"""
56 current_status:
57 description: current or new TTL specification.
58 type: dict
59 returned: always
60 sample:
61 - { "AttributeName": "deploy_timestamp", "TimeToLiveStatus": "ENABLED" }
62 - { "AttributeName": "deploy_timestamp", "Enabled": true }
63 """
64
65 try:
66 import botocore
67 except ImportError:
68 pass # Handled by AnsibleAWSModule
69
70 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
71
72
73 def get_current_ttl_state(c, table_name):
74 """Fetch the state dict for a table."""
75 current_state = c.describe_time_to_live(TableName=table_name)
76 return current_state.get("TimeToLiveDescription")
77
78
79 def does_state_need_changing(attribute_name, desired_state, current_spec):
80 """Run checks to see if the table needs to be modified. Basically a dirty check."""
81 if not current_spec:
82 # we don't have an entry (or a table?)
83 return True
84
85 if desired_state.lower() == "enable" and current_spec.get("TimeToLiveStatus") not in ["ENABLING", "ENABLED"]:
86 return True
87 if desired_state.lower() == "disable" and current_spec.get("TimeToLiveStatus") not in ["DISABLING", "DISABLED"]:
88 return True
89 if attribute_name != current_spec.get("AttributeName"):
90 return True
91
92 return False
93
94
95 def set_ttl_state(c, table_name, state, attribute_name):
96 """Set our specification. Returns the update_time_to_live specification dict,
97 which is different than the describe_* call."""
98 is_enabled = False
99 if state.lower() == "enable":
100 is_enabled = True
101
102 ret = c.update_time_to_live(
103 TableName=table_name,
104 TimeToLiveSpecification={
105 "Enabled": is_enabled,
106 "AttributeName": attribute_name,
107 },
108 )
109
110 return ret.get("TimeToLiveSpecification")
111
112
113 def main():
114 argument_spec = dict(
115 state=dict(choices=["enable", "disable"]),
116 table_name=dict(required=True),
117 attribute_name=dict(required=True),
118 )
119 module = AnsibleAWSModule(
120 argument_spec=argument_spec,
121 )
122
123 try:
124 dbclient = module.client("dynamodb")
125 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
126 module.fail_json_aws(e, msg="Failed to connect to AWS")
127
128 result = {"changed": False}
129
130 # wrap all our calls to catch the standard exceptions. We don't pass `module` in to the
131 # methods so it's easier to do here.
132 try:
133 current_state = get_current_ttl_state(dbclient, module.params["table_name"])
134
135 if does_state_need_changing(module.params["attribute_name"], module.params["state"], current_state):
136 # changes needed
137 new_state = set_ttl_state(
138 dbclient, module.params["table_name"], module.params["state"], module.params["attribute_name"]
139 )
140 result["current_status"] = new_state
141 result["changed"] = True
142 else:
143 # no changes needed
144 result["current_status"] = current_state
145
146 except botocore.exceptions.ClientError as e:
147 module.fail_json_aws(e, msg="Failed to get or update ttl state")
148 except botocore.exceptions.ParamValidationError as e:
149 module.fail_json_aws(e, msg="Failed due to invalid parameters")
150 except ValueError as e:
151 module.fail_json_aws(e, msg="Failed")
152
153 module.exit_json(**result)
154
155
156 if __name__ == "__main__":
157 main()