Unixtime(epoch) と 日時文字列 との変換をTerraformで行う方法を調べました。
Built-in Functions
Terraform 内での日時は、RFC 3339 形式 (YYYY-MM-DD'T'hh:mm:ssZ) に沿った形で扱うようです。
formatdate function が用途に合ってそうですが、日時文字列とUnixtime の変換機能は有りません。
- formatdate - Functions - Configuration Language | Terraform by HashiCorp
- 入力はRFC3339形式のみであり、出力オプションに UNIXTIME 形式は無い。
- timeadd - Functions - Configuration Language | Terraform by HashiCorp
- タイムスタンプに指定期間を加減算。
- timestamp - Functions - Configuration Language | Terraform by HashiCorp
- タイムスタンプ(現在日時)を返す。任意の日時指定は行えない。
使用例
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"))
}
# ---
Outputs:
o11-timestamp = "2022-08-20T08:06:19Z"
o12-timestamp-jst = "2022/08/20 17:06:19"
日時文字列 -> Unixtime
Time Provider の time_static resource で実現できます。
使用例
YYYY-MM-DD'T'hh:mm:ssZ を渡すと、分割した値(year, month, day, ...)や Unixtime (unix) を属性として持つことができます。
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
}
# ---
Outputs:
o21-mountain_day = {
"day" = 11
"hour" = 0
"id" = "2022-08-11T00:00:00Z"
"minute" = 0
"month" = 8
"rfc3339" = "2022-08-11T00:00:00Z"
"second" = 0
"triggers" = tomap(null) /* of string */
"unix" = 1660176000
"year" = 2022
}
o22-mountain_day_jst = 1660143600
Unixtime -> 日時文字列
time_static resource も formatdate function 同様、入力がRFC3339形式のみなので対応していません。 残念ながら現状では Terraform の標準機能・Providerでは実現できないようです。
仕方がないので External Data Source でお茶を濁します。
- Unixtime(epoch) を ISO 8601 書式 に変換するスクリプト
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))
使用例
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
}
# ---
Outputs:
o31-mountain_day = tomap({
"iso" = "2022-08-11T00:00:00+00:00"
})
o32-mountain_day_jst = "2022-08-10T15:00:00+00:00"