Sling Academy
Home/DevOps/Terraform: How to convert timestamp to date and vice versa

Terraform: How to convert timestamp to date and vice versa

Last updated: February 03, 2024

In the world of automation and infrastructure as code, Terraform stands out as a powerful tool for managing infrastructure through code templates. One common challenge when scripting with Terraform is handling dates and timestamps—a necessity for generating logs, scheduling tasks, and more. This tutorial explores how to convert a timestamp to a date and vice versa in Terraform, with progressively complex examples to guide you from the basics to more advanced applications.

Understanding Timestamps and Dates in Terraform

Before diving into the conversions, it’s vital to grasp what timestamps and dates represent in Terraform and why conversions between them might be needed. A timestamp is a sequence of characters denoting the time a certain event occurred, typically in UNIX time format (i.e., the number of seconds since January 1, 1970). Meanwhile, a date refers to a human-readable representation of a day, month, and year.

Basic Conversion: Timestamp to Date

To start, let’s convert a UNIX timestamp to a readable date format in Terraform. Terraform provides built-in functions to perform this task efficiently.

timestamp()

The timestamp() function returns the current UNIX timestamp. To convert this to a readable date, you can use the formatdate() function.

formatdate("YYYY-MM-DD", timestamp())

Output :

"2023-04-01"

This simple example demonstrates how to convert the current timestamp to a specific date format. The formatdate() function is very flexible and allows you to format the date in various ways.

Advanced Conversion: Date to Timestamp

Moving to a slightly more complex use case, what if you need to convert a specific date back into a UNIX timestamp? Terraform provides a function called timeadd() that can be helpful in such cases, though it’s slightly less straightforward than formatdate().

timeadd("1970-01-01T00:00:00Z", "43830h")

This example effectively converts 43830 hours since the UNIX epoch (January 1, 1970) back into a timestamp. The timeadd() function adds the specified duration to a base time. In this case, converting the date back to a timestamp requires some calculation since you must know the exact duration between the date and the UNIX epoch start.

Intermediate Use Cases: Scheduling and Logs

Now that we’ve covered the basics of converting between timestamps and dates, let’s look at more practical applications. For instance, managing schedules or creating logs with dynamic timestamps.

resource "aws_cloudwatch_log_group" "example" {
  name = formatdate("YYYY-MM-DD", timestamp())
}

This example uses Terraform to create an AWS CloudWatch log group with a name based on the current date. The formatdate() function dynamically generates the date, ensuring log names are organized by creation date.

Advanced Use Cases: Time-based Resource Naming

The ability to manipulate dates and timestamps in Terraform can be extremely powerful, especially for naming resources in a way that incorporates date or time information. This enables better organization and tracking of resources.

resource "aws_instance" "example" {
  tags = {
    Name = "Instance-${formatdate("YYYY-MM-DD-HH-MM-SS", timestamp())}"
  }
}

This more complex example demonstrates attaching a precise timestamp to an AWS instance name. It’s particularly useful for resources that are frequently created and destroyed, as it helps differentiate between instances based on the exact time they were provisioned.

Conclusion

Through this tutorial, we’ve explored how to convert timestamps to dates and vice versa in Terraform, starting from basic examples and moving towards more advanced use cases. Efficiently handling these conversions not only aids in scripting and automation tasks but also enhances infrastructure management by providing clearer logs, better scheduling, and improved resource tracking.

Next Article: Terraform: How to compare 2 dates

Previous Article: Terraform: How to extract filename/extension from a path

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide