在 Terraform 中如何进行简单的字符串连接?

我一定是非常愚蠢,但是我不知道如何在 Terraform 中做简单的字符串连接。

我有以下数据 null_data_source:

data "null_data_source" "api_gw_url" {
inputs = {
main_api_gw = "app.api.${var.env_name == "prod" ? "" : var.env_name}mydomain.com"
}
}

因此,当 env_name="prod"我想输出 app.api.mydomain.com和其他任何东西-让我们说 env_name="staging"我想 app.api.staging.mydomain.com

但是上面将输出 app.api.stagingmydomain.com < ——注意 staging后面缺少的点。

如果 env _ name 不是“ prod”而是 Terraform 错误,我尝试连接“ .”:

data "null_data_source" "api_gw_url" {
inputs = {
main_api_gw = "app.api.${var.env_name == "prod" ? "" : var.env_name + "."}mydomain.com"
}
}

错误是 __builtin_StringToInt: strconv.ParseInt: parsing ""

TF 中的 concat()函数似乎用于列表而不是字符串。

正如标题所说: 在 Terraform 中如何进行简单的字符串连接?

我不敢相信我在问如何连接两个字符串在一起 XD

更新:

对于任何有类似问题的人,我暂时做了这个 太可怕了变通方法:

main_api_gw = "app.api.${var.env_name == "prod" ? "" : var.env_name}${var.env_name == "prod" ? "" : "."}mydomain.com"

149955 次浏览

Try Below data resource :

data "null_data_source" "api_gw_url" {
inputs = {
main_api_gw = "app.api${var.env_name == "prod" ? "." : ".${var.env_name}."}mydomain.com"
}
}

I know this was already answered, but I wanted to share my favorite:

format("%s/%s",var.string,"string2")

Real world example:

locals {
documents_path = "${var.documents_path == "" ? format("%s/%s",path.module,"documents") : var.documents_path}"
}

More info:
https://www.terraform.io/docs/configuration/functions/format.html

after lot of research, It finally worked for me. I was trying to follow https://www.hashicorp.com/blog/terraform-0-12-preview-first-class-expressions/, but it did not work. Seems string can't be handled inside the expressions.

data "aws_vpc" "vpc" {
filter {
name   = "tag:Name"
values = ["${var.old_cluster_fqdn == "" ? "${var.cluster_fqdn}" : "${var.old_cluster_fqdn}"}-vpc"]
    

}
}

so to add a simple answer to a simple question:

  • enclose all strings you want to concatenate into one pair of ""
  • reference variables inside the quotes with ${var.name}

Example: var.foo should be concatenated with bar string and separated by a dash

Solution: "${var.foo}-bar"

For Terraform 0.12 and later, you can use join() function:

join(separator, list)

Example:

> join(", ", ["foo", "bar", "baz"])
foo, bar, baz
> join(", ", ["foo"])
foo

If you just want to concatenate without a separator like "foo"+"bar" = "foobar", then:

> join("", ["foo", "bar"])
foobar

Reference: https://www.terraform.io/docs/configuration/functions/join.html

Use the Interpolation Syntax for versions < 0.12

Here is a simple example:

output "s3_static_website_endpoint" {
value = "http://${aws_s3_bucket.bucket_tf.website_endpoint}"
}

Reference the Terraform Interpolation docs: https://developer.hashicorp.com/terraform/language/expressions/strings#string-templates