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
2
Answers
If I run in
terraform console
yourformatdate
with theT
in the time, I get the following output:Thus, the problem is not in how you embed the
T
, it is that theT
is uppercase (as @Phil suggested).One advice for you in the future is to make use of the
terraform console
command (docs) to quickly test and iterate on your expressions. I think it is a very powerful tool to improve your understanding of terraform and speed you up your development.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):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.