Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/route53_health_check.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 ---
11 module: route53_health_check
12 version_added: 5.0.0
13 short_description: Manage health checks in Amazons Route 53 DNS service
14 description:
15 - Creates and deletes DNS Health checks in Amazons Route 53 service.
16 - Only the O(port), O(resource_path), O(string_match) and O(request_interval) are
17 considered when updating existing health checks.
18 - This module was originally added to C(community.aws) in release 1.0.0.
19 options:
20 state:
21 description:
22 - Specifies the action to take.
23 choices: [ 'present', 'absent' ]
24 type: str
25 default: 'present'
26 disabled:
27 description:
28 - Stops Route 53 from performing health checks.
29 - See the AWS documentation for more details on the exact implications.
30 U(https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-values.html)
31 - Defaults to V(true) when creating a new health check.
32 type: bool
33 version_added: 2.1.0
34 version_added_collection: community.aws
35 ip_address:
36 description:
37 - IP address of the end-point to check. Either this or O(fqdn) has to be provided.
38 - IP addresses must be publicly routable.
39 type: str
40 port:
41 description:
42 - The port on the endpoint on which you want Amazon Route 53 to perform
43 health checks. Required for TCP checks.
44 type: int
45 type:
46 description:
47 - The type of health check that you want to create, which indicates how
48 Amazon Route 53 determines whether an endpoint is healthy.
49 - Once health check is created, type can not be changed.
50 - The V(CALCULATED) choice was added in 6.3.0.
51 choices: [ 'HTTP', 'HTTPS', 'HTTP_STR_MATCH', 'HTTPS_STR_MATCH', 'TCP', 'CALCULATED' ]
52 type: str
53 child_health_checks:
54 description:
55 - The child health checks used for a calculated health check.
56 - This parameter takes in the child health checks ids.
57 type: list
58 elements: str
59 version_added: 6.3.0
60 health_threshold:
61 description:
62 - The minimum number of healthy child health checks for a calculated health check to be considered healthy.
63 default: 1
64 type: int
65 version_added: 6.3.0
66 resource_path:
67 description:
68 - The path that you want Amazon Route 53 to request when performing
69 health checks. The path can be any value for which your endpoint will
70 return an HTTP status code of 2xx or 3xx when the endpoint is healthy,
71 for example the file /docs/route53-health-check.html.
72 - Mutually exclusive with O(type='TCP').
73 - The path must begin with a /
74 - Maximum 255 characters.
75 type: str
76 fqdn:
77 description:
78 - Domain name of the endpoint to check. Either this or O(ip_address) has
79 to be provided. When both are given the O(fqdn) is used in the V(Host:)
80 header of the HTTP request.
81 type: str
82 string_match:
83 description:
84 - If the check type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string
85 that you want Amazon Route 53 to search for in the response body from
86 the specified resource. If the string appears in the first 5120 bytes
87 of the response body, Amazon Route 53 considers the resource healthy.
88 type: str
89 request_interval:
90 description:
91 - The number of seconds between the time that Amazon Route 53 gets a
92 response from your endpoint and the time that it sends the next
93 health check request.
94 default: 30
95 choices: [ 10, 30 ]
96 type: int
97 failure_threshold:
98 description:
99 - The number of consecutive health checks that an endpoint must pass or
100 fail for Amazon Route 53 to change the current status of the endpoint
101 from unhealthy to healthy or vice versa.
102 - Will default to C(3) if not specified on creation.
103 choices: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
104 type: int
105 health_check_name:
106 description:
107 - Name of the Health Check.
108 - Used together with O(use_unique_names) to set/make use of O(health_check_name) as a unique identifier.
109 type: str
110 required: false
111 aliases: ['name']
112 version_added: 4.1.0
113 version_added_collection: community.aws
114 use_unique_names:
115 description:
116 - Used together with O(health_check_name) to set/make use of O(health_check_name) as a unique identifier.
117 type: bool
118 required: false
119 version_added: 4.1.0
120 version_added_collection: community.aws
121 health_check_id:
122 description:
123 - ID of the health check to be update or deleted.
124 - If provided, a health check can be updated or deleted based on the ID as unique identifier.
125 type: str
126 required: false
127 aliases: ['id']
128 version_added: 4.1.0
129 version_added_collection: community.aws
130 measure_latency:
131 description:
132 - To enable/disable latency graphs to monitor the latency between health checkers in multiple Amazon Web Services regions and your endpoint.
133 - Value of O(measure_latency) is immutable and can not be modified after creating a health check.
134 See U(https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/monitoring-health-check-latency.html)
135 type: bool
136 required: false
137 version_added: 5.4.0
138 author:
139 - "zimbatm (@zimbatm)"
140 notes:
141 - Support for O(tags) and O(purge_tags) was added in release 2.1.0.
142 extends_documentation_fragment:
143 - amazon.aws.common.modules
144 - amazon.aws.region.modules
145 - amazon.aws.tags
146 - amazon.aws.boto3
147 """
148
149 EXAMPLES = r"""
150 - name: Create a health check for host1.example.com and use it in record
151 amazon.aws.route53_health_check:
152 state: present
153 fqdn: host1.example.com
154 type: HTTP_STR_MATCH
155 resource_path: /
156 string_match: "Hello"
157 request_interval: 10
158 failure_threshold: 2
159 register: my_health_check
160
161 - amazon.aws.route53:
162 action: create
163 zone: "example.com"
164 type: CNAME
165 record: "www.example.com"
166 value: host1.example.com
167 ttl: 30
168 # Routing policy
169 identifier: "host1@www"
170 weight: 100
171 health_check: "{{ my_health_check.health_check.id }}"
172
173 - name: create a simple health check with health_check_name as unique identifier
174 amazon.aws.route53_health_check:
175 state: present
176 health_check_name: ansible
177 fqdn: ansible.com
178 port: 443
179 type: HTTPS
180 use_unique_names: true
181
182 - name: create a TCP health check with latency graphs enabled
183 amazon.aws.route53_health_check:
184 state: present
185 health_check_name: ansible
186 fqdn: ansible.com
187 port: 443
188 type: HTTPS
189 use_unique_names: true
190 measure_latency: true
191
192 - name: Delete health check
193 amazon.aws.route53_health_check:
194 state: absent
195 fqdn: host1.example.com
196
197 - name: Update Health check by ID - update ip_address
198 amazon.aws.route53_health_check:
199 id: 12345678-abcd-abcd-abcd-0fxxxxxxxxxx
200 ip_address: 1.2.3.4
201
202 - name: Update Health check by ID - update port
203 amazon.aws.route53_health_check:
204 id: 12345678-abcd-abcd-abcd-0fxxxxxxxxxx
205 ip_address: 8080
206
207 - name: Delete Health check by ID
208 amazon.aws.route53_health_check:
209 state: absent
210 id: 12345678-abcd-abcd-abcd-0fxxxxxxxxxx
211 """
212
213 RETURN = r"""
214 health_check:
215 description: Information about the health check.
216 returned: success
217 type: dict
218 contains:
219 action:
220 description: The action performed by the module.
221 type: str
222 returned: When a change is or would be made.
223 sample: 'updated'
224 id:
225 description: The Unique ID assigned by AWS to the health check.
226 type: str
227 returned: When the health check exists.
228 sample: 50ec8a13-9623-4c66-9834-dd8c5aedc9ba
229 health_check_version:
230 description: The version number of the health check.
231 type: int
232 returned: When the health check exists.
233 sample: 14
234 health_check_config:
235 description:
236 - Detailed information about the health check.
237 - May contain additional values from Route 53 health check
238 features not yet supported by this module.
239 type: dict
240 returned: When the health check exists.
241 contains:
242 type:
243 description: The type of the health check.
244 type: str
245 returned: When the health check exists.
246 sample: 'HTTPS_STR_MATCH'
247 failure_threshold:
248 description:
249 - The number of consecutive health checks that an endpoint must pass or fail for Amazon Route 53 to
250 change the current status of the endpoint from unhealthy to healthy or vice versa.
251 type: int
252 returned: When the health check exists.
253 sample: 3
254 fully_qualified_domain_name:
255 description: The FQDN configured for the health check to test.
256 type: str
257 returned: When the health check exists and an FQDN is configured.
258 sample: 'updated'
259 ip_address:
260 description: The IPv4 or IPv6 IP address of the endpoint to be queried.
261 type: str
262 returned: When the health check exists and a specific IP address is configured.
263 sample: ''
264 port:
265 description: The port on the endpoint that the health check will query.
266 type: str
267 returned: When the health check exists.
268 sample: 'updated'
269 request_interval:
270 description: The number of seconds between health check queries.
271 type: int
272 returned: When the health check exists.
273 sample: 30
274 resource_path:
275 description: The URI path to query when performing an HTTP/HTTPS based health check.
276 type: str
277 returned: When the health check exists and a resource path has been configured.
278 sample: '/healthz'
279 search_string:
280 description: A string that must be present in the response for a health check to be considered successful.
281 type: str
282 returned: When the health check exists and a search string has been configured.
283 sample: 'ALIVE'
284 disabled:
285 description: Whether the health check has been disabled or not.
286 type: bool
287 returned: When the health check exists.
288 sample: false
289 enable_sni:
290 description: This allows the endpoint to respond to HTTPS health check requests with the applicable SSL/TLS certificate.
291 type: bool
292 returned: When the health check exists.
293 sample: false
294 inverted:
295 description: Specify whether you want Amazon Route 53 to invert the status of a health check.
296 type: bool
297 returned: When the health check exists.
298 sample: false
299 measure_latency:
300 description:
301 - To enable/disable latency graphs to monitor the latency between health checkers in multiple Amazon Web Services regions and your endpoint.
302 type: bool
303 returned: When the health check exists.
304 sample: false
305 tags:
306 description: A dictionary representing the tags on the health check.
307 type: dict
308 returned: When the health check exists.
309 sample: '{"my_key": "my_value"}'
310 """
311
312 import typing
313 import uuid
314
315 if typing.TYPE_CHECKING:
316 from typing import Any
317
318 from ansible_collections.amazon.aws.plugins.module_utils.botocore import ClientType
319
320 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
321
322 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
323 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
324 from ansible_collections.amazon.aws.plugins.module_utils.route53 import AnsibleRoute53Error
325 from ansible_collections.amazon.aws.plugins.module_utils.route53 import Route53ErrorHandler
326 from ansible_collections.amazon.aws.plugins.module_utils.route53 import get_tags
327 from ansible_collections.amazon.aws.plugins.module_utils.route53 import manage_tags
328
329
330 @Route53ErrorHandler.list_error_handler("list health checks")
331 @AWSRetry.jittered_backoff()
332 def _list_health_checks(client: ClientType, **params) -> dict[str, Any]:
333 return client.list_health_checks(**params)
334
335
336 @Route53ErrorHandler.deletion_error_handler("delete health check")
337 @AWSRetry.jittered_backoff()
338 def _delete_health_check(client: ClientType, check_id: str) -> None:
339 # This always returns an empty dict, we don't control the API
340 client.delete_health_check(
341 HealthCheckId=check_id,
342 )
343
344
345 @Route53ErrorHandler.common_error_handler("create health check")
346 @AWSRetry.jittered_backoff()
347 def _create_health_check(client: ClientType, caller_ref: str, health_check: dict[str, Any]) -> dict[str, Any]:
348 return client.create_health_check(
349 CallerReference=caller_ref,
350 HealthCheckConfig=health_check,
351 )
352
353
354 @Route53ErrorHandler.common_error_handler("update health check")
355 @AWSRetry.jittered_backoff()
356 def _update_health_check(client: ClientType, check_id: str, **kwargs) -> dict[str, Any]:
357 return client.update_health_check(
358 HealthCheckId=check_id,
359 **kwargs,
360 )
361
362
363 @Route53ErrorHandler.list_error_handler("get health check", default_value=None)
364 @AWSRetry.jittered_backoff()
365 def _get_health_check(client: ClientType, check_id: str) -> dict[str, Any] | None:
366 return client.get_health_check(
367 HealthCheckId=check_id,
368 )
369
370
371 def iter_health_checks(client: ClientType):
372 """Generator that yields all health checks, handling pagination.
373
374 Args:
375 client: The Route53 boto3 client
376
377 Yields:
378 Health check dictionaries from AWS API
379
380 Note:
381 Because Route53 provides no 'filter' mechanism, using a paginator
382 would result in (on average) double the number of API calls and
383 can get really slow. Additionally, we can't properly wrap the
384 paginator, so retrying means starting from scratch with a paginator.
385 """
386 results = _list_health_checks(client)
387 while True:
388 yield from results.get("HealthChecks", [])
389
390 if results.get("IsTruncated", False):
391 results = _list_health_checks(client, Marker=results.get("NextMarker"))
392 else:
393 break
394
395
396 def find_health_check(
397 client: ClientType,
398 ip_addr: str | None,
399 fqdn: str | None,
400 hc_type: str,
401 request_interval: int,
402 port: int | None,
403 ) -> dict[str, Any] | None:
404 """Searches for health checks that have the exact same set of immutable values.
405
406 Searches across all health checks for one matching the following immutable values:
407 - ip_addr
408 - fqdn
409 - type (immutable)
410 - request_interval
411 - port
412
413 Args:
414 client: The Route53 boto3 client
415 ip_addr: IP address to match
416 fqdn: Fully qualified domain name to match
417 hc_type: Health check type to match
418 request_interval: Request interval to match
419 port: Port to match
420
421 Returns:
422 Health check dict if found, None otherwise
423 """
424 for check in iter_health_checks(client):
425 config = check.get("HealthCheckConfig")
426 if (
427 config.get("IPAddress", None) == ip_addr
428 and config.get("FullyQualifiedDomainName", None) == fqdn
429 and config.get("Type") == hc_type
430 and config.get("RequestInterval") == request_interval
431 and config.get("Port", None) == port
432 ):
433 return check
434
435 return None
436
437
438 def get_existing_checks_with_name(client: ClientType) -> dict[str, dict[str, Any]]:
439 """Get all health checks that have a Name tag.
440
441 Args:
442 client: The Route53 boto3 client
443
444 Returns:
445 Dictionary mapping health check names to health check dicts
446 """
447 health_checks_with_name = {}
448 for check in iter_health_checks(client):
449 tags = describe_health_check(client, check["Id"])["tags"]
450 if "Name" in tags:
451 health_checks_with_name[tags["Name"]] = check
452
453 return health_checks_with_name
454
455
456 def delete_health_check(client: ClientType, check_id: str | None, check_mode: bool) -> tuple[bool, str | None]:
457 """Delete a health check.
458
459 Args:
460 client: The Route53 boto3 client
461 check_id: The health check ID to delete
462 check_mode: Whether running in check mode
463
464 Returns:
465 Tuple of (changed, action)
466 """
467 if not check_id:
468 return False, None
469
470 if check_mode:
471 return True, "delete"
472
473 _delete_health_check(client, check_id)
474
475 return True, "delete"
476
477
478 def validate_health_check_creation_params(
479 healthcheck_type: str,
480 string_match: str | None,
481 child_health_checks: list[str] | None,
482 health_threshold: int | None,
483 ) -> None:
484 """Validate that required parameters are present for health check creation.
485
486 Args:
487 healthcheck_type: Health check type
488 string_match: Search string for STR_MATCH types
489 child_health_checks: List of child health check IDs for CALCULATED type
490 health_threshold: Minimum healthy children for CALCULATED type
491
492 Raises:
493 AnsibleRoute53Error: If required parameters are missing for the given type
494 """
495 missing_args = []
496
497 if healthcheck_type in ["HTTP_STR_MATCH", "HTTPS_STR_MATCH"] and not string_match:
498 missing_args.append("string_match")
499
500 if healthcheck_type == "CALCULATED":
501 if not child_health_checks:
502 missing_args.append("child_health_checks")
503 if not health_threshold:
504 missing_args.append("health_threshold")
505
506 if missing_args:
507 raise AnsibleRoute53Error(message=f"missing required arguments for creation: {', '.join(missing_args)}")
508
509
510 def build_health_check_config(
511 params: dict[str, Any],
512 ip_addr: str | None,
513 fqdn: str | None,
514 healthcheck_type: str,
515 request_interval: int,
516 port: int | None,
517 child_health_checks: list[str] | None,
518 health_threshold: int | None,
519 ) -> dict[str, Any]:
520 """Build the health check configuration dictionary.
521
522 Args:
523 params: Module parameters dict
524 ip_addr: IP address to check
525 fqdn: Fully qualified domain name to check
526 healthcheck_type: Health check type (HTTP, HTTPS, TCP, CALCULATED, etc.)
527 request_interval: Request interval in seconds
528 port: Port number to check
529 child_health_checks: List of child health check IDs (for CALCULATED type)
530 health_threshold: Minimum healthy children threshold (for CALCULATED type)
531
532 Returns:
533 Health check configuration dictionary
534 """
535 health_check = {"Type": healthcheck_type}
536
537 if params.get("disabled") is not None:
538 health_check["Disabled"] = params.get("disabled")
539 if ip_addr:
540 health_check["IPAddress"] = ip_addr
541 if fqdn:
542 health_check["FullyQualifiedDomainName"] = fqdn
543 if port:
544 health_check["Port"] = port
545
546 if healthcheck_type in ["HTTP", "HTTPS", "HTTP_STR_MATCH", "HTTPS_STR_MATCH"]:
547 resource_path = params.get("resource_path")
548 if resource_path:
549 health_check["ResourcePath"] = resource_path
550
551 if healthcheck_type in ["HTTP_STR_MATCH", "HTTPS_STR_MATCH"]:
552 health_check["SearchString"] = params.get("string_match")
553
554 if healthcheck_type == "CALCULATED":
555 health_check["ChildHealthChecks"] = child_health_checks
556 health_check["HealthThreshold"] = health_threshold
557 else:
558 health_check["FailureThreshold"] = params.get("failure_threshold") or 3
559 health_check["RequestInterval"] = request_interval
560
561 if params.get("measure_latency") is not None:
562 health_check["MeasureLatency"] = params.get("measure_latency")
563
564 return health_check
565
566
567 def create_health_check(
568 params: dict[str, Any],
569 client: ClientType,
570 check_mode: bool,
571 ip_addr_in: str | None,
572 fqdn_in: str | None,
573 type_in: str,
574 request_interval_in: int,
575 port_in: int | None,
576 child_health_checks_in: list[str] | None,
577 health_threshold_in: int | None,
578 ) -> tuple[bool, str, str | None]:
579 """Create a new health check.
580
581 Args:
582 params: Module parameters dict
583 client: The Route53 boto3 client
584 check_mode: Whether running in check mode
585 ip_addr_in: IP address to check
586 fqdn_in: Fully qualified domain name to check
587 type_in: Health check type
588 request_interval_in: Request interval in seconds
589 port_in: Port number to check
590 child_health_checks_in: List of child health check IDs
591 health_threshold_in: Minimum healthy children threshold
592
593 Returns:
594 Tuple of (changed, action, check_id)
595 """
596 # In general, if a request is repeated with the same CallerRef it won't
597 # result in a duplicate check appearing. This means we can safely use our
598 # retry decorators
599 caller_ref = str(uuid.uuid4())
600
601 validate_health_check_creation_params(
602 type_in,
603 params.get("string_match"),
604 child_health_checks_in,
605 health_threshold_in,
606 )
607
608 health_check = build_health_check_config(
609 params,
610 ip_addr_in,
611 fqdn_in,
612 type_in,
613 request_interval_in,
614 port_in,
615 child_health_checks_in,
616 health_threshold_in,
617 )
618
619 if check_mode:
620 return True, "create", None
621
622 result = _create_health_check(client, caller_ref, health_check)
623
624 check_id = result.get("HealthCheck").get("Id")
625 return True, "create", check_id
626
627
628 def build_health_check_changes(params: dict[str, Any], existing_check: dict[str, Any]) -> dict[str, Any]:
629 """Build dictionary of changes needed to update a health check.
630
631 Compares the desired parameters against the existing health check configuration
632 and returns only the fields that need to be updated.
633
634 Updatable fields:
635 - ResourcePath
636 - SearchString
637 - FailureThreshold
638 - Disabled
639 - IPAddress (only with health_check_id or use_unique_names)
640 - Port (only with health_check_id or use_unique_names)
641 - FullyQualifiedDomainName (only with health_check_id or use_unique_names)
642 - ChildHealthChecks (only with health_check_id or use_unique_names)
643 - HealthThreshold (only with health_check_id or use_unique_names)
644
645 Args:
646 params: Module parameters dict with desired state
647 existing_check: Existing health check data from AWS API
648
649 Returns:
650 Dictionary of changes to apply, empty dict if no changes needed
651 """
652 changes = {}
653 existing_config = existing_check.get("HealthCheckConfig", {})
654
655 # Always updatable fields
656 resource_path = params.get("resource_path", None)
657 if resource_path and resource_path != existing_config.get("ResourcePath"):
658 changes["ResourcePath"] = resource_path
659
660 search_string = params.get("string_match", None)
661 if search_string and search_string != existing_config.get("SearchString"):
662 changes["SearchString"] = search_string
663
664 type_in = params.get("type", None)
665 if type_in != "CALCULATED":
666 failure_threshold = params.get("failure_threshold", None)
667 if failure_threshold and failure_threshold != existing_config.get("FailureThreshold"):
668 changes["FailureThreshold"] = failure_threshold
669
670 disabled = params.get("disabled", None)
671 if disabled is not None and disabled != existing_config.get("Disabled"):
672 changes["Disabled"] = disabled
673
674 # Immutable fields can only be updated when using health_check_id or use_unique_names
675 if params.get("health_check_id") or params.get("use_unique_names"):
676 ip_address = params.get("ip_address", None)
677 if ip_address is not None and ip_address != existing_config.get("IPAddress"):
678 changes["IPAddress"] = ip_address
679
680 port = params.get("port", None)
681 if port is not None and port != existing_config.get("Port"):
682 changes["Port"] = port
683
684 fqdn = params.get("fqdn", None)
685 if fqdn is not None and fqdn != existing_config.get("FullyQualifiedDomainName"):
686 changes["FullyQualifiedDomainName"] = fqdn
687
688 if type_in == "CALCULATED":
689 child_health_checks = params.get("child_health_checks", None)
690 if child_health_checks is not None and child_health_checks != existing_config.get("ChildHealthChecks"):
691 changes["ChildHealthChecks"] = child_health_checks
692
693 health_threshold = params.get("health_threshold", None)
694 if health_threshold is not None and health_threshold != existing_config.get("HealthThreshold"):
695 changes["HealthThreshold"] = health_threshold
696
697 return changes
698
699
700 def update_health_check(
701 params: dict[str, Any], client: ClientType, check_mode: bool, existing_check: dict[str, Any]
702 ) -> tuple[bool, str | None, str]:
703 """Update an existing health check.
704
705 Args:
706 params: Module parameters dict
707 client: The Route53 boto3 client
708 check_mode: Whether running in check mode
709 existing_check: Existing health check data from AWS API
710
711 Returns:
712 Tuple of (changed, action, check_id)
713 """
714 check_id = existing_check.get("Id")
715 changes = build_health_check_changes(params, existing_check)
716
717 # No changes needed
718 if not changes:
719 return False, None, check_id
720
721 if check_mode:
722 return True, "update", check_id
723
724 # This makes sure we're starting from the version we think we are...
725 version_id = existing_check.get("HealthCheckVersion", 1)
726 _update_health_check(client, check_id, HealthCheckVersion=version_id, **changes)
727
728 return True, "update", check_id
729
730
731 def describe_health_check(client: ClientType, check_id: str | None) -> dict[str, Any]:
732 """Get detailed information about a health check including tags.
733
734 Args:
735 client: The Route53 boto3 client
736 check_id: Health check ID to describe
737
738 Returns:
739 Dictionary containing health check details and tags, or empty dict if not found
740 """
741 if not check_id:
742 return {}
743
744 result = _get_health_check(client, check_id)
745 if not result:
746 return {}
747
748 health_check = result.get("HealthCheck", {})
749 health_check = camel_dict_to_snake_dict(health_check)
750 tags = get_tags(client, "healthcheck", check_id)
751 health_check["tags"] = tags
752 return health_check
753
754
755 def ensure_absent(module, client: ClientType, port_in: int | None) -> tuple[bool, str | None, None]:
756 """Handles deletion of a health check.
757
758 Args:
759 module: AnsibleAWSModule instance
760 client: The Route53 boto3 client
761 port_in: Port number (if applicable)
762
763 Returns:
764 Tuple of (changed, action, check_id) where check_id is always None for deletions
765 """
766 check_id_from_param = module.params.get("health_check_id")
767
768 if check_id_from_param:
769 result = _get_health_check(client, check_id_from_param)
770 if not result:
771 module.exit_json(
772 changed=False, msg=f"The specified health check with ID: {check_id_from_param} does not exist"
773 )
774
775 changed, action = delete_health_check(client, check_id_from_param, module.check_mode)
776 return changed, action, None
777
778 existing_check = find_health_check(
779 client,
780 module.params.get("ip_address"),
781 module.params.get("fqdn"),
782 module.params.get("type"),
783 module.params.get("request_interval"),
784 port_in,
785 )
786
787 if not existing_check:
788 return False, None, None
789
790 check_id = existing_check.get("Id")
791 changed, action = delete_health_check(client, check_id, module.check_mode)
792 return changed, action, None
793
794
795 def ensure_present(module, client: ClientType, port_in: int | None) -> tuple[bool, str | None, str | None]:
796 """Handles creation and updates of a health check.
797
798 Args:
799 module: AnsibleAWSModule instance
800 client: The Route53 boto3 client
801 port_in: Port number (if applicable)
802
803 Returns:
804 Tuple of (changed, action, check_id)
805 """
806 ip_addr_in = module.params.get("ip_address")
807 type_in = module.params.get("type")
808 fqdn_in = module.params.get("fqdn")
809 request_interval_in = module.params.get("request_interval")
810 child_health_checks_in = module.params.get("child_health_checks")
811 health_threshold_in = module.params.get("health_threshold")
812 health_check_name = module.params.get("health_check_name")
813 tags = module.params.get("tags")
814 use_unique_names = module.params.get("use_unique_names")
815 health_check_id_in = module.params.get("health_check_id")
816
817 # Track if user specified tags - needed to determine purge behavior later
818 user_specified_tags = tags is not None
819
820 existing_check = None
821 if health_check_id_in:
822 result = _get_health_check(client, health_check_id_in)
823 if not result:
824 raise AnsibleRoute53Error(
825 message=f"The specified health check with ID: {health_check_id_in} does not exist"
826 )
827 existing_check = result["HealthCheck"]
828 elif not use_unique_names:
829 existing_check = find_health_check(
830 client,
831 module.params.get("ip_address"),
832 module.params.get("fqdn"),
833 module.params.get("type"),
834 module.params.get("request_interval"),
835 port_in,
836 )
837
838 if use_unique_names:
839 existing_checks_with_name = get_existing_checks_with_name(client)
840 if tags is None:
841 tags = {}
842 tags["Name"] = health_check_name
843
844 if health_check_name in existing_checks_with_name:
845 changed, action, check_id = update_health_check(
846 module.params, client, module.check_mode, existing_checks_with_name[health_check_name]
847 )
848 else:
849 changed, action, check_id = create_health_check(
850 module.params,
851 client,
852 module.check_mode,
853 ip_addr_in,
854 fqdn_in,
855 type_in,
856 request_interval_in,
857 port_in,
858 child_health_checks_in,
859 health_threshold_in,
860 )
861 elif existing_check:
862 changed, action, check_id = update_health_check(module.params, client, module.check_mode, existing_check)
863 else:
864 changed, action, check_id = create_health_check(
865 module.params,
866 client,
867 module.check_mode,
868 ip_addr_in,
869 fqdn_in,
870 type_in,
871 request_interval_in,
872 port_in,
873 child_health_checks_in,
874 health_threshold_in,
875 )
876
877 if check_id:
878 # When use_unique_names is true and user didn't specify tags,
879 # we only want to ensure Name tag exists, not purge other tags
880 purge_tags = module.params.get("purge_tags") if user_specified_tags else False
881 changed |= manage_tags(client, "healthcheck", check_id, tags, purge_tags, module.check_mode)
882
883 return changed, action, check_id
884
885
886 def validate_parameters(params: dict[str, Any]) -> int | None:
887 """Validates module parameters and returns the calculated port.
888
889 Args:
890 params: Module parameters dict
891
892 Returns:
893 Calculated port number, or None if not applicable
894
895 Raises:
896 AnsibleRoute53Error: If parameters are invalid
897 """
898 if not params.get("health_check_id") and not params.get("type"):
899 raise AnsibleRoute53Error(
900 message="parameter 'type' is required if not updating or deleting health check by ID."
901 )
902
903 type_in = params.get("type")
904 string_match_in = params.get("string_match")
905 port_in = params.get("port")
906
907 # Default port
908 if port_in is None:
909 if type_in in ["HTTP", "HTTP_STR_MATCH"]:
910 port_in = 80
911 elif type_in in ["HTTPS", "HTTPS_STR_MATCH"]:
912 port_in = 443
913
914 if string_match_in:
915 if type_in not in ["HTTP_STR_MATCH", "HTTPS_STR_MATCH"]:
916 raise AnsibleRoute53Error(
917 message="parameter 'string_match' argument is only for the HTTP(S)_STR_MATCH types"
918 )
919 if len(string_match_in) > 255:
920 raise AnsibleRoute53Error(message="parameter 'string_match' is limited to 255 characters max")
921
922 return port_in
923
924
925 def main():
926 argument_spec = dict(
927 state=dict(choices=["present", "absent"], default="present"),
928 disabled=dict(type="bool"),
929 ip_address=dict(),
930 port=dict(type="int"),
931 type=dict(choices=["HTTP", "HTTPS", "HTTP_STR_MATCH", "HTTPS_STR_MATCH", "TCP", "CALCULATED"]),
932 child_health_checks=dict(type="list", elements="str"),
933 health_threshold=dict(type="int", default=1),
934 resource_path=dict(),
935 fqdn=dict(),
936 string_match=dict(),
937 request_interval=dict(type="int", choices=[10, 30], default=30),
938 failure_threshold=dict(type="int", choices=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
939 tags=dict(type="dict", aliases=["resource_tags"]),
940 purge_tags=dict(type="bool", default=True),
941 health_check_id=dict(type="str", aliases=["id"], required=False),
942 health_check_name=dict(type="str", aliases=["name"], required=False),
943 use_unique_names=dict(type="bool", required=False),
944 measure_latency=dict(type="bool", required=False),
945 )
946
947 args_one_of = [
948 ["ip_address", "fqdn", "health_check_id", "child_health_checks"],
949 ]
950
951 args_if = [
952 ["type", "TCP", ("port",)],
953 ["type", "CALCULATED", ("child_health_checks", "health_threshold")],
954 ]
955
956 args_required_together = [
957 ["use_unique_names", "health_check_name"],
958 ]
959
960 args_mutually_exclusive = [
961 ["health_check_id", "health_check_name"],
962 ["child_health_checks", "ip_address"],
963 ["child_health_checks", "port"],
964 ["child_health_checks", "fqdn"],
965 ]
966
967 module = AnsibleAWSModule(
968 argument_spec=argument_spec,
969 required_one_of=args_one_of,
970 required_if=args_if,
971 required_together=args_required_together,
972 mutually_exclusive=args_mutually_exclusive,
973 supports_check_mode=True,
974 )
975
976 try:
977 port_in = validate_parameters(module.params)
978
979 state_in = module.params.get("state")
980 client = module.client("route53", retry_decorator=AWSRetry.jittered_backoff())
981
982 changed = False
983 action = None
984 check_id = None
985
986 if state_in == "absent":
987 changed, action, check_id = ensure_absent(module, client, port_in)
988 elif state_in == "present":
989 changed, action, check_id = ensure_present(module, client, port_in)
990
991 health_check = describe_health_check(client, check_id)
992 health_check["action"] = action
993 module.exit_json(
994 changed=changed,
995 health_check=health_check,
996 )
997 except AnsibleRoute53Error as e:
998 module.fail_json_aws_error(e)
999
1000
1001 if __name__ == "__main__":
1002 main()