Debian Codegraph @

ansible_collections/community/aws/plugins/modules/iam_server_certificate.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: iam_server_certificate
10 version_added: 1.0.0
11 short_description: Manage IAM server certificates for use on ELBs and CloudFront
12 description:
13 - Allows for the management of IAM server certificates.
14 options:
15 name:
16 description:
17 - Name of certificate to add, update or remove.
18 required: true
19 type: str
20 new_name:
21 description:
22 - When I(state=present), this will update the name of the cert.
23 - The I(cert), I(key) and I(cert_chain) parameters will be ignored if this is defined.
24 type: str
25 new_path:
26 description:
27 - When I(state=present), this will update the path of the cert.
28 - The I(cert), I(key) and I(cert_chain) parameters will be ignored if this is defined.
29 type: str
30 state:
31 description:
32 - Whether to create (or update) or delete the certificate.
33 - If I(new_path) or I(new_name) is defined, specifying present will attempt to make an update these.
34 required: true
35 choices: [ "present", "absent" ]
36 type: str
37 path:
38 description:
39 - When creating or updating, specify the desired path of the certificate.
40 default: "/"
41 type: str
42 cert_chain:
43 description:
44 - The content of the CA certificate chain in PEM encoded format.
45 type: str
46 cert:
47 description:
48 - The content of the certificate body in PEM encoded format.
49 type: str
50 key:
51 description:
52 - The content of the private key in PEM encoded format.
53 type: str
54 dup_ok:
55 description:
56 - By default the module will not upload a certificate that is already uploaded into AWS.
57 - If I(dup_ok=True), it will upload the certificate as long as the name is unique.
58 - The default value for this value changed in release 5.0.0 to C(true).
59 default: true
60 type: bool
61
62 author:
63 - Jonathan I. Davila (@defionscode)
64 extends_documentation_fragment:
65 - amazon.aws.common.modules
66 - amazon.aws.region.modules
67 - amazon.aws.boto3
68 """
69
70 RETURN = r""" # """
71
72 EXAMPLES = r"""
73 - name: Basic server certificate upload from local file
74 community.aws.iam_server_certificate:
75 name: very_ssl
76 state: present
77 cert: "{{ lookup('file', 'path/to/cert') }}"
78 key: "{{ lookup('file', 'path/to/key') }}"
79 cert_chain: "{{ lookup('file', 'path/to/certchain') }}"
80
81 - name: Server certificate upload using key string
82 community.aws.iam_server_certificate:
83 name: very_ssl
84 state: present
85 path: "/a/cert/path/"
86 cert: "{{ lookup('file', 'path/to/cert') }}"
87 key: "{{ lookup('file', 'path/to/key') }}"
88 cert_chain: "{{ lookup('file', 'path/to/certchain') }}"
89
90 - name: Basic rename of existing certificate
91 community.aws.iam_server_certificate:
92 name: very_ssl
93 new_name: new_very_ssl
94 state: present
95 """
96
97 try:
98 import botocore
99 except ImportError:
100 pass # Handled by HAS_BOTO
101
102 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
103
104 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
105 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
106
107 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
108
109
110 @AWSRetry.jittered_backoff()
111 def _list_server_certficates():
112 paginator = client.get_paginator("list_server_certificates")
113 return paginator.paginate().build_full_result()["ServerCertificateMetadataList"]
114
115
116 def check_duplicate_cert(new_cert):
117 orig_cert_names = list(c["ServerCertificateName"] for c in _list_server_certficates())
118 for cert_name in orig_cert_names:
119 cert = get_server_certificate(cert_name)
120 if not cert:
121 continue
122 cert_body = cert.get("certificate_body", None)
123 if not _compare_cert(new_cert, cert_body):
124 continue
125 module.fail_json(
126 changed=False,
127 msg=f"This certificate already exists under the name {cert_name} and dup_ok=False",
128 duplicate_cert=cert,
129 )
130
131
132 def _compare_cert(cert_a, cert_b):
133 if not cert_a and not cert_b:
134 return True
135 if not cert_a or not cert_b:
136 return False
137 # Trim out the whitespace before comparing the certs. While this could mean
138 # an invalid cert 'matches' a valid cert, that's better than some stray
139 # whitespace breaking things
140 cert_a.replace("\r", "")
141 cert_a.replace("\n", "")
142 cert_a.replace(" ", "")
143 cert_b.replace("\r", "")
144 cert_b.replace("\n", "")
145 cert_b.replace(" ", "")
146
147 return cert_a == cert_b
148
149
150 def update_server_certificate(current_cert):
151 changed = False
152 cert = module.params.get("cert")
153 cert_chain = module.params.get("cert_chain")
154
155 if not _compare_cert(cert, current_cert.get("certificate_body", None)):
156 module.fail_json(msg="Modifying the certificate body is not supported by AWS")
157 if not _compare_cert(cert_chain, current_cert.get("certificate_chain", None)):
158 module.fail_json(msg="Modifying the chaining certificate is not supported by AWS")
159 # We can't compare keys.
160
161 if module.check_mode:
162 return changed
163
164 # For now we can't make any changes. Updates to tagging would go here and
165 # update 'changed'
166
167 return changed
168
169
170 def create_server_certificate():
171 cert = module.params.get("cert")
172 key = module.params.get("key")
173 cert_chain = module.params.get("cert_chain")
174
175 if not module.params.get("dup_ok"):
176 check_duplicate_cert(cert)
177
178 path = module.params.get("path")
179 name = module.params.get("name")
180
181 params = dict(
182 ServerCertificateName=name,
183 CertificateBody=cert,
184 PrivateKey=key,
185 )
186
187 if cert_chain:
188 params["CertificateChain"] = cert_chain
189 if path:
190 params["Path"] = path
191
192 if module.check_mode:
193 return True
194
195 try:
196 client.upload_server_certificate(aws_retry=True, **params)
197 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
198 module.fail_json_aws(e, msg=f"Failed to update server certificate {name}")
199
200 return True
201
202
203 def rename_server_certificate(current_cert):
204 name = module.params.get("name")
205 new_name = module.params.get("new_name")
206 new_path = module.params.get("new_path")
207
208 changes = dict()
209
210 # Try to be nice, if we've already been renamed exit quietly.
211 if not current_cert:
212 current_cert = get_server_certificate(new_name)
213 else:
214 if new_name:
215 changes["NewServerCertificateName"] = new_name
216
217 cert_metadata = current_cert.get("server_certificate_metadata", {})
218
219 if not current_cert:
220 module.fail_json(msg=f"Unable to find certificate {name}")
221
222 current_path = cert_metadata.get("path", None)
223 if new_path and current_path != new_path:
224 changes["NewPath"] = new_path
225
226 if not changes:
227 return False
228
229 if module.check_mode:
230 return True
231
232 try:
233 client.update_server_certificate(aws_retry=True, ServerCertificateName=name, **changes)
234 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
235 module.fail_json_aws(e, msg=f"Failed to update server certificate {name}", changes=changes)
236
237 return True
238
239
240 def delete_server_certificate(current_cert):
241 if not current_cert:
242 return False
243
244 if module.check_mode:
245 return True
246
247 name = module.params.get("name")
248
249 try:
250 client.delete_server_certificate(
251 aws_retry=True,
252 ServerCertificateName=name,
253 )
254 except is_boto3_error_code("NoSuchEntity"):
255 return None
256 except (
257 botocore.exceptions.ClientError,
258 botocore.exceptions.BotoCoreError,
259 ) as e: # pylint: disable=duplicate-except
260 module.fail_json_aws(e, msg=f"Failed to delete server certificate {name}")
261
262 return True
263
264
265 def get_server_certificate(name):
266 if not name:
267 return None
268 try:
269 result = client.get_server_certificate(
270 aws_retry=True,
271 ServerCertificateName=name,
272 )
273 except is_boto3_error_code("NoSuchEntity"):
274 return None
275 except (
276 botocore.exceptions.ClientError,
277 botocore.exceptions.BotoCoreError,
278 ) as e: # pylint: disable=duplicate-except
279 module.fail_json_aws(e, msg=f"Failed to get server certificate {name}")
280 cert = dict(camel_dict_to_snake_dict(result.get("ServerCertificate")))
281 return cert
282
283
284 def compatability_results(current_cert):
285 compat_results = dict()
286
287 if not current_cert:
288 return compat_results
289
290 metadata = current_cert.get("server_certificate_metadata", {})
291
292 if current_cert.get("certificate_body", None):
293 compat_results["cert_body"] = current_cert.get("certificate_body")
294 if current_cert.get("certificate_chain", None):
295 compat_results["chain_cert_body"] = current_cert.get("certificate_chain")
296 if metadata.get("arn", None):
297 compat_results["arn"] = metadata.get("arn")
298 if metadata.get("expiration", None):
299 compat_results["expiration_date"] = metadata.get("expiration")
300 if metadata.get("path", None):
301 compat_results["cert_path"] = metadata.get("path")
302 if metadata.get("server_certificate_name", None):
303 compat_results["name"] = metadata.get("server_certificate_name")
304 if metadata.get("upload_date", None):
305 compat_results["upload_date"] = metadata.get("upload_date")
306
307 return compat_results
308
309
310 def main():
311 global module
312 global client
313
314 argument_spec = dict(
315 state=dict(required=True, choices=["present", "absent"]),
316 name=dict(required=True),
317 cert=dict(),
318 key=dict(no_log=True),
319 cert_chain=dict(),
320 new_name=dict(),
321 path=dict(default="/"),
322 new_path=dict(),
323 dup_ok=dict(type="bool", default=True),
324 )
325
326 module = AnsibleAWSModule(
327 argument_spec=argument_spec,
328 mutually_exclusive=[
329 ["new_path", "key"],
330 ["new_path", "cert"],
331 ["new_path", "cert_chain"],
332 ["new_name", "key"],
333 ["new_name", "cert"],
334 ["new_name", "cert_chain"],
335 ],
336 supports_check_mode=True,
337 )
338
339 client = module.client("iam", retry_decorator=AWSRetry.jittered_backoff())
340
341 state = module.params.get("state")
342 name = module.params.get("name")
343 new_name = module.params.get("new_name")
344 new_path = module.params.get("new_path")
345
346 current_cert = get_server_certificate(name)
347
348 results = dict()
349 if state == "absent":
350 changed = delete_server_certificate(current_cert)
351 if changed:
352 results["deleted_cert"] = name
353 else:
354 msg = f"Certificate with the name {name} already absent"
355 results["msg"] = msg
356 else:
357 if new_name or new_path:
358 changed = rename_server_certificate(current_cert)
359 if new_name:
360 name = new_name
361 updated_cert = get_server_certificate(name)
362 elif current_cert:
363 changed = update_server_certificate(current_cert)
364 updated_cert = get_server_certificate(name)
365 else:
366 changed = create_server_certificate()
367 updated_cert = get_server_certificate(name)
368
369 results["server_certificate"] = updated_cert
370 compat_results = compatability_results(updated_cert)
371 if compat_results:
372 results.update(compat_results)
373
374 module.exit_json(changed=changed, **results)
375
376
377 if __name__ == "__main__":
378 main()