Skip to content

Instantly share code, notes, and snippets.

@htnosm
Last active August 20, 2022 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htnosm/a2f6f1224b7403937f77ad063671f0cf to your computer and use it in GitHub Desktop.
Save htnosm/a2f6f1224b7403937f77ad063671f0cf to your computer and use it in GitHub Desktop.
Example of inter-conversion between datetime string and Unixtime in Terraform

example-tf-unixtime

Example of inter-conversion between datetime string and Unixtime in Terraform.

import sys
import json
import datetime
input = sys.stdin.read()
input_json = json.loads(input)
epoch = int(input_json.get('epoch', 0))
dt = datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc)
output = {
'iso': dt.isoformat()
}
print(json.dumps(output, indent=2))
/*
Example 1: timestamp
*/
locals {
now = timestamp()
}
output "o11-timestamp" {
value = local.now
}
output "o12-timestamp-jst" {
value = formatdate("YYYY/MM/DD hh:mm:ss", timeadd(local.now, "9h"))
}
/*
Example 2: datetime string to unixtime
*/
resource "time_static" "mountain_day" {
rfc3339 = "2022-08-11T00:00:00Z"
}
output "o21-mountain_day" {
value = time_static.mountain_day
}
resource "time_static" "mountain_day_jst" {
rfc3339 = "2022-08-11T00:00:00+09:00"
}
output "o22-mountain_day_jst" {
value = time_static.mountain_day_jst.unix
}
/*
Example 3: unixtime to datetime string
*/
data "external" "mountain_day" {
program = ["python", "./epoch.py"]
query = {
epoch = time_static.mountain_day.unix
}
}
output "o31-mountain_day" {
value = data.external.mountain_day.result
}
data "external" "mountain_day_jst" {
program = ["python", "./epoch.py"]
query = {
epoch = time_static.mountain_day_jst.unix
}
}
output "o32-mountain_day_jst" {
value = data.external.mountain_day_jst.result.iso
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment