如何在Terraform中输出某种类型的所有资源?

8

我在我的Terraform代码中定义了一堆aws_ecr_repositories:

resource "aws_ecr_repository" "nginx_images" {
  name = "nginx-test"
}

resource "aws_ecr_repository" "oracle_images" {
  name = "oracle-test"
}

我希望能够获得一个输出,可以将所有的aws_ecr_repository资源列在一个输出中。以下是我尝试过的方法:
output "ecr_repository_urls" {
  value = "[${aws_ecr_repository.*.repository_url}]"
}

这种方法行不通,因为Terraform不允许在资源名称中使用通配符。有没有可能得到这样的输出呢?我的当前解决方案是列出每个定义的资源的输出。

这是有关问题功能的请求:https://github.com/hashicorp/terraform/issues/19931 - Grzegorz Oledzki
2个回答

8

Terraform的星号语法用于使用count元参数跟踪资源创建的每个事物。

如果您想要能够获取所有存储库URL,可以使用单个aws_ecr_repository资源,并使用类似以下内容的count元参数:

variable "images" {
  default = [
    "nginx-test",
    "oracle-test",
  ]
}

resource "aws_ecr_repository" "images" {
  count = "${length(var.images)}"
  name  = "${var.images[count.index]}"
}

output "ecr_repository_urls" {
  value = "[${aws_ecr_repository.images.*.repository_url}]"
}

请注意,如果列表顺序发生变化(无论是重新排序、在列表中间或开头添加内容,还是删除不是列表中最后一项的内容),那么您可能会意外地重新创建您不想要的存储库。 - Brandon Miller
如何输出所有变量,而不仅仅是repository_url? - Sailesh Kotha

2

您可以将它们手动组合成一个列表:

output "ecr_repository_urls" {
  value = ["${aws_ecr_repository.nginx_images.repository_url}", "${aws_ecr_repository.oracle_images.repository_url}"]
}

虽然代码可能不太美观,但你也可以这样做:

您还可以尝试以下方法:

variable "ecr_repos" {
  default = {
    "0" = "foo"
    "1" = "bar"
  }
}

resource "aws_ecr_repository" "images" {
  count = "${length(var.ecr_repos)}"
  name  = "${lookup(var.ecr_repos,count.index)}-test"
}

output "ecr_repository_urls" {
  value = "${aws_ecr_repository.images.*.repository_url}"
}

但问题在于,如果列表顺序改变,它将重新创建资源,并且由于每个存储库都分配了索引号,这将变得非常丑陋。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接