Debian Codegraph @

ansible_collections/community/crypto/plugins/modules/acme_certificate.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2016 Michael Gruener <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: acme_certificate
10 author: "Michael Gruener (@mgruener)"
11 short_description: Create SSL/TLS certificates with the ACME protocol
12 description:
13 - Create and renew SSL/TLS certificates with a CA supporting the L(ACME protocol,https://tools.ietf.org/html/rfc8555), such
14 as L(Let's Encrypt,https://letsencrypt.org/).
15 The current implementation supports the V(http-01), V(dns-01), V(dns-account-01), V(dns-persist-01), and V(tls-alpn-01) challenges.
16 - To use this module, it has to be executed twice. Either as two different tasks in the same run or during two runs. Note
17 that the output of the first run needs to be recorded and passed to the second run as the module argument O(data).
18 - Between these two tasks you have to fulfill the required steps for the chosen challenge by whatever means necessary.
19 For V(http-01) that means creating the necessary challenge file on the destination webserver.
20 For V(dns-01), V(dns-account-01), and V(dns-persist-01) the necessary DNS records have to be created.
21 For V(tls-alpn-01) the necessary certificate has to be created and served.
22 It is I(not) the responsibility of this module to perform these steps.
23 - For details on how to fulfill these challenges, you might have to read through L(the main ACME specification,https://tools.ietf.org/html/rfc8555#section-8)
24 and the L(TLS-ALPN-01 specification,https://www.rfc-editor.org/rfc/rfc8737.html#section-3). Also, consider the examples
25 provided for this module.
26 - The module support for IP identifiers according to L(RFC 8738,https://www.rfc-editor.org/rfc/rfc8738.html).
27 - The module B(experimentally) supports the V(dns-account-01) challenge type according to
28 L(acme-dns-account-label draft 02, https://datatracker.ietf.org/doc/html/draft-ietf-acme-dns-account-label-02).
29 Note that the supported draft version can change at any time,
30 and changes will only be considered breaking once the draft reached RFC status.
31 - The module B(experimentally) supports the V(dns-persist-01) challenge type according to
32 L(acme-dns-persist draft 01, https://www.ietf.org/archive/id/draft-ietf-acme-dns-persist-01.html).
33 Note that the supported draft version can change at any time,
34 and changes will only be considered breaking once the draft reached RFC status.
35 notes:
36 - At least one of O(dest) and O(fullchain_dest) must be specified.
37 - This module includes basic account management functionality. If you want to have more control over your ACME account,
38 use the M(community.crypto.acme_account) module and disable account management for this module using the O(modify_account)
39 option.
40 - This module was called C(letsencrypt) before Ansible 2.6. The usage did not change.
41 seealso:
42 - name: The Let's Encrypt documentation
43 description: Documentation for the Let's Encrypt Certification Authority. Provides useful information for example on rate
44 limits.
45 link: https://letsencrypt.org/docs/
46 - name: Automatic Certificate Management Environment (ACME)
47 description: The specification of the ACME protocol (RFC 8555).
48 link: https://tools.ietf.org/html/rfc8555
49 - name: ACME TLS ALPN Challenge Extension
50 description: The specification of the V(tls-alpn-01) challenge (RFC 8737).
51 link: https://www.rfc-editor.org/rfc/rfc8737.html
52 - module: community.crypto.acme_challenge_cert_helper
53 description: Helps preparing V(tls-alpn-01) challenges.
54 - module: community.crypto.openssl_privatekey
55 description: Can be used to create private keys (both for certificates and accounts).
56 - module: community.crypto.openssl_privatekey_pipe
57 description: Can be used to create private keys without writing it to disk (both for certificates and accounts).
58 - module: community.crypto.openssl_csr
59 description: Can be used to create a Certificate Signing Request (CSR).
60 - module: community.crypto.openssl_csr_pipe
61 description: Can be used to create a Certificate Signing Request (CSR) without writing it to disk.
62 - module: community.crypto.certificate_complete_chain
63 description: Allows to find the root certificate for the returned fullchain.
64 - module: community.crypto.acme_certificate_revoke
65 description: Allows to revoke certificates.
66 - module: community.crypto.acme_account
67 description: Allows to create, modify or delete an ACME account.
68 - module: community.crypto.acme_inspect
69 description: Allows to debug problems.
70 - module: community.crypto.acme_certificate_deactivate_authz
71 description: Allows to deactivate (invalidate) ACME v2 orders.
72 extends_documentation_fragment:
73 - community.crypto._acme.basic
74 - community.crypto._acme.account
75 - community.crypto._acme.certificate
76 - community.crypto._attributes
77 - community.crypto._attributes.files
78 - community.crypto._attributes.actiongroup_acme
79 attributes:
80 check_mode:
81 support: full
82 diff_mode:
83 support: none
84 safe_file_operations:
85 support: full
86 idempotent:
87 support: partial
88 details:
89 - If O(force=true), the module is not idempotent.
90 If O(force=false), it depends on the certificate's validity period and the value of O(remaining_days).
91 - The second phase invocation of the module is always idempotent, assuming no error occurs.
92 options:
93 account_email:
94 description:
95 - The email address associated with this account.
96 - It will be used for certificate expiration warnings.
97 - Note that when O(modify_account) is not set to V(false) and you also used the M(community.crypto.acme_account) module
98 to specify more than one contact for your account, this module will update your account and restrict it to the (at
99 most one) contact email address specified here.
100 type: str
101 agreement:
102 description:
103 - URI to a terms of service document you agree to when using the ACME v1 service at O(acme_directory).
104 - Default is latest gathered from O(acme_directory) URL.
105 - This option has no longer any effect. It is deprecated and will be removed from community.crypto 4.0.0.
106 type: str
107 terms_agreed:
108 description:
109 - Boolean indicating whether you agree to the terms of service document.
110 - ACME servers can require this to be true.
111 type: bool
112 default: false
113 modify_account:
114 description:
115 - Boolean indicating whether the module should create the account if necessary, and update its contact data.
116 - Set to V(false) if you want to use the M(community.crypto.acme_account) module to manage your account instead, and
117 to avoid accidental creation of a new account using an old key if you changed the account key with M(community.crypto.acme_account).
118 - If set to V(false), O(terms_agreed) and O(account_email) are ignored.
119 - The current default V(true) is B(deprecated) and will change to V(false) in community.crypto 4.0.0.
120 type: bool
121 challenge:
122 description:
123 - The challenge to be performed.
124 - If set to V(no challenge), no challenge will be used. This is necessary for some private CAs which use External Account
125 Binding and other means of validating certificate assurance. For example, an account could be allowed to issue certificates
126 for C(foo.example.com) without any further validation for a certain period of time.
127 - Support for V(dns-account-01) and V(dns-persist-01) has been added in community.crypto 3.2.0.
128 type: str
129 default: http-01
130 choices:
131 - http-01
132 - dns-01
133 - dns-account-01
134 - dns-persist-01
135 - tls-alpn-01
136 - no challenge
137 csr:
138 aliases: ['src']
139 csr_content:
140 version_added: 1.2.0
141 data:
142 description:
143 - The data to validate ongoing challenges. This must be specified for the second run of the module only.
144 - The value that must be used here will be provided by a previous use of this module. See the examples for more details.
145 - Note that for ACME v2, only the C(order_uri) entry of O(data) will be used. For ACME v1, O(data) must be non-empty
146 to indicate the second stage is active; all needed data will be taken from the CSR.
147 - 'I(Note): the O(data) option was marked as C(no_log) up to Ansible 2.5. From Ansible 2.6 on, it is no longer marked
148 this way as it causes error messages to be come unusable, and O(data) does not contain any information which can be
149 used without having access to the account key or which are not public anyway.'
150 type: dict
151 dest:
152 description:
153 - The destination file for the certificate.
154 - Required if O(fullchain_dest) is not specified.
155 type: path
156 aliases: ['cert']
157 fullchain_dest:
158 description:
159 - The destination file for the full chain (that is, a certificate followed by chain of intermediate certificates).
160 - Required if O(dest) is not specified.
161 type: path
162 aliases: ['fullchain']
163 chain_dest:
164 description:
165 - If specified, the intermediate certificate will be written to this file.
166 type: path
167 aliases: ['chain']
168 remaining_days:
169 description:
170 - The number of days the certificate must have left being valid. If RV(cert_days) < O(remaining_days), then it will
171 be renewed. If the certificate is not renewed, module return values will not include RV(challenge_data).
172 - To make sure that the certificate is renewed in any case, you can use the O(force) option.
173 type: int
174 default: 10
175 deactivate_authzs:
176 description:
177 - Deactivate authentication objects (authz) after issuing a certificate, or when issuing the certificate failed.
178 - Authentication objects are bound to an account key and remain valid for a certain amount of time, and can be used
179 to issue certificates without having to re-authenticate the domain. This can be a security concern.
180 type: bool
181 default: false
182 force:
183 description:
184 - Enforces the execution of the challenge and validation, even if an existing certificate is still valid for more than
185 O(remaining_days).
186 - This is especially helpful when having an updated CSR, for example with additional domains for which a new certificate
187 is desired.
188 type: bool
189 default: false
190 retrieve_all_alternates:
191 description:
192 - When set to V(true), will retrieve all alternate trust chains offered by the ACME CA. These will not be written to
193 disk, but will be returned together with the main chain as RV(all_chains). See the documentation for the RV(all_chains)
194 return value for details.
195 type: bool
196 default: false
197 select_chain:
198 description:
199 - Allows to specify criteria by which an (alternate) trust chain can be selected.
200 - The list of criteria will be processed one by one until a chain is found matching a criterium. If such a chain is
201 found, it will be used by the module instead of the default chain.
202 - If a criterium matches multiple chains, the first one matching will be returned. The order is determined by the ordering
203 of the C(Link) headers returned by the ACME server and might not be deterministic.
204 - Every criterium can consist of multiple different conditions, like O(select_chain[].issuer) and O(select_chain[].subject).
205 For the criterium to match a chain, all conditions must apply to the same certificate in the chain.
206 - This option can only be used with the C(cryptography) backend.
207 type: list
208 elements: dict
209 version_added: '1.0.0'
210 suboptions:
211 test_certificates:
212 description:
213 - Determines which certificates in the chain will be tested.
214 - V(all) tests all certificates in the chain (excluding the leaf, which is identical in all chains).
215 - V(first) only tests the first certificate in the chain, that is the one which signed the leaf.
216 - V(last) only tests the last certificate in the chain, that is the one furthest away from the leaf. Its issuer
217 is the root certificate of this chain.
218 type: str
219 default: all
220 choices: [first, last, all]
221 issuer:
222 description:
223 - Allows to specify parts of the issuer of a certificate in the chain must have to be selected.
224 - If O(select_chain[].issuer) is empty, any certificate will match.
225 - 'An example value would be V({"commonName": "My Preferred CA Root"}).'
226 type: dict
227 subject:
228 description:
229 - Allows to specify parts of the subject of a certificate in the chain must have to be selected.
230 - If O(select_chain[].subject) is empty, any certificate will match.
231 - 'An example value would be V({"CN": "My Preferred CA Intermediate"}).'
232 type: dict
233 subject_key_identifier:
234 description:
235 - Checks for the SubjectKeyIdentifier extension. This is an identifier based on the private key of the intermediate
236 certificate.
237 - The identifier must be of the form V(A8:4A:6A:63:04:7D:DD:BA:E6:D1:39:B7:A6:45:65:EF:F3:A8:EC:A1).
238 type: str
239 authority_key_identifier:
240 description:
241 - Checks for the AuthorityKeyIdentifier extension. This is an identifier based on the private key of the issuer
242 of the intermediate certificate.
243 - The identifier must be of the form V(C4:A7:B1:A4:7B:2C:71:FA:DB:E1:4B:90:75:FF:C4:15:60:85:89:10).
244 type: str
245 include_renewal_cert_id:
246 description:
247 - Determines whether to request renewal of an existing certificate according to L(Section 5 of RFC 9773,
248 https://www.rfc-editor.org/rfc/rfc9773.html#section-5).
249 - This is only used when the certificate specified in O(dest) or O(fullchain_dest) already exists.
250 - Generally you should use V(when_ari_supported) if you know that the ACME service supports a compatible draft (or final
251 version, once it is out) of the ARI extension. V(always) should never be necessary. If you are not sure, or if you
252 receive strange errors on invalid C(replaces) values in order objects, use V(never), which also happens to be the
253 default.
254 - ACME servers might refuse to create new orders with C(replaces) for certificates that already have an existing order.
255 This can happen if this module is used to create an order, and then the playbook/role fails in case the challenges
256 cannot be set up. If the playbook/role does not record the order data to continue with the existing order, but tries
257 to create a new one on the next run, creating the new order might fail. If O(order_creation_error_strategy=fail)
258 this will make the module fail. O(order_creation_error_strategy=auto) and
259 O(order_creation_error_strategy=retry_without_replaces_cert_id) will avoid this by leaving away C(replaces)
260 on retries.
261 - If O(order_creation_error_strategy=fail), for the above reason, this option should only be set to a value different
262 from V(never) if the role/playbook using it keeps track of order data accross restarts, or if it takes care to
263 deactivate orders whose processing is aborted. Orders can be deactivated with the
264 M(community.crypto.acme_certificate_deactivate_authz) module.
265 type: str
266 choices:
267 never: Never send the certificate ID of the certificate to renew.
268 when_ari_supported: Only send the certificate ID if the ARI endpoint is found in the ACME directory.
269 always: Will always send the certificate ID of the certificate to renew.
270 default: never
271 version_added: 2.20.0
272 profile:
273 description:
274 - Chose a specific profile for certificate selection. The available profiles depend on the CA.
275 - See L(a blog post by Let's Encrypt, https://letsencrypt.org/2025/01/09/acme-profiles/) and
276 L(draft-aaron-acme-profiles-01, https://datatracker.ietf.org/doc/draft-aaron-acme-profiles/)
277 for more information.
278 type: str
279 version_added: 2.24.0
280 order_creation_error_strategy:
281 description:
282 - Selects the error handling strategy for ACME protocol errors if creating a new ACME order fails.
283 type: str
284 choices:
285 auto:
286 - An unspecified algorithm that tries to be clever.
287 - Right now identical to V(retry_without_replaces_cert_id).
288 always:
289 - Always retry, until the limit in O(order_creation_max_retries) has been reached.
290 fail:
291 - Simply fail in case of errors. Do not attempt to retry.
292 - This has been the default before community.crypto 2.24.0.
293 retry_without_replaces_cert_id:
294 - If O(include_renewal_cert_id) is present, creating the order will be tried again without C(replaces).
295 - The only exception is an error of type C(urn:ietf:params:acme:error:alreadyReplaced), that indicates that
296 the certificate was already replaced. This usually means something went wrong and the user should investigate.
297 default: auto
298 version_added: 2.24.0
299 order_creation_max_retries:
300 description:
301 - Depending on the strategy selected in O(order_creation_error_strategy), will retry creating new orders
302 for at most the specified amount of times.
303 type: int
304 default: 3
305 version_added: 2.24.0
306 """
307
308 EXAMPLES = r"""
309 ---
310 ### Example with HTTP challenge ###
311
312 - name: Create a challenge for sample.com using a account key from a variable.
313 community.crypto.acme_certificate:
314 account_key_content: "{{ account_private_key }}"
315 csr: /etc/pki/cert/csr/sample.com.csr
316 dest: /etc/httpd/ssl/sample.com.crt
317 modify_account: false
318 register: sample_com_challenge
319
320 # Alternative first step:
321 - name: Create a challenge for sample.com using a account key from Hashi Vault.
322 community.crypto.acme_certificate:
323 account_key_content: >-
324 {{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/account_private_key:value') }}
325 csr: /etc/pki/cert/csr/sample.com.csr
326 fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
327 modify_account: false
328 register: sample_com_challenge
329
330 # Alternative first step:
331 - name: Create a challenge for sample.com using a account key file.
332 community.crypto.acme_certificate:
333 account_key_src: /etc/pki/cert/private/account.key
334 csr_content: "{{ lookup('file', '/etc/pki/cert/csr/sample.com.csr') }}"
335 dest: /etc/httpd/ssl/sample.com.crt
336 fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
337 modify_account: false
338 register: sample_com_challenge
339
340 # perform the necessary steps to fulfill the challenge
341 # for example:
342 #
343 # - name: Copy http-01 challenge for sample.com
344 # ansible.builtin.copy:
345 # dest: /var/www/html/{{ sample_com_challenge['challenge_data']['sample.com']['http-01']['resource'] }}
346 # content: "{{ sample_com_challenge['challenge_data']['sample.com']['http-01']['resource_value'] }}"
347 # when: sample_com_challenge is changed and 'sample.com' in sample_com_challenge['challenge_data']
348 #
349 # Alternative way:
350 #
351 # - name: Copy http-01 challenges
352 # ansible.builtin.copy:
353 # dest: /var/www/{{ item.key }}/{{ item.value['http-01']['resource'] }}
354 # content: "{{ item.value['http-01']['resource_value'] }}"
355 # loop: "{{ sample_com_challenge.challenge_data | dict2items }}"
356 # when: sample_com_challenge is changed
357
358 - name: Let the challenge be validated and retrieve the cert and intermediate certificate
359 community.crypto.acme_certificate:
360 account_key_src: /etc/pki/cert/private/account.key
361 csr: /etc/pki/cert/csr/sample.com.csr
362 dest: /etc/httpd/ssl/sample.com.crt
363 fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
364 chain_dest: /etc/httpd/ssl/sample.com-intermediate.crt
365 data: "{{ sample_com_challenge }}"
366 modify_account: false
367
368 ---
369 ### Example with DNS challenge against production ACME server ###
370
371 - name: Create a challenge for sample.com using a account key file.
372 community.crypto.acme_certificate:
373 account_key_src: /etc/pki/cert/private/account.key
374 account_email: [email protected]
375 src: /etc/pki/cert/csr/sample.com.csr
376 cert: /etc/httpd/ssl/sample.com.crt
377 challenge: dns-01
378 acme_directory: https://acme-v01.api.letsencrypt.org/directory
379 # Renew if the certificate is at least 30 days old
380 remaining_days: 60
381 modify_account: false
382 register: sample_com_challenge
383
384 # perform the necessary steps to fulfill the challenge
385 # for example:
386 #
387 # - name: Create DNS record for sample.com dns-01 challenge
388 # community.aws.route53:
389 # zone: sample.com
390 # record: "{{ sample_com_challenge.challenge_data['sample.com']['dns-01'].record }}"
391 # type: TXT
392 # ttl: 60
393 # state: present
394 # wait: true
395 # # Note: route53 requires TXT entries to be enclosed in quotes
396 # value: "{{ sample_com_challenge.challenge_data['sample.com']['dns-01'].resource_value | community.dns.quote_txt(always_quote=true) }}"
397 # when: sample_com_challenge is changed and 'sample.com' in sample_com_challenge.challenge_data
398 #
399 # Alternative way:
400 #
401 # - name: Create DNS records for dns-01 challenges
402 # community.aws.route53:
403 # zone: sample.com
404 # record: "{{ item.key }}"
405 # type: TXT
406 # ttl: 60
407 # state: present
408 # wait: true
409 # # Note: item.value is a list of TXT entries, and route53
410 # # requires every entry to be enclosed in quotes
411 # value: "{{ item.value | map('community.dns.quote_txt', always_quote=true) | list }}"
412 # loop: "{{ sample_com_challenge.challenge_data_dns | dict2items }}"
413 # when: sample_com_challenge is changed
414
415 - name: Let the challenge be validated and retrieve the cert and intermediate certificate
416 community.crypto.acme_certificate:
417 account_key_src: /etc/pki/cert/private/account.key
418 account_email: [email protected]
419 src: /etc/pki/cert/csr/sample.com.csr
420 cert: /etc/httpd/ssl/sample.com.crt
421 fullchain: /etc/httpd/ssl/sample.com-fullchain.crt
422 chain: /etc/httpd/ssl/sample.com-intermediate.crt
423 challenge: dns-01
424 acme_directory: https://acme-v01.api.letsencrypt.org/directory
425 remaining_days: 60
426 data: "{{ sample_com_challenge }}"
427 modify_account: false
428 when: sample_com_challenge is changed
429
430 # Alternative second step:
431 - name: Let the challenge be validated and retrieve the cert and intermediate certificate
432 community.crypto.acme_certificate:
433 account_key_src: /etc/pki/cert/private/account.key
434 account_email: [email protected]
435 src: /etc/pki/cert/csr/sample.com.csr
436 cert: /etc/httpd/ssl/sample.com.crt
437 fullchain: /etc/httpd/ssl/sample.com-fullchain.crt
438 chain: /etc/httpd/ssl/sample.com-intermediate.crt
439 challenge: tls-alpn-01
440 remaining_days: 60
441 data: "{{ sample_com_challenge }}"
442 # We use Let's Encrypt's ACME v2 endpoint
443 acme_directory: https://acme-v02.api.letsencrypt.org/directory
444 # The following makes sure that if a chain with /CN=DST Root CA X3 in its issuer is provided
445 # as an alternative, it will be selected. These are the roots cross-signed by IdenTrust.
446 # As long as Let's Encrypt provides alternate chains with the cross-signed root(s) when
447 # switching to their own ISRG Root X1 root, this will use the chain ending with a cross-signed
448 # root. This chain is more compatible with older TLS clients.
449 select_chain:
450 - test_certificates: last
451 issuer:
452 CN: DST Root CA X3
453 O: Digital Signature Trust Co.
454 modify_account: false
455 when: sample_com_challenge is changed
456 """
457
458 RETURN = r"""
459 cert_days:
460 description: The number of days the certificate remains valid.
461 returned: success
462 type: int
463 challenge_data:
464 description:
465 - Per identifier / challenge type challenge data.
466 - Since Ansible 2.8.5, only challenges which are not yet valid are returned.
467 returned: changed
468 type: dict
469 contains:
470 identifier:
471 description:
472 - For every identifier, provides a dictionary of challenge types mapping to challenge data.
473 - The keys in this dictionary are the identifiers. C(identifier) is a placeholder used in the documentation.
474 - Note that the keys are not valid Jinja2 identifiers.
475 returned: changed
476 type: dict
477 contains:
478 challenge-type:
479 description:
480 - Data for every challenge type.
481 - The keys in this dictionary are the challenge types. C(challenge-type) is a placeholder used in the documentation.
482 Possible keys are V(http-01), V(dns-01), V(dns-account-01), V(dns-persist-01), and V(tls-alpn-01).
483 - Note that the keys are not valid Jinja2 identifiers.
484 - B(Note) that this return value for V(dns-account-01) and V(dns-persist-01) challenges is B(experimental)
485 and can change in a breaking way also in minor releases, until the acme-dns-account-label respectively
486 the acme-dns-persist draft is in a more stable state.
487 returned: changed
488 type: dict
489 contains:
490 resource:
491 description: The challenge resource that must be created for validation.
492 returned: changed and challenge is not V(dns-persist-01)
493 type: str
494 sample: .well-known/acme-challenge/evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA
495 resource_original:
496 description:
497 - The original challenge resource including type identifier for V(tls-alpn-01) challenges.
498 returned: changed and O(challenge) is V(tls-alpn-01)
499 type: str
500 sample: DNS:example.com
501 resource_value:
502 description:
503 - The value the resource has to produce for the validation.
504 - For V(http-01), V(dns-01), and V(dns-account-01) challenges, the value can be used as-is.
505 - For V(tls-alpn-01) challenges, note that this return value contains a Base64 encoded version of the correct
506 binary blob which has to be put into the acmeValidation x509 extension; see U(https://www.rfc-editor.org/rfc/rfc8737.html#section-3)
507 for details. To do this, you might need the P(ansible.builtin.b64decode#filter) Jinja filter to extract
508 the binary blob from this return value.
509 returned: changed and challenge is not V(dns-persist-01)
510 type: str
511 sample: IlirfxKKXA...17Dt3juxGJ-PCt92wr-oA
512 record:
513 description: The full DNS record's name for the challenge.
514 returned: changed and challenge is V(dns-01) or V(dns-account-01)
515 type: str
516 sample: _acme-challenge.example.com
517 account_uri:
518 description:
519 - The account URI that must be mentioned in the DNS TXT record.
520 - B(Note) that the type of this return value might change in a breaking way also in minor releases,
521 until the acme-dns-persist draft is in a more stable state.
522 This challenge field is currently under discussion in the ACME WG.
523 returned: changed and challenge is V(dns-persist-01)
524 type: str
525 sample: https://ca.example/acct/123
526 issuer_domain_names:
527 description:
528 - One of the issuer domain names must be mentioned in the DNS TXT record.
529 returned: changed and challenge is V(dns-persist-01)
530 type: list
531 elements: str
532 sample:
533 - letsencrypt.org
534 challenge_data_dns:
535 description:
536 - List of TXT values per DNS record, in case challenge is V(dns-01) or V(dns-account-01).
537 - Since Ansible 2.8.5, only challenges which are not yet valid are returned.
538 returned: changed
539 type: dict
540 authorizations:
541 description:
542 - ACME authorization data.
543 - Maps an identifier to ACME authorization objects. See U(https://tools.ietf.org/html/rfc8555#section-7.1.4).
544 returned: changed
545 type: dict
546 sample:
547 example.com:
548 identifier:
549 type: dns
550 value: example.com
551 status: valid
552 expires: '2022-08-04T01:02:03.45Z'
553 challenges:
554 - url: https://example.org/acme/challenge/12345
555 type: http-01
556 status: valid
557 token: A5b1C3d2E9f8G7h6
558 validated: '2022-08-01T01:01:02.34Z'
559 wildcard: false
560 order_uri:
561 description: ACME order URI.
562 returned: changed
563 type: str
564 finalization_uri:
565 description: ACME finalization URI.
566 returned: changed
567 type: str
568 account_uri:
569 description: ACME account URI.
570 returned: changed
571 type: str
572 all_chains:
573 description:
574 - When O(retrieve_all_alternates) is set to V(true), the module will query the ACME server for alternate chains. This
575 return value will contain a list of all chains returned, the first entry being the main chain returned by the server.
576 - See L(Section 7.4.2 of RFC8555,https://tools.ietf.org/html/rfc8555#section-7.4.2) for details.
577 returned: when certificate was retrieved and O(retrieve_all_alternates) is set to V(true)
578 type: list
579 elements: dict
580 contains:
581 cert:
582 description:
583 - The leaf certificate itself, in PEM format.
584 type: str
585 returned: always
586 chain:
587 description:
588 - The certificate chain, excluding the root, as concatenated PEM certificates.
589 type: str
590 returned: always
591 full_chain:
592 description:
593 - The certificate chain, excluding the root, but including the leaf certificate, as concatenated PEM certificates.
594 type: str
595 returned: always
596 """
597
598 import os
599 import typing as t
600
601 from ansible_collections.community.crypto.plugins.module_utils._acme.account import (
602 ACMEAccount,
603 )
604 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
605 ACMEClient,
606 create_backend,
607 create_default_argspec,
608 )
609 from ansible_collections.community.crypto.plugins.module_utils._acme.certificates import (
610 CertificateChain,
611 Criterium,
612 )
613 from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import (
614 combine_identifier,
615 normalize_combined_identifier,
616 wait_for_validation,
617 )
618 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
619 ModuleFailException,
620 )
621 from ansible_collections.community.crypto.plugins.module_utils._acme.io import (
622 write_file,
623 )
624 from ansible_collections.community.crypto.plugins.module_utils._acme.orders import Order
625 from ansible_collections.community.crypto.plugins.module_utils._acme.utils import (
626 compute_cert_id,
627 pem_to_der,
628 )
629
630 if t.TYPE_CHECKING:
631 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
632
633 from ansible_collections.community.crypto.plugins.module_utils._acme.backends import ( # pragma: no cover
634 CertificateInformation,
635 CryptoBackend,
636 )
637 from ansible_collections.community.crypto.plugins.module_utils._acme.challenges import ( # pragma: no cover
638 Authorization,
639 )
640
641
642 NO_CHALLENGE = "no challenge"
643
644
645 class ACMECertificateClient:
646 """
647 ACME client class. Uses an ACME account object and a CSR to
648 start and validate ACME challenges and download the respective
649 certificates.
650 """
651
652 def __init__(self, module: AnsibleModule, backend: CryptoBackend):
653 self.module = module
654 self.version = module.params["acme_version"]
655 self.challenge = module.params["challenge"]
656 # We use None instead of a magic string for 'no challenge'
657 if self.challenge == NO_CHALLENGE:
658 self.challenge = None
659 self.csr = module.params["csr"]
660 self.csr_content = module.params["csr_content"]
661 self.dest = module.params.get("dest")
662 self.fullchain_dest = module.params.get("fullchain_dest")
663 self.chain_dest = module.params.get("chain_dest")
664 self.client = ACMEClient(module=module, backend=backend)
665 self.account = ACMEAccount(client=self.client)
666 self.directory = self.client.directory
667 self.data = module.params["data"]
668 self.authorizations: dict[str, Authorization] | None = None
669 self.cert_days = -1
670 self.order: Order | None = None
671 self.order_uri = self.data.get("order_uri") if self.data else None
672 self.all_chains: list[dict[str, t.Any]] | None = None
673 self.select_chain_matcher = []
674 self.include_renewal_cert_id = module.params["include_renewal_cert_id"]
675 self.profile = module.params["profile"]
676 self.order_creation_error_strategy = module.params[
677 "order_creation_error_strategy"
678 ]
679 self.order_creation_max_retries = module.params["order_creation_max_retries"]
680
681 if self.module.params["select_chain"]:
682 for criterium_idx, criterium in enumerate(
683 self.module.params["select_chain"]
684 ):
685 try:
686 self.select_chain_matcher.append(
687 self.client.backend.create_chain_matcher(
688 criterium=Criterium(
689 criterium=criterium, index=criterium_idx
690 )
691 )
692 )
693 except ValueError as exc:
694 self.module.warn(
695 f"Error while parsing criterium: {exc}. Ignoring criterium."
696 )
697
698 if self.profile is not None:
699 meta_profiles = (self.directory.get("meta") or {}).get("profiles") or {}
700 if not meta_profiles:
701 raise ModuleFailException(msg="The ACME CA does not support profiles.")
702 if self.profile not in meta_profiles:
703 raise ModuleFailException(
704 msg=f"The ACME CA does not support selected profile {self.profile!r}."
705 )
706
707 # Make sure account exists
708 modify_account = module.params["modify_account"]
709 if modify_account is None:
710 module.deprecate(
711 "The default 'true' for modify_account has been deprecated."
712 " The default will change to 'false' in community.crypto 4.0.0."
713 " We suggest to explicitly set this option to a value to avoid"
714 " this warning. We also recommend to not set it to 'true',"
715 " but to use the community.crypto.acme_account module instead.",
716 version="4.0.0",
717 collection_name="community.crypto",
718 )
719
720 modify_account = True
721 contact = []
722 if module.params["account_email"]:
723 contact.append("mailto:" + module.params["account_email"])
724 created, account_data = self.account.setup_account(
725 contact=contact,
726 terms_agreed=module.params.get("terms_agreed"),
727 allow_creation=modify_account,
728 )
729 if account_data is None:
730 raise ModuleFailException(msg="Account does not exist or is deactivated.")
731 updated = False
732 if not created and account_data and modify_account:
733 updated, account_data = self.account.update_account(
734 account_data=account_data, contact=contact
735 )
736 self.changed = created or updated
737
738 if self.csr is not None and not os.path.exists(self.csr):
739 raise ModuleFailException(f"CSR {self.csr} not found")
740
741 # Extract list of identifiers from CSR
742 self.identifiers = self.client.backend.get_ordered_csr_identifiers(
743 csr_filename=self.csr, csr_content=self.csr_content
744 )
745
746 def is_first_step(self) -> bool:
747 """
748 Return True if this is the first execution of this module, i.e. if a
749 sufficient data object from a first run has not been provided.
750 """
751 if self.data is None:
752 return True
753 # We are in the second stage if data.order_uri is given (which has been
754 # stored in self.order_uri by the constructor).
755 return self.order_uri is None
756
757 def _get_cert_info_or_none(self) -> CertificateInformation | None:
758 if self.module.params.get("dest"):
759 filename = self.module.params["dest"]
760 else:
761 filename = self.module.params["fullchain_dest"]
762 if not os.path.exists(filename):
763 return None
764 return self.client.backend.get_cert_information(cert_filename=filename)
765
766 def start_challenges(self) -> None:
767 """
768 Create new authorizations for all identifiers of the CSR,
769 respectively start a new order for ACME v2.
770 """
771 self.authorizations = {}
772 replaces_cert_id = None
773 if self.include_renewal_cert_id == "always" or (
774 self.include_renewal_cert_id == "when_ari_supported"
775 and self.client.directory.has_renewal_info_endpoint()
776 ):
777 cert_info = self._get_cert_info_or_none()
778 if cert_info is not None:
779 replaces_cert_id = compute_cert_id(
780 backend=self.client.backend,
781 cert_info=cert_info,
782 none_if_required_information_is_missing=True,
783 )
784 self.order = Order.create_with_error_handling(
785 client=self.client,
786 identifiers=self.identifiers,
787 error_strategy=self.order_creation_error_strategy,
788 error_max_retries=self.order_creation_max_retries,
789 replaces_cert_id=replaces_cert_id,
790 profile=self.profile,
791 message_callback=self.module.warn,
792 )
793 self.order_uri = self.order.url
794 self.order.load_authorizations(client=self.client)
795 self.authorizations.update(self.order.authorizations)
796 self.changed = True
797
798 def get_challenges_data(
799 self, first_step: bool
800 ) -> tuple[dict[str, t.Any], dict[str, list[str]]]:
801 """
802 Get challenge details for the chosen challenge type.
803 Return a tuple of generic challenge details, and specialized DNS challenge details.
804 """
805 assert self.authorizations is not None
806 data: dict[str, t.Any] = {}
807 data_dns: dict[str, list[str]] = {}
808 for type_identifier, authz in self.authorizations.items():
809 # Skip valid authentications: their challenges are already valid
810 # and do not need to be returned
811 if authz.status == "valid":
812 continue
813 # We drop the type from the key to preserve backwards compatibility
814 challenges = authz.get_challenge_data(client=self.client)
815 assert authz.identifier is not None
816 data[authz.identifier] = challenges
817 if (
818 first_step
819 and self.challenge is not None
820 and self.challenge not in data[authz.identifier]
821 ):
822 raise ModuleFailException(
823 f"Found no challenge of type '{self.challenge}' for identifier {type_identifier}!"
824 )
825 if (
826 self.challenge in ("dns-01", "dns-account-01")
827 and self.challenge in challenges
828 ):
829 values = data_dns.get(challenges[self.challenge]["record"])
830 if values is None:
831 values = []
832 data_dns[challenges[self.challenge]["record"]] = values
833 values.append(challenges[self.challenge]["resource_value"])
834 return data, data_dns
835
836 def finish_challenges(self) -> None:
837 """
838 Verify challenges for all identifiers of the CSR.
839 """
840 self.authorizations = {}
841
842 # Step 1: obtain challenge information
843 # For ACME v2, we obtain the order object by fetching the
844 # order URI, and extract the information from there.
845 assert self.order_uri is not None
846 self.order = Order.from_url(client=self.client, url=self.order_uri)
847 self.order.load_authorizations(client=self.client)
848 self.authorizations.update(self.order.authorizations)
849
850 # Step 2: validate pending challenges
851 authzs_to_wait_for = []
852 for authz in self.authorizations.values():
853 if authz.status == "pending":
854 if self.challenge is not None:
855 authz.call_validate(
856 client=self.client, challenge_type=self.challenge, wait=False
857 )
858 authzs_to_wait_for.append(authz)
859 # If there is no challenge, we must check whether the authz is valid
860 elif authz.status != "valid":
861 authz.raise_error(
862 error_msg='Status is not "valid", even though no challenge should be necessary',
863 module=self.client.module,
864 )
865 self.changed = True
866
867 # Step 3: wait for authzs to validate
868 wait_for_validation(authzs=authzs_to_wait_for, client=self.client)
869
870 def download_alternate_chains(
871 self, cert: CertificateChain
872 ) -> list[CertificateChain]:
873 alternate_chains = []
874 for alternate in cert.alternates:
875 try:
876 alt_cert = CertificateChain.download(client=self.client, url=alternate)
877 except ModuleFailException as e:
878 self.module.warn(
879 f"Error while downloading alternative certificate {alternate}: {e}"
880 )
881 continue
882 alternate_chains.append(alt_cert)
883 return alternate_chains
884
885 def find_matching_chain(
886 self, chains: t.Iterable[CertificateChain]
887 ) -> CertificateChain | None:
888 for criterium_idx, matcher in enumerate(self.select_chain_matcher):
889 for chain in chains:
890 if matcher.match(certificate=chain):
891 self.module.debug(
892 f"Found matching chain for criterium {criterium_idx}"
893 )
894 return chain
895 return None
896
897 def get_certificate(self) -> None:
898 """
899 Request a new certificate and write it to the destination file.
900 First verifies whether all authorizations are valid; if not, aborts
901 with an error.
902 """
903 assert self.authorizations is not None
904 for identifier_type, identifier in self.identifiers:
905 authz = self.authorizations.get(
906 normalize_combined_identifier(
907 combine_identifier(
908 identifier_type=identifier_type, identifier=identifier
909 )
910 )
911 )
912 if authz is None:
913 raise ModuleFailException(
914 f'Found no authorization information for "{combine_identifier(identifier_type=identifier_type, identifier=identifier)}"!'
915 )
916 if authz.status != "valid":
917 authz.raise_error(
918 error_msg=f'Status is "{authz.status}" and not "valid"',
919 module=self.module,
920 )
921
922 assert self.order is not None
923 self.order.finalize(
924 client=self.client,
925 csr_der=pem_to_der(pem_filename=self.csr, pem_content=self.csr_content),
926 )
927 assert self.order.certificate_uri is not None
928 cert = CertificateChain.download(
929 client=self.client, url=self.order.certificate_uri
930 )
931 if self.module.params["retrieve_all_alternates"] or self.select_chain_matcher:
932 # Retrieve alternate chains
933 alternate_chains = self.download_alternate_chains(cert)
934
935 # Prepare return value for all alternate chains
936 if self.module.params["retrieve_all_alternates"]:
937 self.all_chains = [cert.to_json()]
938 for alt_chain in alternate_chains:
939 self.all_chains.append(alt_chain.to_json())
940
941 # Try to select alternate chain depending on criteria
942 if self.select_chain_matcher:
943 matching_chain = self.find_matching_chain([cert] + alternate_chains)
944 if matching_chain:
945 cert = matching_chain
946 else:
947 self.module.debug("Found no matching alternative chain")
948
949 if cert.cert is not None:
950 pem_cert = cert.cert
951 chain = cert.chain
952
953 if self.dest and write_file(
954 module=self.module, dest=self.dest, content=pem_cert.encode("utf8")
955 ):
956 self.cert_days = self.client.backend.get_cert_days(
957 cert_filename=self.dest
958 )
959 self.changed = True
960
961 if self.fullchain_dest and write_file(
962 module=self.module,
963 dest=self.fullchain_dest,
964 content=(pem_cert + "\n".join(chain)).encode("utf8"),
965 ):
966 self.cert_days = self.client.backend.get_cert_days(
967 cert_filename=self.fullchain_dest
968 )
969 self.changed = True
970
971 if self.chain_dest and write_file(
972 module=self.module,
973 dest=self.chain_dest,
974 content=("\n".join(chain)).encode("utf8"),
975 ):
976 self.changed = True
977
978 def deactivate_authzs(self) -> None:
979 """
980 Deactivates all valid authz's. Does not raise exceptions.
981 https://community.letsencrypt.org/t/authorization-deactivation/19860/2
982 https://tools.ietf.org/html/rfc8555#section-7.5.2
983 """
984 assert self.authorizations is not None
985 for authz in self.authorizations.values():
986 try:
987 authz.deactivate(client=self.client)
988 except Exception:
989 # ignore errors
990 pass
991 if not authz.is_in_final_state(allow_valid=False):
992 self.module.warn(
993 warning=f"Could not deactivate authz object {authz.url}."
994 )
995
996
997 def main() -> t.NoReturn:
998 argument_spec = create_default_argspec(with_certificate=True)
999 argument_spec.argument_spec["csr"]["aliases"] = ["src"]
1000 argument_spec.update_argspec(
1001 modify_account={"type": "bool"},
1002 account_email={"type": "str"},
1003 agreement={
1004 "type": "str",
1005 "removed_in_version": "4.0.0",
1006 "removed_from_collection": "community.crypto",
1007 },
1008 terms_agreed={"type": "bool", "default": False},
1009 challenge={
1010 "type": "str",
1011 "default": "http-01",
1012 "choices": [
1013 "http-01",
1014 "dns-01",
1015 "dns-account-01",
1016 "dns-persist-01",
1017 "tls-alpn-01",
1018 NO_CHALLENGE,
1019 ],
1020 },
1021 data={"type": "dict"},
1022 dest={"type": "path", "aliases": ["cert"]},
1023 fullchain_dest={"type": "path", "aliases": ["fullchain"]},
1024 chain_dest={"type": "path", "aliases": ["chain"]},
1025 remaining_days={"type": "int", "default": 10},
1026 deactivate_authzs={"type": "bool", "default": False},
1027 force={"type": "bool", "default": False},
1028 retrieve_all_alternates={"type": "bool", "default": False},
1029 select_chain={
1030 "type": "list",
1031 "elements": "dict",
1032 "options": {
1033 "test_certificates": {
1034 "type": "str",
1035 "default": "all",
1036 "choices": ["first", "last", "all"],
1037 },
1038 "issuer": {"type": "dict"},
1039 "subject": {"type": "dict"},
1040 "subject_key_identifier": {"type": "str"},
1041 "authority_key_identifier": {"type": "str"},
1042 },
1043 },
1044 include_renewal_cert_id={
1045 "type": "str",
1046 "choices": ["never", "when_ari_supported", "always"],
1047 "default": "never",
1048 },
1049 profile={"type": "str"},
1050 order_creation_error_strategy={
1051 "type": "str",
1052 "default": "auto",
1053 "choices": ["auto", "always", "fail", "retry_without_replaces_cert_id"],
1054 },
1055 order_creation_max_retries={"type": "int", "default": 3},
1056 )
1057 argument_spec.update(
1058 required_one_of=[
1059 ["dest", "fullchain_dest"],
1060 ],
1061 )
1062 module = argument_spec.create_ansible_module(supports_check_mode=True)
1063 backend = create_backend(module, needs_acme_v2=False)
1064
1065 try:
1066 if module.params.get("dest"):
1067 cert_days = backend.get_cert_days(cert_filename=module.params["dest"])
1068 else:
1069 cert_days = backend.get_cert_days(
1070 cert_filename=module.params["fullchain_dest"]
1071 )
1072
1073 if module.params["force"] or cert_days < module.params["remaining_days"]:
1074 # If checkmode is active, base the changed state solely on the status
1075 # of the certificate file as all other actions (accessing an account, checking
1076 # the authorization status...) would lead to potential changes of the current
1077 # state
1078 if module.check_mode:
1079 module.exit_json(
1080 changed=True,
1081 authorizations={},
1082 challenge_data={},
1083 cert_days=cert_days,
1084 )
1085 else:
1086 client = ACMECertificateClient(module=module, backend=backend)
1087 client.cert_days = cert_days
1088 other: dict[str, t.Any] = {}
1089 is_first_step = client.is_first_step()
1090 if is_first_step:
1091 # First run: start challenges / start new order
1092 client.start_challenges()
1093 else:
1094 # Second run: finish challenges, and get certificate
1095 try:
1096 client.finish_challenges()
1097 client.get_certificate()
1098 if client.all_chains is not None:
1099 other["all_chains"] = client.all_chains
1100 finally:
1101 if module.params["deactivate_authzs"]:
1102 client.deactivate_authzs()
1103 data, data_dns = client.get_challenges_data(first_step=is_first_step)
1104 auths = {}
1105 assert client.authorizations is not None
1106 for v in client.authorizations.values():
1107 # Remove "type:" from key
1108 auths[v.identifier] = v.to_json()
1109 module.exit_json(
1110 changed=client.changed,
1111 authorizations=auths,
1112 finalize_uri=client.order.finalize_uri if client.order else None,
1113 order_uri=client.order_uri,
1114 account_uri=client.client.account_uri,
1115 challenge_data=data,
1116 challenge_data_dns=data_dns,
1117 cert_days=client.cert_days,
1118 **other,
1119 )
1120 else:
1121 module.exit_json(changed=False, cert_days=cert_days)
1122 except ModuleFailException as e:
1123 e.do_fail(module=module)
1124
1125
1126 if __name__ == "__main__":
1127 main()