Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: route53
10 version_added: 5.0.0
11 short_description: add or delete entries in Amazons Route 53 DNS service
12 description:
13 - Creates and deletes DNS records in Amazons Route 53 service.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 options:
16 state:
17 description:
18 - Specifies the state of the resource record.
19 required: true
20 aliases: [ 'command' ]
21 choices: [ 'present', 'absent', 'get', 'create', 'delete' ]
22 type: str
23 zone:
24 description:
25 - The DNS zone to modify.
26 - This is a required parameter, if parameter O(hosted_zone_id) is not supplied.
27 type: str
28 hosted_zone_id:
29 description:
30 - The Hosted Zone ID of the DNS zone to modify.
31 - This is a required parameter, if parameter O(zone) is not supplied.
32 type: str
33 record:
34 description:
35 - The full DNS record to create or delete.
36 required: true
37 type: str
38 ttl:
39 description:
40 - The TTL, in second, to give the new record.
41 - Mutually exclusive with O(alias).
42 default: 3600
43 type: int
44 type:
45 description:
46 - The type of DNS record to create.
47 - Support for V(SSHFP) was added in release 9.2.0. See AWS Doc for more information
48 U(https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html).
49 required: true
50 choices: [ 'A', 'CNAME', 'MX', 'AAAA', 'TXT', 'PTR', 'SRV', 'SPF', 'CAA', 'NS', 'SOA', 'SSHFP' ]
51 type: str
52 alias:
53 description:
54 - Indicates if this is an alias record.
55 - Mutually exclusive with O(ttl).
56 - Defaults to V(false).
57 type: bool
58 alias_hosted_zone_id:
59 description:
60 - The hosted zone identifier.
61 type: str
62 alias_evaluate_target_health:
63 description:
64 - Whether or not to evaluate an alias target health. Useful for aliases to Elastic Load Balancers.
65 type: bool
66 default: false
67 value:
68 description:
69 - The new value when creating a DNS record. YAML lists or multiple comma-spaced values are allowed for non-alias records.
70 type: list
71 elements: str
72 overwrite:
73 description:
74 - Whether an existing record should be overwritten on create if values do not match.
75 type: bool
76 retry_interval:
77 description:
78 - In the case that Route 53 is still servicing a prior request, this module will wait and try again after this many seconds.
79 If you have many domain names, the default of V(500) seconds may be too long.
80 default: 500
81 type: int
82 private_zone:
83 description:
84 - If set to V(true), the private zone matching the requested name within the domain will be used if there are both public and private zones.
85 - The default is to use the public zone.
86 type: bool
87 default: false
88 identifier:
89 description:
90 - Have to be specified for Weighted, latency-based and failover resource record sets only.
91 An identifier that differentiates among multiple resource record sets that have the same combination of DNS name and type.
92 type: str
93 weight:
94 description:
95 - Weighted resource record sets only. Among resource record sets that
96 have the same combination of DNS name and type, a value that
97 determines what portion of traffic for the current resource record set
98 is routed to the associated location.
99 - Mutually exclusive with O(routing_region), O(region), and O(failover).
100 type: int
101 routing_region:
102 description:
103 - Latency-based resource record sets only Among resource record sets
104 that have the same combination of DNS name and type, a value that
105 determines which region this should be associated with for the
106 latency-based routing
107 - Mutually exclusive with O(weight) and O(failover).
108 type: str
109 version_added: 11.2.0
110 region:
111 description:
112 - Latency-based resource record sets only Among resource record sets
113 that have the same combination of DNS name and type, a value that
114 determines which region this should be associated with for the
115 latency-based routing
116 - Mutually exclusive with O(weight) and O(failover).
117 - This parameter has been deprecated and will be removed in a release after 2027-06-01.
118 - Please use O(routing_region) instead.
119 type: str
120 aws_region:
121 description:
122 - The AWS region to use for API requests.
123 - If not specified, the value of the E(AWS_REGION) or E(AWS_DEFAULT_REGION) environment variable is used.
124 - See the AWS documentation U(https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region) for more information.
125 - When O(aws_region) is not specified, the module may also use a profile from your AWS configuration.
126 type: str
127 version_added: 11.2.0
128 geo_location:
129 description:
130 - Allows to control how Amazon Route 53 responds to DNS queries based on the geographic origin of the query.
131 - Two geolocation resource record sets that specify same geographic location cannot be created.
132 - Non-geolocation resource record sets that have the same values for the Name and Type elements as geolocation
133 resource record sets cannot be created.
134 suboptions:
135 continent_code:
136 description:
137 - The two-letter code for the continent.
138 - Specifying O(geo_location.continent_code) with either O(geo_location.country_code) or O(geo_location.subdivision_code)
139 returns an InvalidInput error.
140 type: str
141 country_code:
142 description:
143 - The two-letter code for a country.
144 - Amazon Route 53 uses the two-letter country codes that are specified in ISO standard 3166-1 alpha-2 .
145 type: str
146 subdivision_code:
147 description:
148 - The two-letter code for a state of the United States.
149 - To specify O(geo_location.subdivision_code), O(geo_location.country_code) must be set to V(US).
150 type: str
151 type: dict
152 version_added: 3.3.0
153 version_added_collection: community.aws
154 health_check:
155 description:
156 - Health check to associate with this record
157 type: str
158 failover:
159 description:
160 - Failover resource record sets only. Whether this is the primary or
161 secondary resource record set. Allowed values are V(PRIMARY) and V(SECONDARY).
162 - Mutually exclusive with O(weight), O(routing_region), and O(region).
163 type: str
164 choices: ['SECONDARY', 'PRIMARY']
165 vpc_id:
166 description:
167 - When used in conjunction with O(private_zone=true), this will only modify records in the private hosted zone attached to this VPC.
168 - This allows you to have multiple private hosted zones, all with the same name, attached to different VPCs.
169 type: str
170 wait:
171 description:
172 - Wait until the changes have been replicated to all Amazon Route 53 DNS servers.
173 type: bool
174 default: false
175 wait_timeout:
176 description:
177 - How long to wait for the changes to be replicated, in seconds.
178 default: 300
179 type: int
180 author:
181 - Bruce Pennypacker (@bpennypacker)
182 - Mike Buzzetti (@jimbydamonk)
183 extends_documentation_fragment:
184 - amazon.aws.common.modules
185 - amazon.aws.boto3
186 """
187
188 RETURN = r"""
189 nameservers:
190 description: Nameservers associated with the zone.
191 returned: when state is 'get'
192 type: list
193 sample:
194 - ns-1036.awsdns-00.org.
195 - ns-516.awsdns-00.net.
196 - ns-1504.awsdns-00.co.uk.
197 - ns-1.awsdns-00.com.
198 resource_record_sets:
199 description: Info specific to the resource record.
200 returned: when state is 'get'
201 type: complex
202 contains:
203 alias:
204 description: Whether this is an alias.
205 returned: always
206 type: bool
207 sample: false
208 failover:
209 description: Whether this is the primary or secondary resource record set.
210 returned: always
211 type: str
212 sample: "PRIMARY"
213 geo_location:
214 description: Geograpic location based on which Route53 resonds to DNS queries.
215 returned: when configured
216 type: dict
217 sample: { continent_code: "NA", country_code: "US", subdivision_code: "CA" }
218 version_added: 3.3.0
219 version_added_collection: community.aws
220 health_check:
221 description: Health check associated with this record.
222 returned: always
223 type: str
224 identifier:
225 description: An identifier that differentiates among multiple resource record sets that have the same combination of DNS name and type.
226 returned: always
227 type: str
228 name:
229 description: Domain name for the record set.
230 returned: always
231 type: str
232 sample: "new.foo.com"
233 record:
234 description: Domain name for the record set.
235 returned: always
236 type: str
237 sample: "new.foo.com"
238 routing_region:
239 description: Which region this should be associated with for latency-based routing.
240 returned: always
241 type: str
242 sample: "us-west-2"
243 version_added: 11.2.0
244 region:
245 description:
246 - Which region this should be associated with for latency-based routing.
247 - This return value has been deprecated and will be removed in a release after 2027-06-01. Use RV(resource_record_sets.routing_region) instead.
248 returned: always
249 type: str
250 sample: "us-west-2"
251 resource_records:
252 description: Information about the resource records to act upon.
253 type: list
254 returned: always
255 sample: [{"value": "1.1.1.1"}]
256 ttl:
257 description: Resource record cache TTL.
258 returned: always
259 type: str
260 sample: "3600"
261 type:
262 description: Resource record set type.
263 returned: always
264 type: str
265 sample: "A"
266 value:
267 description: Record value.
268 returned: always
269 type: str
270 sample: "52.43.18.27"
271 record_values:
272 description: Record values as a list.
273 returned: always
274 type: list
275 version_added: 11.0.0
276 sample:
277 - 52.43.18.27
278 values:
279 description:
280 - Record values as a list.
281 - This return value has been deprecated and will be removed in a release after
282 2026-12-01. Use RV(resource_record_sets.record_values) instead.
283 returned: always
284 type: list
285 sample:
286 - 52.43.18.27
287 weight:
288 description: Weight of the record.
289 returned: always
290 type: str
291 sample: '3'
292 zone:
293 description: Zone this record set belongs to.
294 returned: always
295 type: str
296 sample: "foo.bar.com"
297 wait_id:
298 description:
299 - The wait ID for the applied change. Can be used to wait for the change to propagate later on when O(wait=false).
300 type: str
301 returned: when changed
302 version_added: 6.3.0
303 """
304
305 EXAMPLES = r"""
306 - name: Add new.foo.com as an A record with 3 IPs and wait until the changes have been replicated
307 amazon.aws.route53:
308 state: present
309 zone: foo.com
310 record: new.foo.com
311 type: A
312 ttl: 7200
313 value: 1.1.1.1,2.2.2.2,3.3.3.3
314 wait: true
315
316 - name: Update new.foo.com as an A record with a list of 3 IPs and wait until the changes have been replicated
317 amazon.aws.route53:
318 state: present
319 zone: foo.com
320 record: new.foo.com
321 type: A
322 ttl: 7200
323 value:
324 - 1.1.1.1
325 - 2.2.2.2
326 - 3.3.3.3
327 wait: true
328
329 - name: Retrieve the details for new.foo.com
330 amazon.aws.route53:
331 state: get
332 zone: foo.com
333 record: new.foo.com
334 type: A
335 register: rec
336
337 - name: Delete new.foo.com A record using the results from the get command
338 amazon.aws.route53:
339 state: absent
340 zone: foo.com
341 record: "{{ rec.set.record }}"
342 ttl: "{{ rec.set.ttl }}"
343 type: "{{ rec.set.type }}"
344 value: "{{ rec.set.value }}"
345
346 # Add an AAAA record. Note that because there are colons in the value
347 # that the IPv6 address must be quoted. Also shows using the old form command=create.
348 - name: Add an AAAA record
349 amazon.aws.route53:
350 command: create
351 zone: foo.com
352 record: localhost.foo.com
353 type: AAAA
354 ttl: 7200
355 value: "::1"
356
357 # For more information on SRV records see:
358 # https://en.wikipedia.org/wiki/SRV_record
359 - name: Add a SRV record with multiple fields for a service on port 22222
360 amazon.aws.route53:
361 state: present
362 zone: foo.com
363 record: "_example-service._tcp.foo.com"
364 type: SRV
365 value: "0 0 22222 host1.foo.com,0 0 22222 host2.foo.com"
366
367 # Note that TXT and SPF records must be surrounded
368 # by quotes when sent to Route 53:
369 - name: Add a TXT record.
370 amazon.aws.route53:
371 state: present
372 zone: foo.com
373 record: localhost.foo.com
374 type: TXT
375 ttl: 7200
376 value: '"bar"'
377
378 - name: Add an alias record that points to an Amazon ELB
379 amazon.aws.route53:
380 state: present
381 zone: foo.com
382 record: elb.foo.com
383 type: A
384 value: "{{ elb_dns_name }}"
385 alias: true
386 alias_hosted_zone_id: "{{ elb_zone_id }}"
387
388 - name: Retrieve the details for elb.foo.com
389 amazon.aws.route53:
390 state: get
391 zone: foo.com
392 record: elb.foo.com
393 type: A
394 register: rec
395
396 - name: Delete an alias record using the results from the get command
397 amazon.aws.route53:
398 state: absent
399 zone: foo.com
400 record: "{{ rec.set.record }}"
401 ttl: "{{ rec.set.ttl }}"
402 type: "{{ rec.set.type }}"
403 value: "{{ rec.set.value }}"
404 alias: true
405 alias_hosted_zone_id: "{{ rec.set.alias_hosted_zone_id }}"
406
407 - name: Add an alias record that points to an Amazon ELB and evaluates it health
408 amazon.aws.route53:
409 state: present
410 zone: foo.com
411 record: elb.foo.com
412 type: A
413 value: "{{ elb_dns_name }}"
414 alias: true
415 alias_hosted_zone_id: "{{ elb_zone_id }}"
416 alias_evaluate_target_health: true
417
418 - name: Add an AAAA record with Hosted Zone ID
419 amazon.aws.route53:
420 state: present
421 zone: foo.com
422 hosted_zone_id: Z2AABBCCDDEEFF
423 record: localhost.foo.com
424 type: AAAA
425 ttl: 7200
426 value: "::1"
427
428 - name: Use a routing policy to distribute traffic
429 amazon.aws.route53:
430 state: present
431 zone: foo.com
432 record: www.foo.com
433 type: CNAME
434 value: host1.foo.com
435 ttl: 30
436 # Routing policy
437 identifier: "host1@www"
438 weight: 100
439 health_check: "d994b780-3150-49fd-9205-356abdd42e75"
440
441 - name: Add a CAA record (RFC 6844)
442 amazon.aws.route53:
443 state: present
444 zone: example.com
445 record: example.com
446 type: CAA
447 value:
448 - 0 issue "ca.example.net"
449 - 0 issuewild ";"
450 - 0 iodef "mailto:[email protected]"
451
452 - name: Create a record with geo_location - country_code
453 amazon.aws.route53:
454 state: present
455 zone: '{{ zone_one }}'
456 record: 'geo-test.{{ zone_one }}'
457 identifier: "geohost@www"
458 type: A
459 value: 1.1.1.1
460 ttl: 30
461 geo_location:
462 country_code: US
463
464 - name: Create a record with geo_location - subdivision code
465 amazon.aws.route53:
466 state: present
467 zone: '{{ zone_one }}'
468 record: 'geo-test.{{ zone_one }}'
469 identifier: "geohost@www"
470 type: A
471 value: 1.1.1.1
472 ttl: 30
473 geo_location:
474 country_code: US
475 subdivision_code: TX
476
477 - name: Add new.foo.com as an SSHFP record
478 amazon.aws.route53:
479 state: present
480 zone: test-zone.com
481 record: new.foo.com
482 type: SSHFP
483 ttl: 7200
484 value: 1 1 11F1A11D1111112B111C1B11B1C11C11C1234567
485
486 - name: Delete new.foo.com as an SSHFP record
487 amazon.aws.route53:
488 state: absent
489 zone: test-zone.com
490 record: new.foo.com
491 type: SSHFP
492 """
493
494 from operator import itemgetter
495
496 try:
497 import botocore
498 except ImportError:
499 pass # Handled by AnsibleAWSModule
500
501 from ansible.module_utils.basic import env_fallback
502 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
503 from ansible.module_utils.common.text.converters import to_native
504
505 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_message
506 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
507 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
508 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
509 from ansible_collections.amazon.aws.plugins.module_utils.waiters import get_waiter
510
511 MAX_AWS_RETRIES = 10 # How many retries to perform when an API call is failing
512 WAIT_RETRY = 5 # how many seconds to wait between propagation status polls
513
514
515 @AWSRetry.jittered_backoff(retries=MAX_AWS_RETRIES)
516 def _list_record_sets(route53, **kwargs):
517 paginator = route53.get_paginator("list_resource_record_sets")
518 return paginator.paginate(**kwargs).build_full_result()["ResourceRecordSets"]
519
520
521 @AWSRetry.jittered_backoff(retries=MAX_AWS_RETRIES)
522 def _list_hosted_zones(route53, **kwargs):
523 paginator = route53.get_paginator("list_hosted_zones")
524 return paginator.paginate(**kwargs).build_full_result()["HostedZones"]
525
526
527 def get_record(route53, zone_id, record_name, record_type, record_identifier):
528 record_sets_results = _list_record_sets(route53, HostedZoneId=zone_id)
529
530 for record_set in record_sets_results:
531 record_set["Name"] = record_set["Name"].encode().decode("unicode_escape")
532 # If the record name and type is not equal, move to the next record
533 if (record_name.lower(), record_type) != (record_set["Name"].lower(), record_set["Type"]):
534 continue
535
536 if record_identifier and record_identifier != record_set.get("SetIdentifier"):
537 continue
538
539 return record_set
540
541 return None
542
543
544 def get_zone_id_by_name(route53, module, zone_name, want_private, want_vpc_id):
545 """Finds a zone by name or zone_id"""
546 hosted_zones_results = _list_hosted_zones(route53)
547
548 for zone in hosted_zones_results:
549 # only save this zone id if the private status of the zone matches
550 # the private_zone_in boolean specified in the params
551 private_zone = module.boolean(zone["Config"].get("PrivateZone", False))
552 zone_id = zone["Id"].replace("/hostedzone/", "")
553
554 if private_zone == want_private and zone["Name"] == zone_name:
555 if want_vpc_id:
556 # NOTE: These details aren't available in other boto3 methods, hence the necessary
557 # extra API call
558 hosted_zone = route53.get_hosted_zone(aws_retry=True, Id=zone_id)
559 if want_vpc_id in [v["VPCId"] for v in hosted_zone["VPCs"]]:
560 return zone_id
561 else:
562 return zone_id
563 return None
564
565
566 def format_record(record_in, zone_in, zone_id):
567 """
568 Formats a record in a way that's consistent with the pre-boto3 migration values
569 as well as returning the 'normal' boto3 style values
570 """
571 if not record_in:
572 return None
573
574 record = dict(record_in)
575 record["zone"] = zone_in
576 record["hosted_zone_id"] = zone_id
577
578 record["type"] = record_in.get("Type", None)
579 record["record"] = record_in.get("Name").encode().decode("unicode_escape")
580 record["ttl"] = record_in.get("TTL", None)
581 record["identifier"] = record_in.get("SetIdentifier", None)
582 record["weight"] = record_in.get("Weight", None)
583 record["routing_region"] = record_in.get("Region", None)
584 record["region"] = record_in.get("Region", None) # Deprecated, kept for backward compatibility
585 record["failover"] = record_in.get("Failover", None)
586 record["health_check"] = record_in.get("HealthCheckId", None)
587
588 if record["ttl"]:
589 record["ttl"] = str(record["ttl"])
590 if record["weight"]:
591 record["weight"] = str(record["weight"])
592 if record["routing_region"]:
593 record["routing_region"] = str(record["routing_region"])
594 if record["region"]:
595 record["region"] = str(record["region"])
596
597 if record_in.get("AliasTarget"):
598 record["alias"] = True
599 record["value"] = record_in["AliasTarget"].get("DNSName")
600 # record_values is the new key, values is deprecated but kept for backward compatibility
601 record["record_values"] = [record_in["AliasTarget"].get("DNSName")]
602 record["values"] = record["record_values"]
603 record["alias_hosted_zone_id"] = record_in["AliasTarget"].get("HostedZoneId")
604 record["alias_evaluate_target_health"] = record_in["AliasTarget"].get("EvaluateTargetHealth")
605 else:
606 record["alias"] = False
607 records = [r.get("Value") for r in record_in.get("ResourceRecords")]
608 record["value"] = ",".join(sorted(records))
609 # record_values is the new key, values is deprecated but kept for backward compatibility
610 record["record_values"] = sorted(records)
611 record["values"] = record["record_values"]
612
613 return record
614
615
616 def get_hosted_zone_nameservers(route53, zone_id):
617 hosted_zone_name = route53.get_hosted_zone(aws_retry=True, Id=zone_id)["HostedZone"]["Name"]
618 resource_records_sets = _list_record_sets(route53, HostedZoneId=zone_id)
619
620 nameservers_records = list(
621 filter(lambda record: record["Name"] == hosted_zone_name and record["Type"] == "NS", resource_records_sets)
622 )[0]["ResourceRecords"]
623
624 return [ns_record["Value"] for ns_record in nameservers_records]
625
626
627 def main():
628 argument_spec = dict(
629 state=dict(
630 type="str", required=True, choices=["absent", "create", "delete", "get", "present"], aliases=["command"]
631 ),
632 zone=dict(type="str"),
633 hosted_zone_id=dict(type="str"),
634 record=dict(type="str", required=True),
635 ttl=dict(type="int", default=3600),
636 type=dict(
637 type="str",
638 required=True,
639 choices=["A", "AAAA", "CAA", "CNAME", "MX", "NS", "PTR", "SOA", "SPF", "SSHFP", "SRV", "TXT"],
640 ),
641 alias=dict(type="bool"),
642 alias_hosted_zone_id=dict(type="str"),
643 alias_evaluate_target_health=dict(type="bool", default=False),
644 value=dict(type="list", elements="str"),
645 overwrite=dict(type="bool"),
646 retry_interval=dict(type="int", default=500),
647 private_zone=dict(type="bool", default=False),
648 identifier=dict(type="str"),
649 weight=dict(type="int"),
650 routing_region=dict(type="str"),
651 region=dict(type="str"),
652 aws_region=dict(
653 type="str",
654 fallback=(env_fallback, ["AWS_REGION", "AWS_DEFAULT_REGION"]),
655 ),
656 geo_location=dict(
657 type="dict",
658 options=dict(
659 continent_code=dict(type="str"), country_code=dict(type="str"), subdivision_code=dict(type="str")
660 ),
661 required=False,
662 ),
663 health_check=dict(type="str"),
664 failover=dict(type="str", choices=["PRIMARY", "SECONDARY"]),
665 vpc_id=dict(type="str"),
666 wait=dict(type="bool", default=False),
667 wait_timeout=dict(type="int", default=300),
668 )
669
670 module = AnsibleAWSModule(
671 argument_spec=argument_spec,
672 supports_check_mode=True,
673 required_one_of=[["zone", "hosted_zone_id"]],
674 # If alias is True then you must specify alias_hosted_zone as well
675 required_together=[["alias", "alias_hosted_zone_id"]],
676 # state=present, absent, create, delete THEN value is required
677 required_if=(
678 ("state", "present", ["value"]),
679 ("state", "create", ["value"]),
680 ),
681 # failover, routing_region, region and weight are mutually exclusive
682 mutually_exclusive=[
683 ("failover", "routing_region", "region", "weight"),
684 ("alias", "ttl"),
685 ],
686 # failover, routing_region, region, weight and geo_location require identifier
687 required_by=dict(
688 failover=("identifier",),
689 routing_region=("identifier",),
690 region=("identifier",),
691 weight=("identifier",),
692 geo_location=("identifier",),
693 ),
694 )
695
696 module.deprecate(
697 "The 'values' key in resource_record_sets return value is deprecated. Use 'record_values' instead.",
698 date="2026-12-01",
699 collection_name="amazon.aws",
700 )
701
702 if module.params["state"] in ("present", "create"):
703 command_in = "create"
704 elif module.params["state"] in ("absent", "delete"):
705 command_in = "delete"
706 elif module.params["state"] == "get":
707 command_in = "get"
708
709 zone_in = (module.params.get("zone") or "").lower()
710 hosted_zone_id_in = module.params.get("hosted_zone_id")
711 ttl_in = module.params.get("ttl")
712 record_in = module.params.get("record").lower()
713 type_in = module.params.get("type")
714 value_in = module.params.get("value") or []
715 alias_in = module.params.get("alias")
716 alias_hosted_zone_id_in = module.params.get("alias_hosted_zone_id")
717 alias_evaluate_target_health_in = module.params.get("alias_evaluate_target_health")
718 retry_interval_in = module.params.get("retry_interval")
719
720 if module.params["vpc_id"] is not None:
721 private_zone_in = True
722 else:
723 private_zone_in = module.params.get("private_zone")
724
725 identifier_in = module.params.get("identifier")
726 weight_in = module.params.get("weight")
727 routing_region_in = module.params.get("routing_region")
728 region_in = module.params.get("region") # Deprecated, for backward compatibility
729 health_check_in = module.params.get("health_check")
730 failover_in = module.params.get("failover")
731 vpc_id_in = module.params.get("vpc_id")
732 wait_in = module.params.get("wait")
733 wait_timeout_in = module.params.get("wait_timeout")
734 geo_location = module.params.get("geo_location")
735 aws_region_in = module.params.get("aws_region")
736
737 # Handle backward compatibility for deprecated 'region' parameter
738 if region_in:
739 module.deprecate(
740 "The 'region' parameter for latency-based routing is deprecated. Please use 'routing_region' instead.",
741 date="2027-06-01",
742 collection_name="amazon.aws",
743 )
744 routing_region_in = region_in
745
746 if zone_in[-1:] != ".":
747 zone_in += "."
748
749 if record_in[-1:] != ".":
750 record_in += "."
751
752 if command_in == "create" or command_in == "delete":
753 if alias_in and len(value_in) != 1:
754 module.fail_json(msg="parameter 'value' must contain a single dns name for alias records")
755 if (
756 weight_in is None and routing_region_in is None and failover_in is None and geo_location is None
757 ) and identifier_in is not None:
758 module.fail_json(
759 msg=(
760 "You have specified identifier which makes sense only if you specify one of: weight, routing_region,"
761 " geo_location or failover."
762 )
763 )
764
765 retry_decorator = AWSRetry.jittered_backoff(
766 retries=MAX_AWS_RETRIES,
767 delay=retry_interval_in,
768 catch_extra_error_codes=["PriorRequestNotComplete"],
769 max_delay=max(60, retry_interval_in),
770 )
771
772 # connect to the route53 endpoint
773 # Use aws_region for API connection, not the deprecated latency-routing region parameter
774 try:
775 client_params = {"retry_decorator": retry_decorator}
776 if aws_region_in:
777 client_params["region"] = aws_region_in
778 route53 = module.client("route53", **client_params)
779 except botocore.exceptions.HTTPClientError as e:
780 module.fail_json_aws(e, msg="Failed to connect to AWS")
781
782 # Find the named zone ID
783 zone_id = hosted_zone_id_in or get_zone_id_by_name(route53, module, zone_in, private_zone_in, vpc_id_in)
784
785 # Verify that the requested zone is already defined in Route53
786 if zone_id is None:
787 errmsg = f"Zone {zone_in or hosted_zone_id_in} does not exist in Route53"
788 module.fail_json(msg=errmsg)
789
790 aws_record = get_record(route53, zone_id, record_in, type_in, identifier_in)
791
792 resource_record_set = scrub_none_parameters(
793 {
794 "Name": record_in,
795 "Type": type_in,
796 "Weight": weight_in,
797 "Region": routing_region_in,
798 "Failover": failover_in,
799 "TTL": ttl_in,
800 "ResourceRecords": [dict(Value=value) for value in value_in],
801 "HealthCheckId": health_check_in,
802 "SetIdentifier": identifier_in,
803 }
804 )
805
806 if geo_location:
807 continent_code = geo_location.get("continent_code")
808 country_code = geo_location.get("country_code")
809 subdivision_code = geo_location.get("subdivision_code")
810
811 if continent_code and (country_code or subdivision_code):
812 module.fail_json(
813 changed=False,
814 msg=(
815 "While using geo_location, continent_code is mutually exclusive with country_code and"
816 " subdivision_code."
817 ),
818 )
819
820 if not any([continent_code, country_code, subdivision_code]):
821 module.fail_json(
822 changed=False,
823 msg="To use geo_location please specify either continent_code, country_code, or subdivision_code.",
824 )
825
826 if geo_location.get("subdivision_code") and geo_location.get("country_code").lower() != "us":
827 module.fail_json(changed=False, msg="To use subdivision_code, you must specify country_code as US.")
828
829 # Build geo_location suboptions specification
830 resource_record_set["GeoLocation"] = {}
831 if continent_code:
832 resource_record_set["GeoLocation"]["ContinentCode"] = continent_code
833 if country_code:
834 resource_record_set["GeoLocation"]["CountryCode"] = country_code
835 if subdivision_code:
836 resource_record_set["GeoLocation"]["SubdivisionCode"] = subdivision_code
837
838 if command_in == "delete" and aws_record is not None:
839 resource_record_set["TTL"] = aws_record.get("TTL")
840 if not resource_record_set["ResourceRecords"]:
841 resource_record_set["ResourceRecords"] = aws_record.get("ResourceRecords")
842
843 if alias_in:
844 resource_record_set["AliasTarget"] = dict(
845 HostedZoneId=alias_hosted_zone_id_in,
846 DNSName=value_in[0],
847 EvaluateTargetHealth=alias_evaluate_target_health_in,
848 )
849 if "ResourceRecords" in resource_record_set:
850 del resource_record_set["ResourceRecords"]
851 if "TTL" in resource_record_set:
852 del resource_record_set["TTL"]
853
854 # On CAA records order doesn't matter
855 if type_in == "CAA":
856 resource_record_set["ResourceRecords"] = sorted(resource_record_set["ResourceRecords"], key=itemgetter("Value"))
857 if aws_record:
858 aws_record["ResourceRecords"] = sorted(aws_record["ResourceRecords"], key=itemgetter("Value"))
859
860 if command_in == "create" and aws_record == resource_record_set:
861 rr_sets = [camel_dict_to_snake_dict(resource_record_set)]
862 module.exit_json(changed=False, resource_records_sets=rr_sets)
863
864 if command_in == "get":
865 if type_in == "NS":
866 ns = aws_record.get("record_values", [])
867 else:
868 # Retrieve name servers associated to the zone.
869 ns = get_hosted_zone_nameservers(route53, zone_id)
870
871 formatted_aws = format_record(aws_record, zone_in, zone_id)
872
873 if formatted_aws is None:
874 # record does not exist
875 module.exit_json(changed=False, set=[], nameservers=ns, resource_record_sets=[])
876
877 rr_sets = [camel_dict_to_snake_dict(aws_record)]
878 module.exit_json(changed=False, set=formatted_aws, nameservers=ns, resource_record_sets=rr_sets)
879
880 if command_in == "delete" and not aws_record:
881 module.exit_json(changed=False)
882
883 if command_in == "create" or command_in == "delete":
884 if command_in == "create" and aws_record:
885 if not module.params["overwrite"]:
886 module.fail_json(msg="Record already exists with different value. Set 'overwrite' to replace it")
887 command = "UPSERT"
888 else:
889 command = command_in.upper()
890
891 wait_id = None
892 if not module.check_mode:
893 try:
894 change_resource_record_sets = route53.change_resource_record_sets(
895 aws_retry=True,
896 HostedZoneId=zone_id,
897 ChangeBatch=dict(Changes=[dict(Action=command, ResourceRecordSet=resource_record_set)]),
898 )
899 wait_id = change_resource_record_sets["ChangeInfo"]["Id"]
900
901 if wait_in:
902 waiter = get_waiter(route53, "resource_record_sets_changed")
903 waiter.wait(
904 Id=change_resource_record_sets["ChangeInfo"]["Id"],
905 WaiterConfig=dict(
906 Delay=WAIT_RETRY,
907 MaxAttempts=wait_timeout_in // WAIT_RETRY,
908 ),
909 )
910 except is_boto3_error_message("but it already exists"):
911 module.exit_json(changed=False)
912 except botocore.exceptions.WaiterError as e:
913 module.fail_json_aws(e, msg="Timeout waiting for resource records changes to be applied")
914 except (
915 botocore.exceptions.BotoCoreError,
916 botocore.exceptions.ClientError,
917 ) as e: # pylint: disable=duplicate-except
918 module.fail_json_aws(e, msg="Failed to update records")
919 except Exception as e:
920 module.fail_json(msg=f"Unhandled exception. ({to_native(e)})")
921
922 formatted_aws = format_record(aws_record, zone_in, zone_id)
923 formatted_record = format_record(resource_record_set, zone_in, zone_id)
924
925 return_result = dict(
926 changed=True,
927 wait_id=wait_id,
928 resource_record_sets=[camel_dict_to_snake_dict(formatted_record)] if command_in != "delete" else {},
929 )
930
931 if module._diff:
932 return_result.update(
933 {
934 "diff": {
935 "before": formatted_aws,
936 "after": camel_dict_to_snake_dict(formatted_record) if command_in != "delete" else {},
937 }
938 }
939 )
940
941 module.exit_json(**return_result)
942
943
944 if __name__ == "__main__":
945 main()