Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/modules/load_balancer_service.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: load_balancer_service
12
13 short_description: Create and manage the services of cloud Load Balancers on the Hetzner Cloud.
14
15
16 description:
17 - Create, update and manage the services of cloud Load Balancers on the Hetzner Cloud.
18
19 author:
20 - Lukas Kaemmerling (@LKaemmerling)
21 version_added: 0.1.0
22 options:
23 load_balancer:
24 description:
25 - Name or ID of the Hetzner Cloud Load Balancer the service belongs to
26 type: str
27 required: true
28 listen_port:
29 description:
30 - The port the service listens on, i.e. the port users can connect to.
31 type: int
32 required: true
33 destination_port:
34 description:
35 - The port traffic is forwarded to, i.e. the port the targets are listening and accepting connections on.
36 - Required if services does not exist and protocol is tcp.
37 type: int
38 protocol:
39 description:
40 - Protocol of the service.
41 - Required if Load Balancer does not exist.
42 type: str
43 choices: [ http, https, tcp ]
44 proxyprotocol:
45 description:
46 - Enable the PROXY protocol.
47 type: bool
48 default: False
49 http:
50 description:
51 - Configuration for HTTP and HTTPS services
52 type: dict
53 suboptions:
54 cookie_name:
55 description:
56 - Name of the cookie which will be set when you enable sticky sessions
57 type: str
58 cookie_lifetime:
59 description:
60 - Lifetime of the cookie which will be set when you enable sticky sessions, in seconds
61 type: int
62 certificates:
63 description:
64 - List of Names or IDs of certificates
65 type: list
66 elements: str
67 sticky_sessions:
68 description:
69 - Enable or disable sticky_sessions
70 type: bool
71 default: False
72 redirect_http:
73 description:
74 - Redirect Traffic from Port 80 to Port 443, only available if protocol is https
75 type: bool
76 default: False
77 health_check:
78 description:
79 - Configuration for health checks
80 type: dict
81 suboptions:
82 protocol:
83 description:
84 - Protocol the health checks will be performed over
85 type: str
86 choices: [ http, https, tcp ]
87 port:
88 description:
89 - Port the health check will be performed on
90 type: int
91 interval:
92 description:
93 - Interval of health checks, in seconds
94 type: int
95 timeout:
96 description:
97 - Timeout of health checks, in seconds
98 type: int
99 retries:
100 description:
101 - Number of retries until a target is marked as unhealthy
102 type: int
103 http:
104 description:
105 - Additional Configuration of health checks with protocol http/https
106 type: dict
107 suboptions:
108 domain:
109 description:
110 - Domain we will set within the HTTP HOST header
111 type: str
112 path:
113 description:
114 - Path we will try to access
115 type: str
116 response:
117 description:
118 - Response we expect, if response is not within the health check response the target is unhealthy
119 type: str
120 status_codes:
121 description:
122 - List of HTTP status codes we expect to get when we perform the health check.
123 type: list
124 elements: str
125 tls:
126 description:
127 - Verify the TLS certificate, only available if health check protocol is https
128 type: bool
129 default: False
130 state:
131 description:
132 - State of the Load Balancer.
133 default: present
134 choices: [ absent, present ]
135 type: str
136 extends_documentation_fragment:
137 - hetzner.hcloud.hcloud
138 """
139
140 EXAMPLES = """
141 - name: Create a basic Load Balancer service with Port 80
142 hetzner.hcloud.load_balancer_service:
143 load_balancer: my-load-balancer
144 protocol: http
145 listen_port: 80
146 state: present
147
148 - name: Ensure the Load Balancer is absent (remove if needed)
149 hetzner.hcloud.load_balancer_service:
150 load_balancer: my-Load Balancer
151 protocol: http
152 listen_port: 80
153 state: absent
154 """
155
156 RETURN = """
157 hcloud_load_balancer_service:
158 description: The Load Balancer service instance
159 returned: Always
160 type: dict
161 contains:
162 load_balancer:
163 description: The name of the Load Balancer where the service belongs to
164 returned: always
165 type: str
166 sample: my-load-balancer
167 listen_port:
168 description: The port the service listens on, i.e. the port users can connect to.
169 returned: always
170 type: int
171 sample: 443
172 protocol:
173 description: Protocol of the service
174 returned: always
175 type: str
176 sample: http
177 destination_port:
178 description:
179 - The port traffic is forwarded to, i.e. the port the targets are listening and accepting connections on.
180 returned: always
181 type: int
182 sample: 80
183 proxyprotocol:
184 description:
185 - Enable the PROXY protocol.
186 returned: always
187 type: bool
188 sample: false
189 http:
190 description: Configuration for HTTP and HTTPS services
191 returned: always
192 type: dict
193 contains:
194 cookie_name:
195 description: Name of the cookie which will be set when you enable sticky sessions
196 returned: always
197 type: str
198 sample: HCLBSTICKY
199 cookie_lifetime:
200 description: Lifetime of the cookie which will be set when you enable sticky sessions, in seconds
201 returned: always
202 type: int
203 sample: 3600
204 certificates:
205 description: List of Names or IDs of certificates
206 returned: always
207 type: list
208 elements: str
209 sticky_sessions:
210 description: Enable or disable sticky_sessions
211 returned: always
212 type: bool
213 sample: true
214 redirect_http:
215 description: Redirect Traffic from Port 80 to Port 443, only available if protocol is https
216 returned: always
217 type: bool
218 sample: false
219 health_check:
220 description: Configuration for health checks
221 returned: always
222 type: dict
223 contains:
224 protocol:
225 description: Protocol the health checks will be performed over
226 returned: always
227 type: str
228 sample: http
229 port:
230 description: Port the health check will be performed on
231 returned: always
232 type: int
233 sample: 80
234 interval:
235 description: Interval of health checks, in seconds
236 returned: always
237 type: int
238 sample: 15
239 timeout:
240 description: Timeout of health checks, in seconds
241 returned: always
242 type: int
243 sample: 10
244 retries:
245 description: Number of retries until a target is marked as unhealthy
246 returned: always
247 type: int
248 sample: 3
249 http:
250 description: Additional Configuration of health checks with protocol http/https
251 returned: always
252 type: dict
253 contains:
254 domain:
255 description: Domain we will set within the HTTP HOST header
256 returned: always
257 type: str
258 sample: example.com
259 path:
260 description: Path we will try to access
261 returned: always
262 type: str
263 sample: /
264 response:
265 description: Response we expect, if response is not within the health check response the target is unhealthy
266 returned: always
267 type: str
268 status_codes:
269 description: List of HTTP status codes we expect to get when we perform the health check.
270 returned: always
271 type: list
272 elements: str
273 sample: ["2??","3??"]
274 tls:
275 description: Verify the TLS certificate, only available if health check protocol is https
276 returned: always
277 type: bool
278 sample: false
279 """
280
281 from ansible.module_utils.basic import AnsibleModule
282
283 from ..module_utils._base import AnsibleHCloud
284 from ..module_utils._vendor.hcloud import APIException, HCloudException
285 from ..module_utils._vendor.hcloud.certificates import BoundCertificate
286 from ..module_utils._vendor.hcloud.load_balancers import (
287 BoundLoadBalancer,
288 LoadBalancerHealtCheckHttp,
289 LoadBalancerHealthCheck,
290 LoadBalancerService,
291 LoadBalancerServiceHttp,
292 )
293
294
295 class AnsibleHCloudLoadBalancerService(AnsibleHCloud):
296 represent = "hcloud_load_balancer_service"
297
298 hcloud_load_balancer: BoundLoadBalancer | None = None
299 hcloud_load_balancer_service: LoadBalancerService | None = None
300
301 def _prepare_result(self):
302 http = None
303 if self.hcloud_load_balancer_service.protocol != "tcp":
304 http = {
305 "cookie_name": self.hcloud_load_balancer_service.http.cookie_name,
306 "cookie_lifetime": self.hcloud_load_balancer_service.http.cookie_lifetime,
307 "redirect_http": self.hcloud_load_balancer_service.http.redirect_http,
308 "sticky_sessions": self.hcloud_load_balancer_service.http.sticky_sessions,
309 "certificates": [
310 certificate.name for certificate in self.hcloud_load_balancer_service.http.certificates
311 ],
312 }
313 health_check = {
314 "protocol": self.hcloud_load_balancer_service.health_check.protocol,
315 "port": self.hcloud_load_balancer_service.health_check.port,
316 "interval": self.hcloud_load_balancer_service.health_check.interval,
317 "timeout": self.hcloud_load_balancer_service.health_check.timeout,
318 "retries": self.hcloud_load_balancer_service.health_check.retries,
319 }
320 if self.hcloud_load_balancer_service.health_check.protocol != "tcp":
321 health_check["http"] = {
322 "domain": self.hcloud_load_balancer_service.health_check.http.domain,
323 "path": self.hcloud_load_balancer_service.health_check.http.path,
324 "response": self.hcloud_load_balancer_service.health_check.http.response,
325 "status_codes": self.hcloud_load_balancer_service.health_check.http.status_codes,
326 "tls": self.hcloud_load_balancer_service.health_check.http.tls,
327 }
328 return {
329 "load_balancer": self.hcloud_load_balancer.name,
330 "protocol": self.hcloud_load_balancer_service.protocol,
331 "listen_port": self.hcloud_load_balancer_service.listen_port,
332 "destination_port": self.hcloud_load_balancer_service.destination_port,
333 "proxyprotocol": self.hcloud_load_balancer_service.proxyprotocol,
334 "http": http,
335 "health_check": health_check,
336 }
337
338 def _get_load_balancer(self):
339 try:
340 self.hcloud_load_balancer = self._client_get_by_name_or_id(
341 "load_balancers",
342 self.module.params.get("load_balancer"),
343 )
344 self._get_load_balancer_service()
345 except HCloudException as exception:
346 self.fail_json_hcloud(exception)
347
348 def _create_load_balancer_service(self):
349 self.module.fail_on_missing_params(required_params=["protocol"])
350 if self.module.params.get("protocol") == "tcp":
351 self.module.fail_on_missing_params(required_params=["destination_port"])
352
353 params = {
354 "protocol": self.module.params.get("protocol"),
355 "listen_port": self.module.params.get("listen_port"),
356 "proxyprotocol": self.module.params.get("proxyprotocol"),
357 }
358
359 if self.module.params.get("destination_port"):
360 params["destination_port"] = self.module.params.get("destination_port")
361
362 if self.module.params.get("http"):
363 params["http"] = self.__get_service_http(http_arg=self.module.params.get("http"))
364
365 if self.module.params.get("health_check"):
366 params["health_check"] = self.__get_service_health_checks(
367 health_check=self.module.params.get("health_check")
368 )
369
370 if not self.module.check_mode:
371 try:
372 action = self.hcloud_load_balancer.add_service(LoadBalancerService(**params))
373 action.wait_until_finished()
374 except HCloudException as exception:
375 self.fail_json_hcloud(exception)
376 self._mark_as_changed()
377 self._get_load_balancer()
378 self._get_load_balancer_service()
379
380 def __get_service_http(self, http_arg):
381 service_http = LoadBalancerServiceHttp(certificates=[])
382 if http_arg.get("cookie_name") is not None:
383 service_http.cookie_name = http_arg.get("cookie_name")
384 if http_arg.get("cookie_lifetime") is not None:
385 service_http.cookie_lifetime = http_arg.get("cookie_lifetime")
386 if http_arg.get("sticky_sessions") is not None:
387 service_http.sticky_sessions = http_arg.get("sticky_sessions")
388 if http_arg.get("redirect_http") is not None:
389 service_http.redirect_http = http_arg.get("redirect_http")
390 if http_arg.get("certificates") is not None:
391 certificates = http_arg.get("certificates")
392 if certificates is not None:
393 for certificate_id_or_name in certificates:
394 certificate: BoundCertificate = self._client_get_by_name_or_id(
395 "certificates",
396 certificate_id_or_name,
397 )
398 service_http.certificates.append(certificate)
399
400 return service_http
401
402 def __get_service_health_checks(self, health_check):
403 service_health_check = LoadBalancerHealthCheck()
404 if health_check.get("protocol") is not None:
405 service_health_check.protocol = health_check.get("protocol")
406 if health_check.get("port") is not None:
407 service_health_check.port = health_check.get("port")
408 if health_check.get("interval") is not None:
409 service_health_check.interval = health_check.get("interval")
410 if health_check.get("timeout") is not None:
411 service_health_check.timeout = health_check.get("timeout")
412 if health_check.get("retries") is not None:
413 service_health_check.retries = health_check.get("retries")
414 if health_check.get("http") is not None:
415 health_check_http = health_check.get("http")
416 service_health_check.http = LoadBalancerHealtCheckHttp()
417 if health_check_http.get("domain") is not None:
418 service_health_check.http.domain = health_check_http.get("domain")
419 if health_check_http.get("path") is not None:
420 service_health_check.http.path = health_check_http.get("path")
421 if health_check_http.get("response") is not None:
422 service_health_check.http.response = health_check_http.get("response")
423 if health_check_http.get("status_codes") is not None:
424 service_health_check.http.status_codes = health_check_http.get("status_codes")
425 if health_check_http.get("tls") is not None:
426 service_health_check.http.tls = health_check_http.get("tls")
427
428 return service_health_check
429
430 def _update_load_balancer_service(self):
431 changed = False
432 try:
433 params = {
434 "listen_port": self.module.params.get("listen_port"),
435 }
436
437 if self.module.params.get("destination_port") is not None:
438 if self.hcloud_load_balancer_service.destination_port != self.module.params.get("destination_port"):
439 params["destination_port"] = self.module.params.get("destination_port")
440 changed = True
441
442 if self.module.params.get("protocol") is not None:
443 if self.hcloud_load_balancer_service.protocol != self.module.params.get("protocol"):
444 params["protocol"] = self.module.params.get("protocol")
445 changed = True
446
447 if self.module.params.get("proxyprotocol") is not None:
448 if self.hcloud_load_balancer_service.proxyprotocol != self.module.params.get("proxyprotocol"):
449 params["proxyprotocol"] = self.module.params.get("proxyprotocol")
450 changed = True
451
452 if self.module.params.get("http") is not None:
453 params["http"] = self.__get_service_http(http_arg=self.module.params.get("http"))
454 changed = True
455
456 if self.module.params.get("health_check") is not None:
457 params["health_check"] = self.__get_service_health_checks(
458 health_check=self.module.params.get("health_check")
459 )
460 changed = True
461
462 if changed and not self.module.check_mode:
463 action = self.hcloud_load_balancer.update_service(LoadBalancerService(**params))
464 action.wait_until_finished()
465 self._get_load_balancer()
466 except HCloudException as exception:
467 self.fail_json_hcloud(exception)
468
469 if changed:
470 self._mark_as_changed()
471
472 def _get_load_balancer_service(self):
473 for service in self.hcloud_load_balancer.services:
474 if self.module.params.get("listen_port") == service.listen_port:
475 self.hcloud_load_balancer_service = service
476
477 def present_load_balancer_service(self):
478 self._get_load_balancer()
479 if self.hcloud_load_balancer_service is None:
480 self._create_load_balancer_service()
481 else:
482 self._update_load_balancer_service()
483
484 def delete_load_balancer_service(self):
485 try:
486 self._get_load_balancer()
487 if self.hcloud_load_balancer_service is not None:
488 if not self.module.check_mode:
489 try:
490 action = self.hcloud_load_balancer.delete_service(self.hcloud_load_balancer_service)
491 action.wait_until_finished()
492 except HCloudException as exception:
493 self.fail_json_hcloud(exception)
494 self._mark_as_changed()
495 self.hcloud_load_balancer_service = None
496 except APIException as exception:
497 self.fail_json_hcloud(exception)
498
499 @classmethod
500 def define_module(cls):
501 return AnsibleModule(
502 argument_spec=dict(
503 load_balancer={"type": "str", "required": True},
504 listen_port={"type": "int", "required": True},
505 destination_port={"type": "int"},
506 protocol={
507 "type": "str",
508 "choices": ["http", "https", "tcp"],
509 },
510 proxyprotocol={"type": "bool", "default": False},
511 http={
512 "type": "dict",
513 "options": dict(
514 cookie_name={"type": "str"},
515 cookie_lifetime={"type": "int"},
516 sticky_sessions={"type": "bool", "default": False},
517 redirect_http={"type": "bool", "default": False},
518 certificates={"type": "list", "elements": "str"},
519 ),
520 },
521 health_check={
522 "type": "dict",
523 "options": dict(
524 protocol={
525 "type": "str",
526 "choices": ["http", "https", "tcp"],
527 },
528 port={"type": "int"},
529 interval={"type": "int"},
530 timeout={"type": "int"},
531 retries={"type": "int"},
532 http={
533 "type": "dict",
534 "options": dict(
535 domain={"type": "str"},
536 path={"type": "str"},
537 response={"type": "str"},
538 status_codes={"type": "list", "elements": "str"},
539 tls={"type": "bool", "default": False},
540 ),
541 },
542 ),
543 },
544 state={
545 "choices": ["absent", "present"],
546 "default": "present",
547 },
548 **super().base_module_arguments(),
549 ),
550 supports_check_mode=True,
551 )
552
553
554 def main():
555 module = AnsibleHCloudLoadBalancerService.define_module()
556
557 hcloud = AnsibleHCloudLoadBalancerService(module)
558 state = module.params.get("state")
559 if state == "absent":
560 hcloud.delete_load_balancer_service()
561 elif state == "present":
562 hcloud.present_load_balancer_service()
563
564 module.exit_json(**hcloud.get_result())
565
566
567 if __name__ == "__main__":
568 main()