How to Sanitize the RDS Username with Terraform
Posted on September 4, 2018
How to Sanitize the RDS Username (for acceptance by API validation) with Terraform
Let’s say you want to use RDS on AWS.
You write some Terraform to manage those resources:
Fill in
Tou may even use some module to do the same for you:
Fill in
But regardless, you pass/define a username for the RDS database admin.
More importantly, AWS has really specific expectations on that username.
Here is a way to validate our provided password to align with a few of those expectations:
locals {
# we have to fixup the master username before we use it, the AWS API will error out otherwise
# RDS expects the username to be without hyphens and 16 characters at max. 'rdsadmin' is also
# a forbidden username, though we don't validate that here.
db_master_user_unsanitized = "${var.app_db_master_user}"
# truncate to 16 characters, but deal with the fact that substr() will error out if you ask
# for more characters than are in the string
master_user_max_length = "16"
master_user_length = "${length(local.db_master_user_unsanitized)}"
master_user_truncation_length = "${local.master_user_length < local.default_master_user_max_length ? local.master_user_length : local.master_user_max_length}"
db_master_user_truncated = "${substr(local.db_master_user_unsanitized, 0, local.master_user_max_length)}"
# remove hyphens from the username
db_master_user = "${replace(local.db_master_user_truncated, "-", "")}"
}
TODO: fix the issue above where we replace after truncating, replace then truncate.
Pieces to the Puzzle
First, we use local values to define some parameters, we have:
- the “Unsanitized” username,
- the “maximum allowed length” for the username,
- the “length of the current (unsanitized) username”,
- the “length to truncate the username at”
- the truncated/sanitized password
We use these parameters as follows:
- NOTE: / TODO: run
replace()
to remove-
first - The max length is defined to be 16 characters. This is based on the API spec from AWS.
- We run
length()
on the unsanitized usernamedb_master_user_unsanitized
. - We compare the length of that string against the maximum length allowed.
- If the length of that string is larger/bigger than the max allowed, we set our max limit as the truncation length.
- If the length of that string is less than the max, we use the length of the string as our truncation length.
- We truncate the username to the truncation length.