amazon-web-servicesdatetimeterraformquotesstring-concatenation

Terraform Quotes Syntax for Var + formatdate


Terraform = v1.8.2 AWS Provider = >= 5.30 from hashicorp/aws

Trying to use terraform to create an AWS resource name to include the date+time it was created. This is to serialize the resource for replacement (to avoid error 'resource with that name already exists') and have that serial string be something useful instead of random. I already add the date created as a resource Tag, but the timestamp in the name would be helpful.

e.g. Desired resource name Name = "my-app-20240707T1932"

code snippet

locals{
 name = "my-app"
 dateyear = formatdate("YYYYMMDD", timestamp()) # e.g. 20240707
 dateyeartime = formatdate("YYYYMMDD'T'hhmm", timestamp()) # e.g. 20240707T1932
}

module "aurora" {
  source = "..."
  name            = "${local.name}-${local.dateyeartime}"
}

If I use "${local.name}-${local.dateyear}" variable (i.e. without the 'T'), it works fine (but doesn't meet my desired result of including the time). If I use "${local.name}-${local.dateyeartime}", then I get this error:

Error: only lowercase alphanumeric characters and hyphens allowed in "cluster_identifier"

The issue is the 'T' within the date, which necessitates double-quotes around the date, which results in single-quotes within double-quotes within double-quotes.

Yes, I could just omit the 'T', but then I wouldn't get to struggle for 3 hours and interact with you fine folks.

Desired result is resource name like this: my-app-20240707T1932


Solution

  • This error is coming from the AWS provider rather than from Terraform itself.

    Your formatdate call is valid in isolation and would generate a timestamp string just as you described. Unfortunately, Amazon RDS uses case-insensitive cluster identifiers, with the following rules described in the Request Parameters for rds:CreateDBCluster (emphasis mine):

    DBClusterIdentifier:

    The identifier for this DB cluster. This parameter is stored as a lowercase string.

    Valid for Cluster Type: Aurora DB clusters and Multi-AZ DB clusters

    Constraints:

    • Must contain from 1 to 63 (for Aurora DB clusters) or 1 to 52 (for Multi-AZ DB clusters) letters, numbers, or hyphens.
    • First character must be a letter.
    • Can't end with a hyphen or contain two consecutive hyphens.

    The API itself converts uppercase letters to lowercase when accepting a request.

    The hashicorp/aws provider seems to try to enforce consistency by requiring you to provide a value that would be accepted as-is by the API without any case conversions, and so it rejects uppercase letters.

    Therefore you cannot use an uppercase letter as part of your cluster identifier. You will need to select a different character to use as the delimiter between the date and the time.