Terraform timestamp() to numbers only string

北城余情 提交于 2019-12-03 17:37:05

The current interpolate function timestamp() has been hardcoded with output format RFC3339 in the source code:

https://github.com/hashicorp/terraform/blob/master/config/interpolate_funcs.go#L1521

return time.Now().UTC().Format(time.RFC3339), nil

So there is nothing wrong with your way, however we can improve it a little bit.

locals {
  timestamp = "${timestamp()}"
  timestamp_sanitized = "${replace("${local.timestamp}", "/[-| |T|Z|:]/", "")}"

}

Reference:

https://github.com/google/re2/wiki/Syntax

replace(string, search, replace) - Does a search and replace on the given string. All instances of search are replaced with the value of replace. If search is wrapped in forward slashes, it is treated as a regular expression. If using a regular expression, replace can reference subcaptures in the regular expression by using $n where n is the index or name of the subcapture. If using a regular expression, the syntax conforms to the re2 regular expression syntax.

Terraform 0.12.0 introduced a new function formatdate which can make this more readable:

output "timestamp" {
  value = formatdate("YYYYMMDDhhmmss", timestamp())
}

At the time of writing, formatdate's smallest supported unit is whole seconds, so this won't give exactly the same result as the regexp approach, but can work if the nearest second is accurate enough for the use-case.

This answer just shows an example of @BMW's answer which wasn't obvious to someone that's new to Terraform.

$ cat main.tf
locals {
  timestamp = "${timestamp()}"
  timestamp_sanitized = "${replace("${local.timestamp}", "/[-| |T|Z|:]/", "")}"

}

output "timestamp" {
  value = "${local.timestamp_sanitized}"
}

Example runs

Run #1:

$ terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

timestamp = 20190221205825

Run #2:

$ terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

timestamp = 20190221205839
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!