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:

We use these parameters as follows: