Debian Codegraph @

ansible_collections/community/aws/plugins/modules/s3_website.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: s3_website
10 version_added: 1.0.0
11 short_description: Configure an s3 bucket as a website
12 description:
13 - Configure an s3 bucket as a website
14 author:
15 - Rob White (@wimnat)
16 options:
17 name:
18 description:
19 - "Name of the s3 bucket"
20 required: true
21 type: str
22 error_key:
23 description:
24 - "The object key name to use when a 4XX class error occurs. To remove an error key, set to None."
25 type: str
26 redirect_all_requests:
27 description:
28 - "Describes the redirect behavior for every request to this s3 bucket website endpoint"
29 type: str
30 state:
31 description:
32 - "Add or remove s3 website configuration"
33 choices: [ 'present', 'absent' ]
34 required: true
35 type: str
36 suffix:
37 description:
38 - >
39 Suffix that is appended to a request that is for a directory on the website endpoint (e.g. if the suffix is index.html and you make a request to
40 samplebucket/images/ the data that is returned will be for the object with the key name images/index.html). The suffix must not include a slash
41 character.
42 default: index.html
43 type: str
44
45 extends_documentation_fragment:
46 - amazon.aws.common.modules
47 - amazon.aws.region.modules
48 - amazon.aws.boto3
49 """
50
51 EXAMPLES = r"""
52 # Note: These examples do not set authentication details, see the AWS Guide for details.
53
54 - name: Configure an s3 bucket to redirect all requests to example.com
55 community.aws.s3_website:
56 name: mybucket.com
57 redirect_all_requests: example.com
58 state: present
59
60 - name: Remove website configuration from an s3 bucket
61 community.aws.s3_website:
62 name: mybucket.com
63 state: absent
64
65 - name: Configure an s3 bucket as a website with index and error pages
66 community.aws.s3_website:
67 name: mybucket.com
68 suffix: home.htm
69 error_key: errors/404.htm
70 state: present
71 """
72
73 RETURN = r"""
74 index_document:
75 description: index document
76 type: complex
77 returned: always
78 contains:
79 suffix:
80 description: suffix that is appended to a request that is for a directory on the website endpoint
81 returned: success
82 type: str
83 sample: index.html
84 error_document:
85 description: error document
86 type: complex
87 returned: always
88 contains:
89 key:
90 description: object key name to use when a 4XX class error occurs
91 returned: when error_document parameter set
92 type: str
93 sample: error.html
94 redirect_all_requests_to:
95 description: where to redirect requests
96 type: complex
97 returned: always
98 contains:
99 host_name:
100 description: name of the host where requests will be redirected.
101 returned: when redirect all requests parameter set
102 type: str
103 sample: ansible.com
104 protocol:
105 description: protocol to use when redirecting requests.
106 returned: when redirect all requests parameter set
107 type: str
108 sample: https
109 routing_rules:
110 description: routing rules
111 type: list
112 returned: always
113 contains:
114 condition:
115 type: complex
116 description: A container for describing a condition that must be met for the specified redirect to apply.
117 contains:
118 http_error_code_returned_equals:
119 description: The HTTP error code when the redirect is applied.
120 returned: always
121 type: str
122 key_prefix_equals:
123 description: object key name prefix when the redirect is applied. For example, to redirect
124 requests for ExamplePage.html, the key prefix will be ExamplePage.html
125 returned: when routing rule present
126 type: str
127 sample: docs/
128 redirect:
129 type: complex
130 description: Container for redirect information.
131 returned: always
132 contains:
133 host_name:
134 description: name of the host where requests will be redirected.
135 returned: when host name set as part of redirect rule
136 type: str
137 sample: ansible.com
138 http_redirect_code:
139 description: The HTTP redirect code to use on the response.
140 returned: when routing rule present
141 type: str
142 protocol:
143 description: Protocol to use when redirecting requests.
144 returned: when routing rule present
145 type: str
146 sample: http
147 replace_key_prefix_with:
148 description: object key prefix to use in the redirect request
149 returned: when routing rule present
150 type: str
151 sample: documents/
152 replace_key_with:
153 description: object key prefix to use in the redirect request
154 returned: when routing rule present
155 type: str
156 sample: documents/
157 """
158
159 import time
160
161 try:
162 import botocore
163 except ImportError:
164 pass # Handled by AnsibleAWSModule
165
166 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
167
168 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
169
170 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
171
172
173 def _create_redirect_dict(url):
174 redirect_dict = {}
175 url_split = url.split(":")
176
177 # Did we split anything?
178 if len(url_split) == 2:
179 redirect_dict["Protocol"] = url_split[0]
180 redirect_dict["HostName"] = url_split[1].replace("//", "")
181 elif len(url_split) == 1:
182 redirect_dict["HostName"] = url_split[0]
183 else:
184 raise ValueError("Redirect URL appears invalid")
185
186 return redirect_dict
187
188
189 def _create_website_configuration(suffix, error_key, redirect_all_requests):
190 website_configuration = {}
191
192 if error_key is not None:
193 website_configuration["ErrorDocument"] = {"Key": error_key}
194
195 if suffix is not None:
196 website_configuration["IndexDocument"] = {"Suffix": suffix}
197
198 if redirect_all_requests is not None:
199 website_configuration["RedirectAllRequestsTo"] = _create_redirect_dict(redirect_all_requests)
200
201 return website_configuration
202
203
204 def enable_or_update_bucket_as_website(client_connection, resource_connection, module):
205 bucket_name = module.params.get("name")
206 redirect_all_requests = module.params.get("redirect_all_requests")
207 # If redirect_all_requests is set then don't use the default suffix that has been set
208 if redirect_all_requests is not None:
209 suffix = None
210 else:
211 suffix = module.params.get("suffix")
212 error_key = module.params.get("error_key")
213 changed = False
214
215 try:
216 bucket_website = resource_connection.BucketWebsite(bucket_name)
217 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
218 module.fail_json_aws(e, msg="Failed to get bucket")
219
220 try:
221 website_config = client_connection.get_bucket_website(Bucket=bucket_name)
222 except is_boto3_error_code("NoSuchWebsiteConfiguration"):
223 website_config = None
224 except (
225 botocore.exceptions.ClientError,
226 botocore.exceptions.BotoCoreError,
227 ) as e: # pylint: disable=duplicate-except
228 module.fail_json_aws(e, msg="Failed to get website configuration")
229
230 if website_config is None:
231 try:
232 bucket_website.put(
233 WebsiteConfiguration=_create_website_configuration(suffix, error_key, redirect_all_requests)
234 )
235 changed = True
236 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
237 module.fail_json_aws(e, msg="Failed to set bucket website configuration")
238 except ValueError as e:
239 module.fail_json(msg=str(e))
240 else:
241 try:
242 if (
243 (suffix is not None and website_config["IndexDocument"]["Suffix"] != suffix)
244 or (error_key is not None and website_config["ErrorDocument"]["Key"] != error_key)
245 or (
246 redirect_all_requests is not None
247 and website_config["RedirectAllRequestsTo"] != _create_redirect_dict(redirect_all_requests)
248 )
249 ):
250 try:
251 bucket_website.put(
252 WebsiteConfiguration=_create_website_configuration(suffix, error_key, redirect_all_requests)
253 )
254 changed = True
255 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
256 module.fail_json_aws(e, msg="Failed to update bucket website configuration")
257 except KeyError:
258 try:
259 bucket_website.put(
260 WebsiteConfiguration=_create_website_configuration(suffix, error_key, redirect_all_requests)
261 )
262 changed = True
263 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
264 module.fail_json_aws(e, msg="Failed to update bucket website configuration")
265 except ValueError as e:
266 module.fail_json(msg=str(e))
267
268 # Wait 5 secs before getting the website_config again to give it time to update
269 time.sleep(5)
270
271 website_config = client_connection.get_bucket_website(Bucket=bucket_name)
272 module.exit_json(changed=changed, **camel_dict_to_snake_dict(website_config))
273
274
275 def disable_bucket_as_website(client_connection, module):
276 changed = False
277 bucket_name = module.params.get("name")
278
279 try:
280 client_connection.get_bucket_website(Bucket=bucket_name)
281 except is_boto3_error_code("NoSuchWebsiteConfiguration"):
282 module.exit_json(changed=changed)
283 except (
284 botocore.exceptions.ClientError,
285 botocore.exceptions.BotoCoreError,
286 ) as e: # pylint: disable=duplicate-except
287 module.fail_json_aws(e, msg="Failed to get bucket website")
288
289 try:
290 client_connection.delete_bucket_website(Bucket=bucket_name)
291 changed = True
292 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
293 module.fail_json_aws(e, msg="Failed to delete bucket website")
294
295 module.exit_json(changed=changed)
296
297
298 def main():
299 argument_spec = dict(
300 name=dict(type="str", required=True),
301 state=dict(type="str", required=True, choices=["present", "absent"]),
302 suffix=dict(type="str", required=False, default="index.html"),
303 error_key=dict(type="str", required=False, no_log=False),
304 redirect_all_requests=dict(type="str", required=False),
305 )
306
307 module = AnsibleAWSModule(
308 argument_spec=argument_spec,
309 mutually_exclusive=[
310 ["redirect_all_requests", "suffix"],
311 ["redirect_all_requests", "error_key"],
312 ],
313 )
314
315 try:
316 client_connection = module.client("s3")
317 resource_connection = module.resource("s3")
318 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
319 module.fail_json_aws(e, msg="Failed to connect to AWS")
320
321 state = module.params.get("state")
322
323 if state == "present":
324 enable_or_update_bucket_as_website(client_connection, resource_connection, module)
325 elif state == "absent":
326 disable_bucket_as_website(client_connection, module)
327
328
329 if __name__ == "__main__":
330 main()