How to Use Timestamp Function in Terraform: Simple Guide
In Terraform, use the
timestamp() function to get the current date and time in UTC as an ISO 8601 string. This function returns a string like "2024-06-01T12:34:56Z" that you can use in resource definitions or outputs.Syntax
The timestamp() function takes no arguments and returns the current time in UTC formatted as an ISO 8601 string.
- timestamp(): Returns the current date and time in UTC.
terraform
timestamp()
Output
"2024-06-01T12:34:56Z"
Example
This example shows how to use timestamp() to output the current time when Terraform runs. It demonstrates capturing the timestamp and displaying it as an output value.
terraform
output "current_time" {
value = timestamp()
}Output
current_time = "2024-06-01T12:34:56Z"
Common Pitfalls
One common mistake is expecting timestamp() to return a fixed value across runs. It always returns the current time when Terraform runs, so it changes each time you apply. Avoid using it in places where a stable value is required.
Also, timestamp() returns a string, not a number. If you need a numeric timestamp, you must convert it externally.
terraform
/* Wrong: expecting fixed timestamp */ resource "aws_s3_bucket" "example" { bucket = "my-bucket-${timestamp()}" # This changes every apply, causing resource recreation } /* Right: use a fixed value or variable instead */ resource "aws_s3_bucket" "example" { bucket = "my-bucket-fixedname" }
Quick Reference
- Returns: Current UTC time as ISO 8601 string
- Arguments: None
- Use cases: Timestamps in logs, outputs, or metadata
- Not for: Stable IDs or resource names that must not change
Key Takeaways
Use
timestamp() to get the current UTC time as an ISO 8601 string in Terraform.timestamp() takes no arguments and returns a string like "2024-06-01T12:34:56Z".The value changes every time Terraform runs, so do not use it for stable resource names or IDs.
Use
timestamp() mainly for outputs, logs, or metadata that reflect the current time.Remember
timestamp() returns a string, not a numeric timestamp.