Home > Enterprise >  How to use a function in "final_snapshot_identifier" of "aws_db_instance"?
How to use a function in "final_snapshot_identifier" of "aws_db_instance"?

Time:05-03

I am new to Terraform. I would like to build RDS (MySQL) using Terraform and make its snapshot name contain timestamp. How can I code to realize this?

I checked the official document about timestamp() function (https://www.terraform.io/language/functions/timestamp#examples), but the page does not clearly mention how to use timestamp() in .tf files.

Code

resource "aws_db_instance" "db-dev" {
    identifier                = "db-dev"
    allocated_storage         = 30
    storage_type              = "gp2"
    engine                    = "mysql"
    engine_version            = "8.0.27"
    instance_class            = "db.t3.micro"
    db_name                   = "test"
    username                  = "admin"
    password                  = "admin"
    port                      = 3306
    publicly_accessible       = false
    availability_zone         = "${var.az_1_private}"
    security_group_names      = []
    vpc_security_group_ids    = ["${aws_security_group.sg-1-dev.id}"]
    db_subnet_group_name      = "db-dev-subnet"
    parameter_group_name      = "db-dev-parameter"
    multi_az                  = false
    backup_retention_period   = 0
    backup_window             = "04:30-05:00"
    maintenance_window        = "wed:01:00-wed:03:00"
    final_snapshot_identifier = "db-dev-${timestamp()}"
}

Error message

Error: invalid value for final_snapshot_identifier (must only contain alphanumeric characters and hyphens)

CodePudding user response:

timestamp returns a UTC timestamp string like 2022-05-02T05:20:12Z which includes colons for the time part of the timestamp.

Colons are not permitted to be in snapshot names.

You can use the formatdate function to format the timestamp to any format that only includes alphanumeric & hyphen characters.

For example, this should work:

final_snapshot_identifier = “db-dev-${formatdate(“YYYMMDDhhmmss”, timestamp())}”
  • Related