Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/modules/certificate.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2020, Hetzner Cloud GmbH <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6
7 from __future__ import annotations
8
9 DOCUMENTATION = """
10 ---
11 module: certificate
12
13 short_description: Create and manage certificates on the Hetzner Cloud.
14
15
16 description:
17 - Create, update and manage certificates on the Hetzner Cloud.
18
19 author:
20 - Lukas Kaemmerling (@lkaemmerling)
21
22 options:
23 id:
24 description:
25 - The ID of the Hetzner Cloud certificate to manage.
26 - Only required if no certificate I(name) is given
27 type: int
28 name:
29 description:
30 - The Name of the Hetzner Cloud certificate to manage.
31 - Only required if no certificate I(id) is given or a certificate does not exist.
32 type: str
33 labels:
34 description:
35 - User-defined labels (key-value pairs)
36 type: dict
37 certificate:
38 description:
39 - Certificate and chain in PEM format, in order so that each record directly certifies the one preceding.
40 - Required if certificate does not exist and I(type=uploaded).
41 type: str
42 private_key:
43 description:
44 - Certificate key in PEM format.
45 - Required if certificate does not exist and I(type=uploaded).
46 type: str
47 domain_names:
48 description:
49 - Domains and subdomains that should be contained in the Certificate issued by Let's Encrypt.
50 - Required if I(type=managed).
51 type: list
52 default: [ ]
53 elements: str
54 type:
55 description:
56 - Choose between uploading a Certificate in PEM format or requesting a managed Let's Encrypt Certificate.
57 default: uploaded
58 choices: [ uploaded, managed ]
59 type: str
60 state:
61 description:
62 - State of the certificate.
63 default: present
64 choices: [ absent, present ]
65 type: str
66 extends_documentation_fragment:
67 - hetzner.hcloud.hcloud
68
69 """
70
71 EXAMPLES = """
72 - name: Create a basic certificate
73 hetzner.hcloud.certificate:
74 name: my-certificate
75 certificate: -----BEGIN CERTIFICATE-----...
76 private_key: -----BEGIN PRIVATE KEY-----...
77 state: present
78
79 - name: Create a certificate with labels
80 hetzner.hcloud.certificate:
81 name: my-certificate
82 certificate: -----BEGIN CERTIFICATE-----...
83 private_key: -----BEGIN PRIVATE KEY-----...
84 labels:
85 key: value
86 mylabel: 123
87 state: present
88
89 - name: Create a managed certificate
90 hetzner.hcloud.certificate:
91 name: my-certificate
92 type: managed
93 domain_names:
94 - example.com
95 - www.example.com
96 state: present
97
98 - name: Ensure the certificate is absent (remove if needed)
99 hetzner.hcloud.certificate:
100 name: my-certificate
101 state: absent
102 """
103
104 RETURN = """
105 hcloud_certificate:
106 description: The certificate instance
107 returned: Always
108 type: dict
109 contains:
110 id:
111 description: Numeric identifier of the certificate
112 returned: always
113 type: int
114 sample: 1937415
115 name:
116 description: Name of the certificate
117 returned: always
118 type: str
119 sample: my website cert
120 fingerprint:
121 description: Fingerprint of the certificate
122 returned: always
123 type: str
124 sample: "03:c7:55:9b:2a:d1:04:17:09:f6:d0:7f:18:34:63:d4:3e:5f"
125 certificate:
126 description: Certificate and chain in PEM format
127 returned: always
128 type: str
129 sample: "-----BEGIN CERTIFICATE-----..."
130 domain_names:
131 description: List of Domains and Subdomains covered by the Certificate
132 returned: always
133 type: dict
134 not_valid_before:
135 description: Point in time when the Certificate becomes valid (in ISO-8601 format)
136 returned: always
137 type: str
138 not_valid_after:
139 description: Point in time when the Certificate stops being valid (in ISO-8601 format)
140 returned: always
141 type: str
142 labels:
143 description: User-defined labels (key-value pairs)
144 returned: always
145 type: dict
146 """
147
148 from ansible.module_utils.basic import AnsibleModule
149
150 from ..module_utils._base import AnsibleHCloud
151 from ..module_utils._vendor.hcloud import HCloudException
152 from ..module_utils._vendor.hcloud.certificates import BoundCertificate
153
154
155 class AnsibleHCloudCertificate(AnsibleHCloud):
156 represent = "hcloud_certificate"
157
158 hcloud_certificate: BoundCertificate | None = None
159
160 def _prepare_result(self):
161 return {
162 "id": self.hcloud_certificate.id,
163 "name": self.hcloud_certificate.name,
164 "type": self.hcloud_certificate.type,
165 "fingerprint": self.hcloud_certificate.fingerprint,
166 "certificate": self.hcloud_certificate.certificate,
167 "not_valid_before": self.hcloud_certificate.not_valid_before.isoformat(),
168 "not_valid_after": self.hcloud_certificate.not_valid_after.isoformat(),
169 "domain_names": self.hcloud_certificate.domain_names,
170 "labels": self.hcloud_certificate.labels,
171 }
172
173 def _get_certificate(self):
174 try:
175 if self.module.params.get("id") is not None:
176 self.hcloud_certificate = self.client.certificates.get_by_id(self.module.params.get("id"))
177 elif self.module.params.get("name") is not None:
178 self.hcloud_certificate = self.client.certificates.get_by_name(self.module.params.get("name"))
179
180 except HCloudException as exception:
181 self.fail_json_hcloud(exception)
182
183 def _create_certificate(self):
184 self.module.fail_on_missing_params(required_params=["name"])
185
186 params = {
187 "name": self.module.params.get("name"),
188 "labels": self.module.params.get("labels"),
189 }
190 if self.module.params.get("type") == "uploaded":
191 self.module.fail_on_missing_params(required_params=["certificate", "private_key"])
192 params["certificate"] = self.module.params.get("certificate")
193 params["private_key"] = self.module.params.get("private_key")
194 if not self.module.check_mode:
195 try:
196 self.client.certificates.create(**params)
197 except HCloudException as exception:
198 self.fail_json_hcloud(exception)
199 else:
200 self.module.fail_on_missing_params(required_params=["domain_names"])
201 params["domain_names"] = self.module.params.get("domain_names")
202 if not self.module.check_mode:
203 try:
204 resp = self.client.certificates.create_managed(**params)
205 # Action should take 60 to 90 seconds on average, wait for 5m to
206 # allow DNS or Let's Encrypt slowdowns.
207 resp.action.wait_until_finished(max_retries=62) # 62 retries >= 302 seconds
208 except HCloudException as exception:
209 self.fail_json_hcloud(exception)
210
211 self._mark_as_changed()
212 self._get_certificate()
213
214 def _update_certificate(self):
215 try:
216 name = self.module.params.get("name")
217 if name is not None and self.hcloud_certificate.name != name:
218 self.module.fail_on_missing_params(required_params=["id"])
219 if not self.module.check_mode:
220 self.hcloud_certificate.update(name=name)
221 self._mark_as_changed()
222
223 labels = self.module.params.get("labels")
224 if labels is not None and self.hcloud_certificate.labels != labels:
225 if not self.module.check_mode:
226 self.hcloud_certificate.update(labels=labels)
227 self._mark_as_changed()
228 except HCloudException as exception:
229 self.fail_json_hcloud(exception)
230 self._get_certificate()
231
232 def present_certificate(self):
233 self._get_certificate()
234 if self.hcloud_certificate is None:
235 self._create_certificate()
236 else:
237 self._update_certificate()
238
239 def delete_certificate(self):
240 self._get_certificate()
241 if self.hcloud_certificate is not None:
242 if not self.module.check_mode:
243 try:
244 self.client.certificates.delete(self.hcloud_certificate)
245 except HCloudException as exception:
246 self.fail_json_hcloud(exception)
247 self._mark_as_changed()
248 self.hcloud_certificate = None
249
250 @classmethod
251 def define_module(cls):
252 return AnsibleModule(
253 argument_spec=dict(
254 id={"type": "int"},
255 name={"type": "str"},
256 type={
257 "choices": ["uploaded", "managed"],
258 "default": "uploaded",
259 },
260 domain_names={"type": "list", "elements": "str", "default": []},
261 certificate={"type": "str"},
262 private_key={"type": "str", "no_log": True},
263 labels={"type": "dict"},
264 state={
265 "choices": ["absent", "present"],
266 "default": "present",
267 },
268 **super().base_module_arguments(),
269 ),
270 required_one_of=[["id", "name"]],
271 required_if=[["state", "present", ["name"]]],
272 supports_check_mode=True,
273 )
274
275
276 def main():
277 module = AnsibleHCloudCertificate.define_module()
278
279 hcloud = AnsibleHCloudCertificate(module)
280 state = module.params.get("state")
281 if state == "absent":
282 hcloud.delete_certificate()
283 elif state == "present":
284 hcloud.present_certificate()
285
286 module.exit_json(**hcloud.get_result())
287
288
289 if __name__ == "__main__":
290 main()