lemur/lemur/plugins/lemur_acme/route53.py

105 lines
3.1 KiB
Python
Raw Normal View History

2016-06-28 00:57:53 +02:00
import time
2018-05-07 18:58:24 +02:00
2016-06-28 00:57:53 +02:00
from lemur.plugins.lemur_aws.sts import sts_client
@sts_client('route53')
def wait_for_dns_change(change_id, client=None):
2016-06-28 00:57:53 +02:00
_, change_id = change_id
while True:
response = client.get_change(Id=change_id)
if response["ChangeInfo"]["Status"] == "INSYNC":
return
time.sleep(5)
@sts_client('route53')
def find_zone_id(domain, client=None):
paginator = client.get_paginator("list_hosted_zones")
zones = []
for page in paginator.paginate():
for zone in page["HostedZones"]:
if domain.endswith(zone["Name"]) or (domain + ".").endswith(zone["Name"]):
if not zone["Config"]["PrivateZone"]:
zones.append((zone["Name"], zone["Id"]))
if not zones:
raise ValueError(
"Unable to find a Route53 hosted zone for {}".format(domain)
)
return zones[0][1]
2016-06-28 00:57:53 +02:00
@sts_client('route53')
def change_txt_record(action, zone_id, domain, value, client=None):
current_txt_records = []
try:
2018-06-20 19:33:35 +02:00
current_records = client.list_resource_record_sets(
HostedZoneId=zone_id,
StartRecordName=domain,
StartRecordType='TXT',
2018-06-20 19:33:35 +02:00
MaxItems="1")["ResourceRecordSets"]
for record in current_records:
if record.get('Type') == 'TXT':
current_txt_records.extend(record.get("ResourceRecords", []))
except Exception as e:
# Current Resource Record does not exist
if "NoSuchHostedZone" not in str(type(e)):
raise
# For some reason TXT records need to be
# manually quoted.
current_txt_records.append({"Value": '"{}"'.format(value)})
if action == "DELETE" and len(current_txt_records) > 1:
# If we want to delete one record out of many, we'll update the record to not include the deleted value instead.
# This allows us to support concurrent issuance.
current_txt_records = [
record for record in current_txt_records if not (record.get('Value') == '"{}"'.format(value))
]
action = "UPSERT"
2016-06-28 00:57:53 +02:00
response = client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
"Changes": [
{
"Action": action,
"ResourceRecordSet": {
"Name": domain,
"Type": "TXT",
"TTL": 300,
"ResourceRecords": current_txt_records,
2016-06-28 00:57:53 +02:00
}
}
]
}
)
return response["ChangeInfo"]["Id"]
def create_txt_record(host, value, account_number):
zone_id = find_zone_id(host, account_number=account_number)
2016-06-28 00:57:53 +02:00
change_id = change_txt_record(
"UPSERT",
2016-06-28 00:57:53 +02:00
zone_id,
host,
value,
account_number=account_number
2016-06-28 00:57:53 +02:00
)
2018-06-12 00:40:15 +02:00
2016-06-28 00:57:53 +02:00
return zone_id, change_id
2018-06-12 00:40:15 +02:00
def delete_txt_record(change_ids, account_number, host, value):
for change_id in change_ids:
zone_id, _ = change_id
change_txt_record(
"DELETE",
zone_id,
host,
value,
account_number=account_number
)