【发布时间】:2021-12-24 21:37:22
【问题描述】:
我有多个 aws_glue_catalog_table 资源,我想创建一个 output 循环遍历所有资源以显示每个资源的 S3 存储桶位置。这样做的目的是测试我是否为 Terratest 中的每个资源使用了正确的location(因为它是变量的串联)。我不能使用 aws_glue_catalog_table.* 或 aws_glue_catalog_table.[],因为 Terraform 不允许在不指定名称的情况下引用资源。
所以我用r1、r2、rx 创建了一个variable "table_names"。然后,我可以遍历名称。我想动态创建字符串aws_glue_catalog_table.r1.storage_descriptor[0].location,这样我可以检查location是否正确。
resource "aws_glue_catalog_table" "r1" {
name = "r1"
database_name = var.db_name
storage_descriptor {
location = "s3://${var.bucket_name}/${var.environment}-config/r1"
}
...
}
resource "aws_glue_catalog_table" "rX" {
name = "rX"
database_name = var.db_name
storage_descriptor {
location = "s3://${var.bucket_name}/${var.environment}-config/rX"
}
}
variable "table_names" {
description = "The list of Athena table names"
type = list(string)
default = ["r1", "r2", "r3", "rx"]
}
output "athena_tables" {
description = "Athena tables"
value = [for n in var.table_names : n]
}
第一次尝试:我尝试使用语法 aws_glue_catalog_table.${table} 创建一个 output "athena_tables_location",但确实做到了。
output "athena_tables_location" {
// HOW DO I ITERATE OVER ALL TABLES?
value = [for t in var.table_names : aws_glue_catalog_table.${t}.storage_descriptor[0].location"]
}
第二次尝试:我尝试创建 variable "table_name_locations",但 IntelliJ 已经在 for 循环 [for t in var.table_names : "aws_glue_catalog_table.${t}.storage_descriptor[0].location"] 中显示错误 ${t}。
variable "table_name_locations" {
description = "The list of Athena table locations"
type = list(string)
// THIS ALSO DOES NOT WORK
default = [for t in var.table_names : "aws_glue_catalog_table.${t}.storage_descriptor[0].location"]
}
如何列出output 中的所有表格位置,然后使用 Terratest 对其进行测试?
一旦我可以遍历表并收集 S3 位置,我就可以使用 Terratest 进行以下测试:
athenaTablesLocation := terraform.Output(t, terraformOpts, "athena_tables_location")
assert.Contains(t, athenaTablesLocation, "s3://rX/test-config/rX",)
【问题讨论】:
-
试试:
aws_glue_catalog_table[t].storage_descriptor[0].location -
我必须在
aws_glue_catalog_table.[t].storage_descriptor[0].location后面加上.aws_glue_catalog_table。但是I get the error期望得到 '['` -
不,
[之前的点是无效的语法,这就是您收到该错误的原因。因此,您绝对不必在aws_glue_catalog_table之后执行.。你真的尝试了我的建议吗? -
是的,我试过了。如果我不使用
.,我会收到错误Unresolved reference storage_descriptor -
当我使用
aws_glue_catalog_table[t].并执行 Ctrl + 空格时,IntelliJ 建议使用表的名称自动完成r1...rX。 IntelliJ 认为我与没有[t]的aws_glue_catalog_table处于同一水平。顺便说一句,我正在为 IntelliJ 使用 golang 插件。所以我想问题不在于 IntelliJ。它仍然是语法。