gpt4 book ai didi

Terraform timestamp() 为仅数字字符串

转载 作者:行者123 更新时间:2023-12-04 22:02:49 25 4
gpt4 key购买 nike

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

如果我在连字符、空格、冒号 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.

关于Terraform timestamp() 为仅数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com