如何检查字符串是否包含地形插值中的子字符串? [英] How to check if string contains a substring in terraform interpolation?

查看:12
本文介绍了如何检查字符串是否包含地形插值中的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查一个 terraform 字符串是否包含另一个字符串?

How do you check if a terraform string contains another string?

例如,我想特别对待名称中带有tmp"的 terraform 工作空间(例如,允许在没有快照的情况下删除 rds 实例),因此如下所示:

For example, I want to treat terraform workspaces with "tmp" in the name specially (e.g. allowing rds instances to be deleted without a snapshot), so something like this:

locals
{
  is_tmp = "${"tmp" in terraform.workspace}"
}

据我所知,substr插值函数不能做到这一点.

As far as I can tell, the substr interpolation function doesn't accomplish this.

推荐答案

对于 terraform 0.12.xx 显然你应该使用 regexall 来做到这一点.

For terraform 0.12.xx apparently you are suppose to use regexall to do this.

来自 terraform 0.12.XX 的手册:regexall() 文档

From the manual for terraform 0.12.XX: regexall() documentation

regexall 还可用于测试特定字符串是否与给定模式匹配,方法是测试结果匹配列表的长度是否大于零.

regexall can also be used to test whether a particular string matches a given pattern, by testing whether the length of the resulting list of matches is greater than zero.

手册中的示例:

> length(regexall("[a-z]+", "1234abcd5678efgh9"))
2

> length(regexall("[a-z]+", "123456789")) > 0
false

在 terraform 0.12.xx 语法中应用于您的案例的示例应类似于:

Example applied to your case in terraform 0.12.xx syntax should be something like:

locals
{
  is_tmp = length(regexall(".*tmp.*", terraform.workspace)) > 0
}

手册中还特别指出不要使用regex";而是使用正则表达式.

It also specifically says in the manual not to use "regex" but instead use regexall.

如果给定的模式根本不匹配,正则表达式会引发错误.要测试给定模式是否与字符串匹配,请使用 regexall 并测试结果的长度是否大于零.

If the given pattern does not match at all, the regex raises an error. To test whether a given pattern matches a string, use regexall and test that the result has length greater than zero.

如上所述,这是因为当您尝试在运行计划时现已发布的 0.12.xx 的更高版本中使用它时,实际上会收到异常错误.这就是我发现这一点的原因,也是我在此处发布新答案的原因.

As stated above this is because you will actually get an exception error when you try to use it in the later versions of 0.12.xx that are out now when you run plan. This is how I found this out and why I posted the new answer back here.

这篇关于如何检查字符串是否包含地形插值中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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