Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2019 Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 # Author:
8 # - Matthew Davis <[email protected]>
9 # on behalf of Telstra Corporation Limited
10
11 DOCUMENTATION = r"""
12 ---
13 module: acm_certificate
14 short_description: Upload and delete certificates in the AWS Certificate Manager service
15 version_added: 1.0.0
16 description:
17 - >
18 Import and delete certificates in Amazon Web Service's Certificate
19 Manager (AWS ACM).
20 - >
21 This module does not currently interact with AWS-provided certificates.
22 It currently only manages certificates provided to AWS by the user.
23 - The ACM API allows users to upload multiple certificates for the same domain
24 name, and even multiple identical certificates. This module attempts to
25 restrict such freedoms, to be idempotent, as per the Ansible philosophy.
26 It does this through applying AWS resource "Name" tags to ACM certificates.
27 - >
28 When I(state=present),
29 if there is one certificate in ACM
30 with a C(Name) tag equal to the I(name_tag) parameter,
31 and an identical body and chain,
32 this task will succeed without effect.
33 - >
34 When I(state=present),
35 if there is one certificate in ACM
36 a I(Name) tag equal to the I(name_tag) parameter,
37 and a different body,
38 this task will overwrite that certificate.
39 - >
40 When I(state=present),
41 if there are multiple certificates in ACM
42 with a I(Name) tag equal to the I(name_tag) parameter,
43 this task will fail.
44 - >
45 When I(state=absent) and I(certificate_arn) is defined,
46 this module will delete the ACM resource with that ARN if it exists in this
47 region, and succeed without effect if it doesn't exist.
48 - >
49 When I(state=absent) and I(domain_name) is defined, this module will delete
50 all ACM resources in this AWS region with a corresponding domain name.
51 If there are none, it will succeed without effect.
52 - >
53 When I(state=absent) and I(certificate_arn) is not defined,
54 and I(domain_name) is not defined, this module will delete all ACM resources
55 in this AWS region with a corresponding I(Name) tag.
56 If there are none, it will succeed without effect.
57 - >
58 Note that this may not work properly with keys of size 4096 bits, due to a
59 limitation of the ACM API.
60 - Prior to release 5.0.0 this module was called C(community.aws.aws_acm).
61 The usage did not change.
62 options:
63 certificate:
64 description:
65 - The body of the PEM encoded public certificate.
66 - Required when I(state) is not C(absent) and the certificate does not exist.
67 - >
68 If your certificate is in a file,
69 use C(lookup('file', 'path/to/cert.pem')).
70 type: str
71 certificate_arn:
72 description:
73 - The ARN of a certificate in ACM to modify or delete.
74 - >
75 If I(state=present), the certificate with the specified ARN can be updated.
76 For example, this can be used to add/remove tags to an existing certificate.
77 - >
78 If I(state=absent), you must provide one of
79 I(certificate_arn), I(domain_name) or I(name_tag).
80 - >
81 If I(state=absent) and no resource exists with this ARN in this region,
82 the task will succeed with no effect.
83 - >
84 If I(state=absent) and the corresponding resource exists in a different
85 region, this task may report success without deleting that resource.
86 type: str
87 aliases: [arn]
88 certificate_chain:
89 description:
90 - The body of the PEM encoded chain for your certificate.
91 - >
92 If your certificate chain is in a file,
93 use C(lookup('file', 'path/to/chain.pem')).
94 - Ignored when I(state=absent)
95 type: str
96 domain_name:
97 description:
98 - The domain name of the certificate.
99 - >
100 If I(state=absent) and I(domain_name) is specified,
101 this task will delete all ACM certificates with this domain.
102 - >
103 Exactly one of I(domain_name), I(name_tag) and I(certificate_arn)
104 must be provided.
105 - >
106 If I(state=present) this must not be specified.
107 (Since the domain name is encoded within the public certificate's body.)
108 type: str
109 aliases: [domain]
110 name_tag:
111 description:
112 - >
113 The unique identifier for tagging resources using AWS tags,
114 with key I(Name).
115 - This can be any set of characters accepted by AWS for tag values.
116 - >
117 This is to ensure Ansible can treat certificates idempotently,
118 even though the ACM API allows duplicate certificates.
119 - If I(state=preset), this must be specified.
120 - >
121 If I(state=absent) and I(name_tag) is specified,
122 this task will delete all ACM certificates with this Name tag.
123 - >
124 If I(state=absent), you must provide exactly one of
125 I(certificate_arn), I(domain_name) or I(name_tag).
126 - >
127 If both I(name_tag) and the 'Name' tag in I(tags) are set,
128 the values must be the same.
129 - >
130 If the 'Name' tag in I(tags) is not set and I(name_tag) is set,
131 the I(name_tag) value is copied to I(tags).
132 type: str
133 aliases: [name]
134 private_key:
135 description:
136 - The body of the PEM encoded private key.
137 - Required when I(state=present) and the certificate does not exist.
138 - Ignored when I(state=absent).
139 - >
140 If your private key is in a file,
141 use C(lookup('file', 'path/to/key.pem')).
142 type: str
143 state:
144 description:
145 - >
146 If I(state=present), the specified public certificate and private key
147 will be uploaded, with I(Name) tag equal to I(name_tag).
148 - >
149 If I(state=absent), any certificates in this region
150 with a corresponding I(domain_name), I(name_tag) or I(certificate_arn)
151 will be deleted.
152 choices: [present, absent]
153 default: present
154 type: str
155
156 notes:
157 - Support for I(tags) and I(purge_tags) was added in release 3.2.0
158 author:
159 - Matthew Davis (@matt-telstra) on behalf of Telstra Corporation Limited
160 extends_documentation_fragment:
161 - amazon.aws.common.modules
162 - amazon.aws.region.modules
163 - amazon.aws.tags
164 - amazon.aws.boto3
165 """
166
167 EXAMPLES = r"""
168
169 - name: upload a self-signed certificate
170 community.aws.acm_certificate:
171 certificate: "{{ lookup('file', 'cert.pem' ) }}"
172 privateKey: "{{ lookup('file', 'key.pem' ) }}"
173 name_tag: my_cert # to be applied through an AWS tag as "Name":"my_cert"
174 region: ap-southeast-2 # AWS region
175
176 - name: create/update a certificate with a chain
177 community.aws.acm_certificate:
178 certificate: "{{ lookup('file', 'cert.pem' ) }}"
179 private_key: "{{ lookup('file', 'key.pem' ) }}"
180 name_tag: my_cert
181 certificate_chain: "{{ lookup('file', 'chain.pem' ) }}"
182 state: present
183 region: ap-southeast-2
184 register: cert_create
185
186 - name: print ARN of cert we just created
187 ansible.builtin.debug:
188 var: cert_create.certificate.arn
189
190 - name: delete the cert we just created
191 community.aws.acm_certificate:
192 name_tag: my_cert
193 state: absent
194 region: ap-southeast-2
195
196 - name: delete a certificate with a particular ARN
197 community.aws.acm_certificate:
198 certificate_arn: "arn:aws:acm:ap-southeast-2:123456789012:certificate/01234567-abcd-abcd-abcd-012345678901"
199 state: absent
200 region: ap-southeast-2
201
202 - name: delete all certificates with a particular domain name
203 community.aws.acm_certificate:
204 domain_name: acm.ansible.com
205 state: absent
206 region: ap-southeast-2
207
208 - name: add tags to an existing certificate with a particular ARN
209 community.aws.acm_certificate:
210 certificate_arn: "arn:aws:acm:ap-southeast-2:123456789012:certificate/01234567-abcd-abcd-abcd-012345678901"
211 tags:
212 Name: my_certificate
213 Application: search
214 Environment: development
215 purge_tags: true
216 """
217
218 RETURN = r"""
219 certificate:
220 description: Information about the certificate which was uploaded
221 type: complex
222 returned: when I(state=present)
223 contains:
224 arn:
225 description: The ARN of the certificate in ACM
226 type: str
227 returned: when I(state=present) and not in check mode
228 sample: "arn:aws:acm:ap-southeast-2:123456789012:certificate/01234567-abcd-abcd-abcd-012345678901"
229 domain_name:
230 description: The domain name encoded within the public certificate
231 type: str
232 returned: when I(state=present)
233 sample: acm.ansible.com
234 arns:
235 description: A list of the ARNs of the certificates in ACM which were deleted
236 type: list
237 elements: str
238 returned: when I(state=absent)
239 sample:
240 - "arn:aws:acm:ap-southeast-2:123456789012:certificate/01234567-abcd-abcd-abcd-012345678901"
241 """
242
243
244 import base64
245 import re # regex library
246 from copy import deepcopy
247
248 try:
249 import botocore
250 except ImportError:
251 pass # handled by AnsibleAWSModule
252
253 from ansible.module_utils._text import to_text
254
255 from ansible_collections.amazon.aws.plugins.module_utils.acm import ACMServiceManager
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.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
261
262
263 def ensure_tags(client, module, resource_arn, existing_tags, tags, purge_tags):
264 if tags is None:
265 return (False, existing_tags)
266
267 tags_to_add, tags_to_remove = compare_aws_tags(existing_tags, tags, purge_tags)
268 changed = bool(tags_to_add or tags_to_remove)
269 if tags_to_add and not module.check_mode:
270 try:
271 client.add_tags_to_certificate(
272 CertificateArn=resource_arn,
273 Tags=ansible_dict_to_boto3_tag_list(tags_to_add),
274 )
275 except (
276 botocore.exceptions.ClientError,
277 botocore.exceptions.BotoCoreError,
278 ) as e:
279 module.fail_json_aws(e, f"Couldn't add tags to certificate {resource_arn}")
280 if tags_to_remove and not module.check_mode:
281 # remove_tags_from_certificate wants a list of key, value pairs, not a list of keys.
282 tags_list = [{"Key": key, "Value": existing_tags.get(key)} for key in tags_to_remove]
283 try:
284 client.remove_tags_from_certificate(
285 CertificateArn=resource_arn,
286 Tags=tags_list,
287 )
288 except (
289 botocore.exceptions.ClientError,
290 botocore.exceptions.BotoCoreError,
291 ) as e:
292 module.fail_json_aws(e, f"Couldn't remove tags from certificate {resource_arn}")
293 new_tags = deepcopy(existing_tags)
294 for key, value in tags_to_add.items():
295 new_tags[key] = value
296 for key in tags_to_remove:
297 new_tags.pop(key, None)
298 return (changed, new_tags)
299
300
301 # Takes in two text arguments
302 # Each a PEM encoded certificate
303 # Or a chain of PEM encoded certificates
304 # May include some lines between each chain in the cert, e.g. "Subject: ..."
305 # Returns True iff the chains/certs are functionally identical (including chain order)
306 def chain_compare(module, a, b):
307 chain_a_pem = pem_chain_split(module, a)
308 chain_b_pem = pem_chain_split(module, b)
309
310 if len(chain_a_pem) != len(chain_b_pem):
311 return False
312
313 # Chain length is the same
314 for ca, cb in zip(chain_a_pem, chain_b_pem):
315 der_a = PEM_body_to_DER(module, ca)
316 der_b = PEM_body_to_DER(module, cb)
317 if der_a != der_b:
318 return False
319
320 return True
321
322
323 # Takes in PEM encoded data with no headers
324 # returns equivilent DER as byte array
325 def PEM_body_to_DER(module, pem):
326 try:
327 der = base64.b64decode(to_text(pem))
328 except (ValueError, TypeError) as e:
329 module.fail_json_aws(e, msg="Unable to decode certificate chain")
330 return der
331
332
333 # Store this globally to avoid repeated recompilation
334 pem_chain_split_regex = re.compile(
335 r"------?BEGIN [A-Z0-9. ]*CERTIFICATE------?([a-zA-Z0-9\+\/=\s]+)------?END [A-Z0-9. ]*CERTIFICATE------?"
336 )
337
338
339 # Use regex to split up a chain or single cert into an array of base64 encoded data
340 # Using "-----BEGIN CERTIFICATE-----" and "----END CERTIFICATE----"
341 # Noting that some chains have non-pem data in between each cert
342 # This function returns only what's between the headers, excluding the headers
343 def pem_chain_split(module, pem):
344 pem_arr = re.findall(pem_chain_split_regex, to_text(pem))
345
346 if len(pem_arr) == 0:
347 # This happens if the regex doesn't match at all
348 module.fail_json(msg="Unable to split certificate chain. Possibly zero-length chain?")
349
350 return pem_arr
351
352
353 def update_imported_certificate(client, module, acm, old_cert, desired_tags):
354 """
355 Update the existing certificate that was previously imported in ACM.
356 """
357 module.debug("Existing certificate found in ACM")
358 if ("tags" not in old_cert) or ("Name" not in old_cert["tags"]):
359 # shouldn't happen
360 module.fail_json(msg="Internal error, unsure which certificate to update", certificate=old_cert)
361 if module.params.get("name_tag") is not None and (old_cert["tags"]["Name"] != module.params.get("name_tag")):
362 # This could happen if the user identified the certificate using 'certificate_arn' or 'domain_name',
363 # and the 'Name' tag in the AWS API does not match the ansible 'name_tag'.
364 module.fail_json(msg="Internal error, Name tag does not match", certificate=old_cert)
365 if "certificate" not in old_cert:
366 # shouldn't happen
367 module.fail_json(msg="Internal error, unsure what the existing cert in ACM is", certificate=old_cert)
368
369 cert_arn = None
370 # Are the existing certificate in ACM and the local certificate the same?
371 same = True
372 if module.params.get("certificate") is not None:
373 same &= chain_compare(module, old_cert["certificate"], module.params["certificate"])
374 if module.params["certificate_chain"]:
375 # Need to test this
376 # not sure if Amazon appends the cert itself to the chain when self-signed
377 same &= chain_compare(module, old_cert["certificate_chain"], module.params["certificate_chain"])
378 else:
379 # When there is no chain with a cert
380 # it seems Amazon returns the cert itself as the chain
381 same &= chain_compare(module, old_cert["certificate_chain"], module.params["certificate"])
382
383 if same:
384 module.debug("Existing certificate in ACM is the same")
385 cert_arn = old_cert["certificate_arn"]
386 changed = False
387 else:
388 absent_args = ["certificate", "name_tag", "private_key"]
389 if sum([(module.params[a] is not None) for a in absent_args]) < 3:
390 module.fail_json(
391 msg="When importing a certificate, all of 'name_tag', 'certificate' and 'private_key' must be specified"
392 )
393 module.debug("Existing certificate in ACM is different, overwriting")
394 changed = True
395 if module.check_mode:
396 cert_arn = old_cert["certificate_arn"]
397 # note: returned domain will be the domain of the previous cert
398 else:
399 # update cert in ACM
400 cert_arn = acm.import_certificate(
401 client,
402 module,
403 certificate=module.params["certificate"],
404 private_key=module.params["private_key"],
405 certificate_chain=module.params["certificate_chain"],
406 arn=old_cert["certificate_arn"],
407 tags=desired_tags,
408 )
409 return (changed, cert_arn)
410
411
412 def import_certificate(client, module, acm, desired_tags):
413 """
414 Import a certificate to ACM.
415 """
416 # Validate argument requirements
417 absent_args = ["certificate", "name_tag", "private_key"]
418 cert_arn = None
419 if sum([(module.params[a] is not None) for a in absent_args]) < 3:
420 module.fail_json(
421 msg="When importing a new certificate, all of 'name_tag', 'certificate' and 'private_key' must be specified"
422 )
423 module.debug("No certificate in ACM. Creating new one.")
424 changed = True
425 if module.check_mode:
426 domain = "example.com"
427 module.exit_json(certificate=dict(domain_name=domain), changed=True)
428 else:
429 cert_arn = acm.import_certificate(
430 client,
431 module,
432 certificate=module.params["certificate"],
433 private_key=module.params["private_key"],
434 certificate_chain=module.params["certificate_chain"],
435 tags=desired_tags,
436 )
437 return (changed, cert_arn)
438
439
440 def ensure_certificates_present(client, module, acm, certificates, desired_tags, filter_tags):
441 cert_arn = None
442 changed = False
443 if len(certificates) > 1:
444 msg = f"More than one certificate with Name={module.params['name_tag']} exists in ACM in this region"
445 module.fail_json(msg=msg, certificates=certificates)
446 elif len(certificates) == 1:
447 # Update existing certificate that was previously imported to ACM.
448 (changed, cert_arn) = update_imported_certificate(client, module, acm, certificates[0], desired_tags)
449 else: # len(certificates) == 0
450 # Import new certificate to ACM.
451 (changed, cert_arn) = import_certificate(client, module, acm, desired_tags)
452
453 # Add/remove tags to/from certificate
454 try:
455 existing_tags = boto3_tag_list_to_ansible_dict(
456 client.list_tags_for_certificate(CertificateArn=cert_arn)["Tags"]
457 )
458 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
459 module.fail_json_aws(e, "Couldn't get tags for certificate")
460
461 purge_tags = module.params.get("purge_tags")
462 (c, new_tags) = ensure_tags(client, module, cert_arn, existing_tags, desired_tags, purge_tags)
463 changed |= c
464 domain = acm.get_domain_of_cert(client=client, module=module, arn=cert_arn)
465 module.exit_json(certificate=dict(domain_name=domain, arn=cert_arn, tags=new_tags), changed=changed)
466
467
468 def ensure_certificates_absent(client, module, acm, certificates):
469 for cert in certificates:
470 if not module.check_mode:
471 acm.delete_certificate(client, module, cert["certificate_arn"])
472 module.exit_json(arns=[cert["certificate_arn"] for cert in certificates], changed=(len(certificates) > 0))
473
474
475 def main():
476 argument_spec = dict(
477 certificate=dict(),
478 certificate_arn=dict(aliases=["arn"]),
479 certificate_chain=dict(),
480 domain_name=dict(aliases=["domain"]),
481 name_tag=dict(aliases=["name"]),
482 private_key=dict(no_log=True),
483 tags=dict(type="dict", aliases=["resource_tags"]),
484 purge_tags=dict(type="bool", default=True),
485 state=dict(default="present", choices=["present", "absent"]),
486 )
487 module = AnsibleAWSModule(
488 argument_spec=argument_spec,
489 supports_check_mode=True,
490 )
491 acm = ACMServiceManager(module)
492
493 # Check argument requirements
494 if module.params["state"] == "present":
495 # at least one of these should be specified.
496 absent_args = ["certificate_arn", "domain_name", "name_tag"]
497 if sum([(module.params[a] is not None) for a in absent_args]) < 1:
498 for a in absent_args:
499 module.debug(f"{a} is {module.params[a]}")
500 module.fail_json(
501 msg="If 'state' is specified as 'present' then at least one of 'name_tag', 'certificate_arn' or 'domain_name' must be specified"
502 )
503 else: # absent
504 # exactly one of these should be specified
505 absent_args = ["certificate_arn", "domain_name", "name_tag"]
506 if sum([(module.params[a] is not None) for a in absent_args]) != 1:
507 for a in absent_args:
508 module.debug(f"{a} is {module.params[a]}")
509 module.fail_json(
510 msg="If 'state' is specified as 'absent' then exactly one of 'name_tag', 'certificate_arn' or 'domain_name' must be specified"
511 )
512
513 filter_tags = None
514 desired_tags = None
515 if module.params.get("tags") is not None:
516 desired_tags = module.params["tags"]
517 else:
518 # Because we're setting the Name tag, we need to explicitly not purge when tags isn't passed
519 module.params["purge_tags"] = False
520 if module.params.get("name_tag") is not None:
521 # The module was originally implemented to filter certificates based on the 'Name' tag.
522 # Other tags are not used to filter certificates.
523 # It would make sense to replace the existing name_tag, domain, certificate_arn attributes
524 # with a 'filter' attribute, but that would break backwards-compatibility.
525 filter_tags = dict(Name=module.params["name_tag"])
526 if desired_tags is not None:
527 if "Name" in desired_tags:
528 if desired_tags["Name"] != module.params["name_tag"]:
529 module.fail_json(msg="Value of 'name_tag' conflicts with value of 'tags.Name'")
530 else:
531 desired_tags["Name"] = module.params["name_tag"]
532 else:
533 desired_tags = deepcopy(filter_tags)
534
535 client = module.client("acm")
536
537 # fetch the list of certificates currently in ACM
538 certificates = acm.get_certificates(
539 client=client,
540 module=module,
541 domain_name=module.params["domain_name"],
542 arn=module.params["certificate_arn"],
543 only_tags=filter_tags,
544 )
545
546 module.debug(f"Found {len(certificates)} corresponding certificates in ACM")
547 if module.params["state"] == "present":
548 ensure_certificates_present(client, module, acm, certificates, desired_tags, filter_tags)
549
550 else: # state == absent
551 ensure_certificates_absent(client, module, acm, certificates)
552
553
554 if __name__ == "__main__":
555 # tests()
556 main()