Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
badra001 committed Apr 25, 2023
1 parent 2367699 commit 600640c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 58 deletions.
87 changes: 29 additions & 58 deletions code/ddns-lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
LOGGER = logging.getLogger()
account_id = None
region = None
VERSION = '1.2.0b44'
VERSION = '1.2.0b45'

# Read Env variables
DEBUG_LOG_LEVEL = os.environ.get('DebugLogLevel', 'INFO')
Expand Down Expand Up @@ -297,6 +297,7 @@ def lambda_handler(
global phz_collection_by_vpc
global count

count['start'] = datetime.now()
LOGGER.info("event: %s", str(event) + lineno())
LOGGER.info("context: %s", str(context) + lineno())
LOGGER.info("Sns Topic Mode: %s, sending to %s", str(SNS_ENABLE), SNS_TOPIC_ARN)
Expand All @@ -323,6 +324,7 @@ def lambda_handler(

# Set variables
# Get the state from the Event stream
event_source = event['source']
state = event['detail']['state']
LOGGER.debug("instance state: %s", str(state) + lineno())

Expand Down Expand Up @@ -610,6 +612,7 @@ def lambda_handler(

flags = process_tags_flags(tags)
LOGGER.debug("New flags structure: %s", str(pformat(flags)) + lineno())
LOGGER.info("Options flags: " + ' '.join([f"{x}={flags[x]}" for x in flags]))

tag_data = {}
tag_data_fields = ['valid', 'hostname', 'zonename']
Expand Down Expand Up @@ -771,12 +774,19 @@ def lambda_handler(
caller_response.append('Failed to create ' + append_msg)
LOGGER.error('Failed to create TXT record: %s',
create_response)
else:
LOGGER.info(
f"flags=noheritage, not adding heritage TXT for A host {final_private_hostname} zone {zone_data_forward.name} value {private_ip}")

except BaseException as err:
LOGGER.error("instance: %s, unexpected error. %s\n",
instance_id, str(err) + lineno())
else:
LOGGER.info(
f"flags=noforward, not adding A and heritage TXT for host {final_private_hostname} zone {zone_data_forward.name} value {private_ip}")

if not flags['noreverse']:
fqdn = create_fqdn(final_private_hostname, final_hosted_zone_name)
try:
if reverse_zone_associated:
create_response = create_resource_record(
Expand All @@ -786,10 +796,10 @@ def lambda_handler(
tag_data['ptr_entry'].hostname,
tag_data['ptr_entry'].zonename,
'PTR',
create_fqdn(final_private_hostname, final_hosted_zone_name),
fqdn,
)
append_msg = f"PTR record in zone id: {zone_data_reverse.zone_id} owner {zone_data_reverse.owner_account} for hostname {tag_data['ptr_entry'].hostname} " + \
f"zone {tag_data['ptr_entry'].zonename} to value {final_private_dns_name}"
f"zone {tag_data['ptr_entry'].zonename} to value {fqdn}"
count[create_response] += 1
if create_response == 'success':
LOGGER.info("instance: %s, Created %s",
Expand Down Expand Up @@ -832,11 +842,17 @@ def lambda_handler(
LOGGER.error('Failed to create TXT record: %s',
create_response)

else:
LOGGER.info(
f"flags=noheritage, not adding heritage TXT for PTR host {tag_data['ptr_entry'].hostname} zone {tag_data['ptr_entry'].zonename}")
except BaseException as err:
LOGGER.error("instance: %s, unexpected error. %s\n",
instance_id, str(err) + lineno())
else:
LOGGER.info(
f"flags=noreverse, not adding PTR and heritage TXT for host {tag_data['ptr_entry'].hostname} zone {tag_data['ptr_entry'].zonename} value {fqdn}")

else: # not running so delete the records
else: # not running so delete the records. Note this may leave orphans around if the flags are set and then the host is shut down. We may want to remove no matter what.
if not flags['noforward']:
# Process and delete A record and associated TXT record
process_response = process_delete_records(
Expand Down Expand Up @@ -989,7 +1005,9 @@ def lambda_handler(
instance_id, lineno())
caller_response.insert(0, 'Successfully created recordsets')

LOGGER.info(f'{APPNAME} stats: ' +
count['end'] = datetime.now()
count['elapsed_ms'] = (count['end'] - count['start']).total_seconds() * 1000.0
LOGGER.info(f"{APPNAME} stats: source={event_source} state={state} " +
' '.join([f"{c}={count[c]}" for c in sorted(count.keys())]))
return caller_response

Expand Down Expand Up @@ -1042,6 +1060,7 @@ def get_instances(client, instance_id):
time.sleep(i)
count['sleep.count'] += 1
count['sleep.time'] += i
count['retry'] += 1

return instance_data

Expand Down Expand Up @@ -1087,6 +1106,7 @@ def new_list_hosted_zones(client, instance_id):
time.sleep(i)
count['sleep.count'] += 1
count['sleep.time'] += i
count['retry'] += 1

if hosted_zones == {}:
LOGGER.error("instance: %s, list_hosted_zones returned error. Timed out. %s",
Expand Down Expand Up @@ -1143,6 +1163,7 @@ def new_list_hosted_zones_by_vpc(client, instance_id, vpc_id, region):
time.sleep(i)
count['sleep.count'] += 1
count['sleep.time'] += i
count['retry'] += 1

if hosted_zones == {}:
LOGGER.error("vpc_id: %s, instance: %s, list_hosted_zones_by_vpc returned error. Timed out. %s",
Expand Down Expand Up @@ -1390,6 +1411,7 @@ def get_dhcp_option_set_id_for_vpc(client, instance_id, vpc_id):
time.sleep(i)
count['sleep.count'] += 1
count['sleep.time'] += i
count['retry'] += 1

return option_set_for_vpc

Expand Down Expand Up @@ -1556,6 +1578,7 @@ def new_change_resource_recordset(oclient, instance_id, zone_id, host_name, host
time.sleep(i)
count['sleep.count'] += 1
count['sleep.time'] += i
count['retry'] += 1

if i >= MAX_API_RETRY:
LOGGER.error("instance: %s, change_resource_record_sets exceeded max retry of %s",
Expand Down Expand Up @@ -1773,6 +1796,7 @@ def new_get_resource_record(oclient, instance_id, zone_id, host_name, hosted_zon
time.sleep(i)
count['sleep.count'] += 1
count['sleep.time'] += i
count['retry'] += 1

if i >= MAX_API_RETRY:
LOGGER.error("instance: %s, list_resource_record_sets exceeded max retry of %s",
Expand All @@ -1795,59 +1819,6 @@ def new_get_resource_record(oclient, instance_id, zone_id, host_name, hosted_zon
return str(value)


# def delete_resource_record(client, zone_id, host_name, hosted_zone_name, record_type, value):
# """
# This function deletes resource records from the hosted zone passed by the calling function.
# :param client:
# :param zone_id:
# :param host_name:
# :param hosted_zone_name:
# :param record_type:
# :param value:
# :return:
# """
# try:
# LOGGER.debug("Deleting %s record %s in zone %s"
# " %s", record_type, host_name, hosted_zone_name, lineno())
# if host_name[-1] != '.':
# host_name = host_name + '.'
# response = client.change_resource_record_sets(
# HostedZoneId=zone_id,
# ChangeBatch={
# "Comment": "Updated by Lambda DDNS",
# "Changes": [
# {
# "Action": "DELETE",
# "ResourceRecordSet": {
# "Name": host_name + hosted_zone_name,
# "Type": record_type,
# "TTL": DNS_RR_TTL,
# "ResourceRecords": [
# {
# "Value": value
# },
# ]
# }
# }
# ]
# }
# )

# LOGGER.debug("delete record response: %s", str(response) + lineno())
# return response

# except ClientError as err:
# if 'Not Found' in str(err):
# LOGGER.debug("Record not found error: %s", str(err) + lineno())
# return

# if 'InvalidChangeBatch' in str(err) and 'it was not found' in str(err):
# LOGGER.debug("Record not found error: %s", str(err) + lineno())
# return

# LOGGER.info("unexpected error. %s\n", str(err) + lineno())


def new_delete_resource_record(oclient, instance_id, zone_id, host_name, hosted_zone_name, record_type, value):
"""
This function deletes resource records from the hosted zone passed by the calling function.
Expand Down
Binary file modified code/ddns-lambda.zip
Binary file not shown.

0 comments on commit 600640c

Please sign in to comment.