Terraform timestamp()只能为数字字符串 [英] Terraform timestamp() to numbers only string

查看:166
本文介绍了Terraform timestamp()只能为数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The timestamp() function in the interpolation syntax will return an ISO 8601 formatted string, which looks like this 2019-02-06T23:22:28Z. However, I want to have a string which looks like this 20190206232240706500000001. A string with only numbers (integers) and no hyphens, white spaces, colon, Z or T. What is a simple and elegant way to achieve this?

如果我在连字符,空格,冒号Z和T时替换了每个字符类,则可以使用该功能

It works if I replace every a single character class at the time hyphens, white spaces, colon Z and 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}"
}

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

The resulting output is in the desired format, except the string is significantly shorter:

Outputs:

timestamp = 20190207000744

但是,此解决方案非常难看.

However, this solution is very ugly. Is there another way of doing the same thing in a more elegant way as well as producing a string with the same length as the example string 20190206232240706500000001?

推荐答案

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

返回时间.Now().UTC().Format(time.RFC3339),无

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}", "/[- TZ:]/", "")}"

}

参考:

https://github.com/google/re2/wiki/语法

replace(string,search,replace)-在给定的字符串上进行搜索和替换.搜索的所有实例都将替换为replace的值.如果搜索用正斜杠包装,则将其视为正则表达式.如果使用正则表达式,则replace可以通过使用$ n引用正则表达式中的子捕获,其中n是子捕获的索引或名称.如果使用正则表达式,则语法符合re2正则表达式语法.

这篇关于Terraform timestamp()只能为数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆