Debian Codegraph @

ansible_collections/community/aws/plugins/modules/cloudfront_origin_access_identity.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 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
10 version_added: 1.0.0
11 module: cloudfront_origin_access_identity
12
13 short_description: Create, update and delete origin access identities for a
14 CloudFront distribution
15
16 description:
17 - Allows for easy creation, updating and deletion of origin access
18 identities.
19
20 author:
21 - Willem van Ketwich (@wilvk)
22
23 options:
24 state:
25 description: If the named resource should exist.
26 choices:
27 - present
28 - absent
29 default: present
30 type: str
31 origin_access_identity_id:
32 description:
33 - The origin_access_identity_id of the CloudFront distribution.
34 required: false
35 type: str
36 comment:
37 description:
38 - A comment to describe the CloudFront origin access identity.
39 required: false
40 type: str
41 caller_reference:
42 description:
43 - A unique identifier to reference the origin access identity by.
44 required: false
45 type: str
46
47 notes:
48 - Does not support check mode.
49
50 extends_documentation_fragment:
51 - amazon.aws.common.modules
52 - amazon.aws.region.modules
53 - amazon.aws.boto3
54 """
55
56 EXAMPLES = r"""
57
58 - name: create an origin access identity
59 community.aws.cloudfront_origin_access_identity:
60 state: present
61 caller_reference: this is an example reference
62 comment: this is an example comment
63
64 - name: update an existing origin access identity using caller_reference as an identifier
65 community.aws.cloudfront_origin_access_identity:
66 origin_access_identity_id: E17DRN9XUOAHZX
67 caller_reference: this is an example reference
68 comment: this is a new comment
69
70 - name: delete an existing origin access identity using caller_reference as an identifier
71 community.aws.cloudfront_origin_access_identity:
72 state: absent
73 caller_reference: this is an example reference
74 comment: this is a new comment
75 """
76
77 RETURN = r"""
78 cloud_front_origin_access_identity:
79 description: The origin access identity's information.
80 returned: always
81 type: complex
82 contains:
83 cloud_front_origin_access_identity_config:
84 description: describes a url specifying the origin access identity.
85 returned: always
86 type: complex
87 contains:
88 caller_reference:
89 description: a caller reference for the oai
90 returned: always
91 type: str
92 comment:
93 description: a comment describing the oai
94 returned: always
95 type: str
96 id:
97 description: a unique identifier of the oai
98 returned: always
99 type: str
100 s3_canonical_user_id:
101 description: the canonical user ID of the user who created the oai
102 returned: always
103 type: str
104 e_tag:
105 description: The current version of the origin access identity created.
106 returned: always
107 type: str
108 location:
109 description: The fully qualified URI of the new origin access identity just created.
110 returned: when initially created
111 type: str
112 """
113
114 import datetime
115
116 try:
117 from botocore.exceptions import BotoCoreError
118 from botocore.exceptions import ClientError
119 except ImportError:
120 pass # caught by imported AnsibleAWSModule
121
122 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
123
124 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
125 from ansible_collections.amazon.aws.plugins.module_utils.cloudfront_facts import CloudFrontFactsServiceManager
126
127 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
128
129
130 class CloudFrontOriginAccessIdentityServiceManager(object):
131 """
132 Handles CloudFront origin access identity service calls to aws
133 """
134
135 def __init__(self, module):
136 self.module = module
137 self.client = module.client("cloudfront")
138
139 def create_origin_access_identity(self, caller_reference, comment):
140 try:
141 return self.client.create_cloud_front_origin_access_identity(
142 CloudFrontOriginAccessIdentityConfig={"CallerReference": caller_reference, "Comment": comment}
143 )
144 except (ClientError, BotoCoreError) as e:
145 self.module.fail_json_aws(e, msg="Error creating cloud front origin access identity.")
146
147 def delete_origin_access_identity(self, origin_access_identity_id, e_tag):
148 try:
149 result = self.client.delete_cloud_front_origin_access_identity(Id=origin_access_identity_id, IfMatch=e_tag)
150 return result, True
151 except (ClientError, BotoCoreError) as e:
152 self.module.fail_json_aws(e, msg="Error deleting Origin Access Identity.")
153
154 def update_origin_access_identity(self, caller_reference, comment, origin_access_identity_id, e_tag):
155 changed = False
156 new_config = {"CallerReference": caller_reference, "Comment": comment}
157
158 try:
159 current_config = self.client.get_cloud_front_origin_access_identity_config(Id=origin_access_identity_id)[
160 "CloudFrontOriginAccessIdentityConfig"
161 ]
162 except (ClientError, BotoCoreError) as e:
163 self.module.fail_json_aws(e, msg="Error getting Origin Access Identity config.")
164
165 if new_config != current_config:
166 changed = True
167
168 try:
169 # If the CallerReference is a value already sent in a previous identity request
170 # the returned value is that of the original request
171 result = self.client.update_cloud_front_origin_access_identity(
172 CloudFrontOriginAccessIdentityConfig=new_config,
173 Id=origin_access_identity_id,
174 IfMatch=e_tag,
175 )
176 except (ClientError, BotoCoreError) as e:
177 self.module.fail_json_aws(e, msg="Error updating Origin Access Identity.")
178
179 return result, changed
180
181
182 class CloudFrontOriginAccessIdentityValidationManager(object):
183 """
184 Manages CloudFront Origin Access Identities
185 """
186
187 def __init__(self, module):
188 self.module = module
189 self.__cloudfront_facts_mgr = CloudFrontFactsServiceManager(module)
190
191 def describe_origin_access_identity(self, origin_access_identity_id, fail_if_missing=True):
192 try:
193 return self.__cloudfront_facts_mgr.get_origin_access_identity(
194 id=origin_access_identity_id, fail_if_error=False
195 )
196 except is_boto3_error_code("NoSuchCloudFrontOriginAccessIdentity") as e: # pylint: disable=duplicate-except
197 if fail_if_missing:
198 self.module.fail_json_aws(e, msg="Error getting etag from origin_access_identity.")
199 return {}
200 except (ClientError, BotoCoreError) as e: # pylint: disable=duplicate-except
201 self.module.fail_json_aws(e, msg="Error getting etag from origin_access_identity.")
202
203 def validate_etag_from_origin_access_identity_id(self, origin_access_identity_id, fail_if_missing):
204 oai = self.describe_origin_access_identity(origin_access_identity_id, fail_if_missing)
205 if oai is not None:
206 return oai.get("ETag")
207
208 def validate_origin_access_identity_id_from_caller_reference(self, caller_reference):
209 origin_access_identities = self.__cloudfront_facts_mgr.list_origin_access_identities()
210 origin_origin_access_identity_ids = [oai.get("Id") for oai in origin_access_identities]
211 for origin_access_identity_id in origin_origin_access_identity_ids:
212 oai_config = self.__cloudfront_facts_mgr.get_origin_access_identity_config(id=origin_access_identity_id)
213 temp_caller_reference = oai_config.get("CloudFrontOriginAccessIdentityConfig").get("CallerReference")
214 if temp_caller_reference == caller_reference:
215 return origin_access_identity_id
216
217 def validate_comment(self, comment):
218 if comment is None:
219 return "origin access identity created by Ansible with datetime " + datetime.datetime.now().strftime(
220 "%Y-%m-%dT%H:%M:%S.%f"
221 )
222 return comment
223
224 def validate_caller_reference_from_origin_access_identity_id(self, origin_access_identity_id, caller_reference):
225 if caller_reference is None:
226 if origin_access_identity_id is None:
227 return datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
228 oai = self.describe_origin_access_identity(origin_access_identity_id, fail_if_missing=True)
229 origin_access_config = oai.get("CloudFrontOriginAccessIdentity", {}).get(
230 "CloudFrontOriginAccessIdentityConfig", {}
231 )
232 return origin_access_config.get("CallerReference")
233 return caller_reference
234
235
236 def main():
237 argument_spec = dict(
238 state=dict(choices=["present", "absent"], default="present"),
239 origin_access_identity_id=dict(),
240 caller_reference=dict(),
241 comment=dict(),
242 )
243
244 result = {}
245 e_tag = None
246 changed = False
247
248 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=False)
249 service_mgr = CloudFrontOriginAccessIdentityServiceManager(module)
250 validation_mgr = CloudFrontOriginAccessIdentityValidationManager(module)
251
252 state = module.params.get("state")
253 caller_reference = module.params.get("caller_reference")
254
255 comment = module.params.get("comment")
256 origin_access_identity_id = module.params.get("origin_access_identity_id")
257
258 if origin_access_identity_id is None and caller_reference is not None:
259 origin_access_identity_id = validation_mgr.validate_origin_access_identity_id_from_caller_reference(
260 caller_reference
261 )
262
263 if state == "present":
264 comment = validation_mgr.validate_comment(comment)
265 caller_reference = validation_mgr.validate_caller_reference_from_origin_access_identity_id(
266 origin_access_identity_id, caller_reference
267 )
268 if origin_access_identity_id is not None:
269 e_tag = validation_mgr.validate_etag_from_origin_access_identity_id(origin_access_identity_id, True)
270 # update cloudfront origin access identity
271 result, changed = service_mgr.update_origin_access_identity(
272 caller_reference, comment, origin_access_identity_id, e_tag
273 )
274 else:
275 # create cloudfront origin access identity
276 result = service_mgr.create_origin_access_identity(caller_reference, comment)
277 changed = True
278 else:
279 e_tag = validation_mgr.validate_etag_from_origin_access_identity_id(origin_access_identity_id, False)
280 if e_tag:
281 result, changed = service_mgr.delete_origin_access_identity(origin_access_identity_id, e_tag)
282
283 result.pop("ResponseMetadata", None)
284
285 module.exit_json(changed=changed, **camel_dict_to_snake_dict(result))
286
287
288 if __name__ == "__main__":
289 main()