Terraform timestamp() 到数字字符串

Terraform timestamp() to numbers only string

插值语法中的timestamp()函数将return一个ISO 8601格式的字符串,看起来像这样2019-02-06T23:22:28Z。但是,我想要一个看起来像 20190206232240706500000001 的字符串。只有数字(整数)且没有连字符、空格、冒号、Z 或 T 的字符串。实现此目的的简单而优雅的方法是什么?

如果我将每个字符 class 替换为连字符、空格、冒号 Z 和 T:

locals {
  timestamp = "${timestamp()}"
  timestamp_no_hyphens = "${replace("${local.timestamp}", "-", "")}"
  timestamp_no_spaces = "${replace("${local.timestamp_no_hyphens}", " ", "")}"
  timestamp_no_t = "${replace("${local.timestamp_no_spaces}", "T", "")}"
  timestamp_no_z = "${replace("${local.timestamp_no_t}", "Z", "")}"
  timestamp_no_colons = "${replace("${local.timestamp_no_z}", ":", "")}"
  timestamp_sanitized = "${local.timestamp_no_colons}"
}

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

结果输出采用所需格式,但字符串明显更短:

Outputs:

timestamp = 20190207000744

但是,这个解决方案非常难看。是否有另一种方法可以更优雅地做同样的事情,并生成与示例字符串 20190206232240706500000001?

长度相同的字符串

当前interpolate function timestamp()已在源代码中硬编码输出格式RFC3339

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

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

所以你的方法没有问题,但是我们可以稍微改进一下。

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

}

参考:

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.

此答案仅显示了@BMW 的答案示例,对于 Terraform 的新手来说并不明显。

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

}

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

示例运行

运行 #1:

$ terraform apply

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

Outputs:

timestamp = 20190221205825

运行 #2:

$ terraform apply

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

Outputs:

timestamp = 20190221205839

Terraform 0.12.0 引入了一个新函数 formatdate 可以使它更具可读性:

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

在撰写本文时,formatdate 支持的最小单位是整秒,因此这不会给出与正则表达式方法完全相同的结果,但如果最接近的秒足够准确,则可以使用对于 use-case.