Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rds-postgres/admin-login/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ module "rotation" {
variables = {
ALTERNATE_USERNAME = coalesce(var.alternate_username, "${var.username}_alt")
PRIMARY_USERNAME = var.username
REPLICA_HOST = can(var.replica_host) ? var.replica_host : ""
REPLICA_HOST_PARAM = can(var.replica_host_param) ? var.replica_host_param : ""
}
}

Expand Down
19 changes: 13 additions & 6 deletions rds-postgres/admin-login/rotation/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

ALTERNATE_USERNAME = os.environ['ALTERNATE_USERNAME']
PRIMARY_USERNAME = os.environ['PRIMARY_USERNAME']
REPLICA_HOST = os.environ['REPLICA_HOST']
REPLICA_HOST_PARAM = os.environ['REPLICA_HOST_PARAM']


def lambda_handler(event, context):
Expand Down Expand Up @@ -111,6 +111,9 @@ def create_secret(service_client, arn, token):
KeyError: If the secret json does not contain the expected keys

"""
# Setup ssm client
ssm_client = boto3.client('ssm')

# Make sure the current secret exists
current_dict = get_secret_dict(service_client, arn, "AWSCURRENT")

Expand All @@ -127,11 +130,15 @@ def create_secret(service_client, arn, token):
current_dict['password'] = passwd['RandomPassword']

# Add DATABASE_URL to secret
current_dict['DATABASE_URL'] = dict_to_url(current_dict, False)
current_dict['DATABASE_URL'] = dict_to_url(current_dict, "")

if REPLICA_HOST_PARAM:
# Fetch database replica url
replica_url_parameter = ssm_client.get_parameter(Name=REPLICA_HOST_PARAM, WithDecryption=True)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to add something to the IAM policy to support this API request?

replica_url = replica_url_parameter['Parameter']['Value']

if REPLICA_HOST:
# Add DATABASE_REPLICA_URL to secret
current_dict['DATABASE_REPLICA_URL'] = dict_to_url(current_dict, True)
current_dict['DATABASE_REPLICA_URL'] = dict_to_url(current_dict, replica_url)

# Put the secret
service_client.put_secret_value(SecretId=arn, ClientRequestToken=token, SecretString=json.dumps(current_dict), VersionStages=['AWSPENDING'])
Expand Down Expand Up @@ -295,9 +302,9 @@ def dict_to_url(secret, replica):
url: DATABASE_URL-style string
"""
if replica:
host = secret['host']
host = replica
else:
host = REPLICA_HOST
host = secret['host']

return "postgres://%s:%s@%s:%s/%s" % (secret['username'],
secret['password'], host, secret['port'],
Expand Down