Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2024 Felix Fontein <[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 = """
9 module: acme_certificate_order_create
10 author: Felix Fontein (@felixfontein)
11 version_added: 2.24.0
12 short_description: Create an ACME v2 order
13 description:
14 - Creates an ACME v2 order. This is the first step of obtaining a new certificate
15 with the L(ACME protocol,https://tools.ietf.org/html/rfc8555) from a Certificate
16 Authority such as L(Let's Encrypt,https://letsencrypt.org/).
17 This module does not support ACME v1, the original version of the ACME protocol
18 before standardization.
19 - The current implementation supports the V(http-01), V(dns-01), V(dns-account-01), V(dns-persist-01),
20 and V(tls-alpn-01) challenges.
21 - This module needs to be used in conjunction with the
22 M(community.crypto.acme_certificate_order_validate) and.
23 M(community.crypto.acme_certificate_order_finalize) module.
24 An order can be effectively deactivated with the
25 M(community.crypto.acme_certificate_deactivate_authz) module.
26 Note that both modules require the output RV(order_uri) of this module.
27 - To create or modify ACME accounts, use the M(community.crypto.acme_account) module.
28 This module will I(not) create or update ACME accounts.
29 - Between the call of this module and M(community.crypto.acme_certificate_order_finalize),
30 you have to fulfill the required steps for the chosen challenge by whatever means necessary.
31 For V(http-01) that means creating the necessary challenge file on the destination webserver.
32 For V(dns-01), V(dns-account-01), and V(dns-persist-01) the necessary DNS records have to be created.
33 For V(tls-alpn-01) the necessary certificate has to be created and served.
34 It is I(not) the responsibility of this module to perform these steps.
35 - For details on how to fulfill these challenges, you might have to read through
36 L(the main ACME specification,https://tools.ietf.org/html/rfc8555#section-8)
37 and the L(TLS-ALPN-01 specification,https://www.rfc-editor.org/rfc/rfc8737.html#section-3).
38 Also, consider the examples provided for this module.
39 - The module includes support for IP identifiers according to
40 L(RFC 8738,https://www.rfc-editor.org/rfc/rfc8738.html) ACME extension.
41 - The module B(experimentally) supports the V(dns-account-01) challenge type according to
42 L(acme-dns-account-label draft 02, https://datatracker.ietf.org/doc/html/draft-ietf-acme-dns-account-label-02).
43 Note that the supported draft version can change at any time,
44 and changes will only be considered breaking once the draft reached RFC status.
45 - The module B(experimentally) supports the V(dns-persist-01) challenge type according to
46 L(acme-dns-persist draft 01, https://www.ietf.org/archive/id/draft-ietf-acme-dns-persist-01.html).
47 Note that the supported draft version can change at any time,
48 and changes will only be considered breaking once the draft reached RFC status.
49 seealso:
50 - module: community.crypto.acme_certificate_order_validate
51 description: Validate pending authorizations of an ACME order.
52 - module: community.crypto.acme_certificate_order_finalize
53 description: Finalize an ACME order after satisfying the challenges.
54 - module: community.crypto.acme_certificate_order_info
55 description: Obtain information for an ACME order.
56 - module: community.crypto.acme_certificate_deactivate_authz
57 description: Deactivate all authorizations (authz) of an ACME order, effectively deactivating
58 the order itself.
59 - module: community.crypto.acme_certificate_renewal_info
60 description: Determine whether a certificate should be renewed.
61 - name: The Let's Encrypt documentation
62 description: Documentation for the Let's Encrypt Certification Authority.
63 Provides useful information for example on rate limits.
64 link: https://letsencrypt.org/docs/
65 - name: Automatic Certificate Management Environment (ACME)
66 description: The specification of the ACME protocol (RFC 8555).
67 link: https://tools.ietf.org/html/rfc8555
68 - name: ACME TLS ALPN Challenge Extension
69 description: The specification of the V(tls-alpn-01) challenge (RFC 8737).
70 link: https://www.rfc-editor.org/rfc/rfc8737.html
71 - module: community.crypto.acme_challenge_cert_helper
72 description: Helps preparing V(tls-alpn-01) challenges.
73 - module: community.crypto.openssl_privatekey
74 description: Can be used to create private keys (both for certificates and accounts).
75 - module: community.crypto.openssl_privatekey_pipe
76 description: Can be used to create private keys without writing it to disk (both for certificates and accounts).
77 - module: community.crypto.openssl_csr
78 description: Can be used to create a Certificate Signing Request (CSR).
79 - module: community.crypto.openssl_csr_pipe
80 description: Can be used to create a Certificate Signing Request (CSR) without writing it to disk.
81 - module: community.crypto.acme_account
82 description: Allows to create, modify or delete an ACME account.
83 - module: community.crypto.acme_inspect
84 description: Allows to debug problems.
85 extends_documentation_fragment:
86 - community.crypto._acme.basic
87 - community.crypto._acme.account
88 - community.crypto._acme.certificate
89 - community.crypto._attributes
90 - community.crypto._attributes.actiongroup_acme
91 attributes:
92 check_mode:
93 support: none
94 diff_mode:
95 support: none
96 idempotent:
97 support: none
98 options:
99 deactivate_authzs:
100 description:
101 - "Deactivate authentication objects (authz) when issuing the certificate
102 failed."
103 - "Authentication objects are bound to an account key and remain valid
104 for a certain amount of time, and can be used to issue certificates
105 without having to re-authenticate the domain. This can be a security
106 concern."
107 type: bool
108 default: true
109 replaces_cert_id:
110 description:
111 - If provided, will request the order to replace the certificate identified by this certificate ID
112 according to L(Section 5 of RFC 9773, https://www.rfc-editor.org/rfc/rfc9773.html#section-5).
113 - This certificate ID must be computed as specified in
114 L(Section 4.1 of RFC 9773, https://www.rfc-editor.org/rfc/rfc9773.html#section-4.1).
115 It is returned as return value RV(community.crypto.acme_certificate_renewal_info#module:cert_id) of the
116 M(community.crypto.acme_certificate_renewal_info) module.
117 - ACME servers might refuse to create new orders that indicate to replace a certificate for which
118 an active replacement order already exists. This can happen if this module is used to create an order,
119 and then the playbook/role fails in case the challenges cannot be set up. If the playbook/role does not
120 record the order data to continue with the existing order, but tries to create a new one on the next run,
121 creating the new order might fail. If O(order_creation_error_strategy=fail) this will make the module fail.
122 O(order_creation_error_strategy=auto) and O(order_creation_error_strategy=retry_without_replaces_cert_id)
123 will avoid this by leaving away C(replaces) on retries.
124 - If O(order_creation_error_strategy=fail), for the above reason, this option should only be used
125 if the role/playbook using it keeps track of order data accross restarts, or if it takes care to
126 deactivate orders whose processing is aborted. Orders can be deactivated with the
127 M(community.crypto.acme_certificate_deactivate_authz) module.
128 type: str
129 profile:
130 description:
131 - Chose a specific profile for certificate selection. The available profiles depend on the CA.
132 - See L(a blog post by Let's Encrypt, https://letsencrypt.org/2025/01/09/acme-profiles/) and
133 L(draft-aaron-acme-profiles-01, https://datatracker.ietf.org/doc/draft-aaron-acme-profiles/)
134 for more information.
135 type: str
136 order_creation_error_strategy:
137 description:
138 - Selects the error handling strategy for ACME protocol errors if creating a new ACME order fails.
139 type: str
140 choices:
141 auto:
142 - An unspecified algorithm that tries to be clever.
143 - Right now identical to V(retry_without_replaces_cert_id).
144 always:
145 - Always retry, until the limit in O(order_creation_max_retries) has been reached.
146 fail:
147 - Simply fail in case of errors. Do not attempt to retry.
148 retry_without_replaces_cert_id:
149 - If O(replaces_cert_id) is present, creating the order will be tried again without C(replaces).
150 - The only exception is an error of type C(urn:ietf:params:acme:error:alreadyReplaced), that indicates that
151 the certificate was already replaced. This usually means something went wrong and the user should investigate.
152 default: auto
153 order_creation_max_retries:
154 description:
155 - Depending on the strategy selected in O(order_creation_error_strategy), will retry creating new orders
156 for at most the specified amount of times.
157 type: int
158 default: 3
159 """
160
161 EXAMPLES = r"""
162 ---
163 ### Example with HTTP-01 challenge ###
164
165 - name: Create a challenge for sample.com using a account key from a variable
166 community.crypto.acme_certificate_order_create:
167 account_key_content: "{{ account_private_key }}"
168 csr: /etc/pki/cert/csr/sample.com.csr
169 register: sample_com_challenge
170
171 # Alternative first step:
172 - name: Create a challenge for sample.com using a account key from Hashi Vault
173 community.crypto.acme_certificate_order_create:
174 account_key_content: >-
175 {{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/account_private_key:value') }}
176 csr: /etc/pki/cert/csr/sample.com.csr
177 register: sample_com_challenge
178
179 # Alternative first step:
180 - name: Create a challenge for sample.com using a account key file
181 community.crypto.acme_certificate_order_create:
182 account_key_src: /etc/pki/cert/private/account.key
183 csr_content: "{{ lookup('file', '/etc/pki/cert/csr/sample.com.csr') }}"
184 register: sample_com_challenge
185
186 # Perform the necessary steps to fulfill the challenge. For example:
187 #
188 # - name: Copy http-01 challenges
189 # ansible.builtin.copy:
190 # dest: /var/www/{{ item.identifier }}/{{ item.challenges['http-01'].resource }}
191 # content: "{{ item.challenges['http-01'].resource_value }}"
192 # loop: "{{ sample_com_challenge.challenge_data }}"
193 # when: "'http-01' in item.challenges"
194
195 - name: Let the challenge be validated
196 community.crypto.acme_certificate_order_validate:
197 account_key_src: /etc/pki/cert/private/account.key
198 order_uri: "{{ sample_com_challenge.order_uri }}"
199 challenge: http-01
200
201 - name: Retrieve the cert and intermediate certificate
202 community.crypto.acme_certificate_order_finalize:
203 account_key_src: /etc/pki/cert/private/account.key
204 csr: /etc/pki/cert/csr/sample.com.csr
205 order_uri: "{{ sample_com_challenge.order_uri }}"
206 cert_dest: /etc/httpd/ssl/sample.com.crt
207 fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
208 chain_dest: /etc/httpd/ssl/sample.com-intermediate.crt
209
210 ---
211 ### Example with DNS challenge against production ACME server ###
212
213 - name: Create a challenge for sample.com using a account key file.
214 community.crypto.acme_certificate_order_create:
215 acme_directory: https://acme-v01.api.letsencrypt.org/directory
216 account_key_src: /etc/pki/cert/private/account.key
217 csr: /etc/pki/cert/csr/sample.com.csr
218 register: sample_com_challenge
219
220 # Perform the necessary steps to fulfill the challenge. For example:
221 #
222 # - name: Create DNS records for dns-01 challenges
223 # community.aws.route53:
224 # zone: sample.com
225 # record: "{{ item.key }}"
226 # type: TXT
227 # ttl: 60
228 # state: present
229 # wait: true
230 # # Note: item.value is a list of TXT entries, and route53
231 # # requires every entry to be enclosed in quotes
232 # value: "{{ item.value | map('community.dns.quote_txt', always_quote=true) | list }}"
233 # loop: "{{ sample_com_challenge.challenge_data_dns | dict2items }}"
234
235 - name: Let the challenge be validated
236 community.crypto.acme_certificate_order_validate:
237 acme_directory: https://acme-v01.api.letsencrypt.org/directory
238 account_key_src: /etc/pki/cert/private/account.key
239 order_uri: "{{ sample_com_challenge.order_uri }}"
240 challenge: dns-01
241
242 - name: Retrieve the cert and intermediate certificate
243 community.crypto.acme_certificate_order_finalize:
244 acme_directory: https://acme-v01.api.letsencrypt.org/directory
245 account_key_src: /etc/pki/cert/private/account.key
246 csr: /etc/pki/cert/csr/sample.com.csr
247 order_uri: "{{ sample_com_challenge.order_uri }}"
248 cert_dest: /etc/httpd/ssl/sample.com.crt
249 fullchain_dest: /etc/httpd/ssl/sample.com-fullchain.crt
250 chain_dest: /etc/httpd/ssl/sample.com-intermediate.crt
251 """
252
253 RETURN = """
254 challenge_data:
255 description:
256 - For every identifier, provides the challenge information.
257 - Only challenges which are not yet valid are returned.
258 returned: changed
259 type: list
260 elements: dict
261 contains:
262 identifier:
263 description:
264 - The identifier for this challenge.
265 type: str
266 sample: example.com
267 identifier_type:
268 description:
269 - The identifier's type.
270 - V(dns) for DNS names, and V(ip) for IP addresses.
271 type: str
272 choices:
273 - dns
274 - ip
275 sample: dns
276 challenges:
277 description:
278 - Information for different challenge types supported for this identifier.
279 - Note that the keys are not valid Jinja2 identifiers.
280 type: dict
281 contains:
282 http-01:
283 description:
284 - Information for V(http-01) authorization.
285 - The server needs to make the path RV(challenge_data[].challenges.http-01.resource)
286 accessible via HTTP (which might redirect to HTTPS). A C(GET) operation to this path
287 needs to provide the value from RV(challenge_data[].challenges.http-01.resource_value).
288 returned: if the identifier supports V(http-01) authorization
289 type: dict
290 contains:
291 resource:
292 description:
293 - The path the value has to be provided under.
294 returned: success
295 type: str
296 sample: .well-known/acme-challenge/evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA
297 resource_value:
298 description:
299 - The value the resource has to produce for the validation.
300 returned: success
301 type: str
302 sample: IlirfxKKXA...17Dt3juxGJ-PCt92wr-oA
303 dns-01:
304 description:
305 - Information for V(dns-01) authorization.
306 - A DNS TXT record needs to be created with the record name RV(challenge_data[].challenges.dns-01.record)
307 and value RV(challenge_data[].challenges.dns-01.resource_value).
308 returned: if the identifier supports V(dns-01) authorization
309 type: dict
310 contains:
311 resource:
312 description:
313 - Always contains the string V(_acme-challenge).
314 returned: success
315 type: str
316 sample: _acme-challenge
317 resource_value:
318 description:
319 - The value the resource has to produce for the validation.
320 returned: success
321 type: str
322 sample: IlirfxKKXA...17Dt3juxGJ-PCt92wr-oA
323 record:
324 description: The full DNS record's name for the challenge.
325 returned: success
326 type: str
327 sample: _acme-challenge.example.com
328 dns-account-01:
329 description:
330 - Information for V(dns-account-01) authorization.
331 - A DNS TXT record needs to be created with the record name RV(challenge_data[].challenges.dns-01.record)
332 and value RV(challenge_data[].challenges.dns-01.resource_value).
333 - B(Note) that this return value is B(experimental) and can change in a breaking way also in minor releases,
334 until the acme-dns-account-label draft is in a more stable state.
335 returned: if the identifier supports V(dns-account-01) authorization
336 version_added: 3.2.0
337 type: dict
338 contains:
339 resource:
340 description:
341 - Always ends with the string V(._acme-challenge).
342 returned: success
343 type: str
344 sample: _ujmmovf2vn55tgye._acme-challenge
345 resource_value:
346 description:
347 - The value the resource has to produce for the validation.
348 returned: success
349 type: str
350 sample: IlirfxKKXA...17Dt3juxGJ-PCt92wr-oA
351 record:
352 description: The full DNS record's name for the challenge.
353 returned: success
354 type: str
355 sample: _ujmmovf2vn55tgye._acme-challenge.example.com
356 dns-persist-01:
357 description:
358 - Information for V(dns-persist-01) authorization.
359 - A DNS TXT record needs to be created with the record name V(_validation-persist.<domain>).
360 See the P(community.crypto.acme_dns_persist_record#filter) for how to create the record's content.
361 - B(Note) that this return value is B(experimental) and can change in a breaking way also in minor releases,
362 until the acme-dns-persist draft is in a more stable state.
363 returned: if the identifier supports V(dns-persist-01) authorization
364 version_added: 3.2.0
365 type: dict
366 contains:
367 account_uri:
368 description:
369 - The account URI that must be mentioned in the DNS TXT record.
370 - B(Note) that the type of this return value might change in a breaking way also in minor releases,
371 until the acme-dns-persist draft is in a more stable state.
372 This challenge field is currently under discussion in the ACME WG.
373 returned: success
374 type: str
375 sample: https://ca.example/acct/123
376 issuer_domain_names:
377 description:
378 - One of the issuer domain names must be mentioned in the DNS TXT record.
379 returned: success
380 type: list
381 elements: str
382 sample:
383 - letsencrypt.org
384 tls-alpn-01:
385 description:
386 - Information for V(tls-alpn-01) authorization.
387 - A certificate needs to be created for the DNS name RV(challenge_data[].challenges.tls-alpn-01.resource)
388 with acmeValidation X.509 extension of value RV(challenge_data[].challenges.tls-alpn-01.resource_value).
389 This certificate needs to be served when the application-layer protocol C(acme-tls/1) is negotiated for
390 a HTTPS connection to port 443 with the SNI extension for the domain name
391 (RV(challenge_data[].challenges.tls-alpn-01.resource_original)) being validated.
392 - See U(https://www.rfc-editor.org/rfc/rfc8737.html#section-3) for details.
393 returned: if the identifier supports V(tls-alpn-01) authorization
394 type: dict
395 contains:
396 resource:
397 description:
398 - The DNS name for DNS identifiers, and the reverse DNS mapping (RFC1034, RFC3596) for IP addresses.
399 returned: success
400 type: str
401 sample: example.com
402 resource_original:
403 description:
404 - The original identifier including type identifier.
405 returned: success
406 type: str
407 sample: dns:example.com
408 resource_value:
409 description:
410 - The value the resource has to produce for the validation.
411 - "B(Note:) this return value contains a Base64 encoded version of the correct
412 binary blob which has to be put into the acmeValidation X.509 extension; see
413 U(https://www.rfc-editor.org/rfc/rfc8737.html#section-3) for details. To do this,
414 you might need the P(ansible.builtin.b64decode#filter) Jinja filter to extract
415 the binary blob from this return value."
416 returned: success
417 type: str
418 sample: AAb=
419 challenge_data_dns:
420 description:
421 - List of TXT values per DNS record for V(dns-01) challenges.
422 - Only challenges which are not yet valid are returned.
423 returned: success
424 type: dict
425 challenge_data_dns_account:
426 description:
427 - List of TXT values per DNS record for V(dns-account-01) challenges.
428 - Only challenges which are not yet valid are returned.
429 returned: success
430 type: dict
431 version_added: 3.2.0
432 order_uri:
433 description: ACME order URI.
434 returned: success
435 type: str
436 account_uri:
437 description: ACME account URI.
438 returned: success
439 type: str
440 """
441
442 import typing as t
443
444 from ansible_collections.community.crypto.plugins.module_utils._acme.acme import (
445 create_backend,
446 create_default_argspec,
447 )
448 from ansible_collections.community.crypto.plugins.module_utils._acme.certificate import (
449 ACMECertificateClient,
450 )
451 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
452 ModuleFailException,
453 )
454
455
456 def main() -> t.NoReturn:
457 argument_spec = create_default_argspec(with_certificate=True)
458 argument_spec.update_argspec(
459 deactivate_authzs={"type": "bool", "default": True},
460 replaces_cert_id={"type": "str"},
461 profile={"type": "str"},
462 order_creation_error_strategy={
463 "type": "str",
464 "default": "auto",
465 "choices": ["auto", "always", "fail", "retry_without_replaces_cert_id"],
466 },
467 order_creation_max_retries={"type": "int", "default": 3},
468 )
469 module = argument_spec.create_ansible_module()
470
471 backend = create_backend(module, needs_acme_v2=False)
472
473 try:
474 client = ACMECertificateClient(module=module, backend=backend)
475
476 profile = module.params["profile"]
477 if profile is not None:
478 meta_profiles = (client.client.directory.get("meta") or {}).get(
479 "profiles"
480 ) or {}
481 if not meta_profiles:
482 raise ModuleFailException(
483 msg='The ACME CA does not support profiles. Please omit the "profile" option.'
484 )
485 if profile not in meta_profiles:
486 raise ModuleFailException(
487 msg=f"The ACME CA does not support selected profile {profile!r}."
488 )
489
490 order = None
491 done = False
492 try:
493 order = client.create_order(
494 replaces_cert_id=module.params["replaces_cert_id"], profile=profile
495 )
496 client.check_that_authorizations_can_be_used(order)
497 done = True
498 finally:
499 if module.params["deactivate_authzs"] and order and not done:
500 client.deactivate_authzs(order)
501 data, data_dns, data_dns_account = client.get_challenges_data(order)
502 module.exit_json(
503 changed=True,
504 order_uri=order.url,
505 account_uri=client.client.account_uri,
506 challenge_data=data,
507 challenge_data_dns=data_dns,
508 challenge_data_dns_account=data_dns_account,
509 )
510 except ModuleFailException as e:
511 e.do_fail(module=module)
512
513
514 if __name__ == "__main__":
515 main()