如何在Terraform中正确访问本地对象属性以生成资源名称?
问题解决:Terraform 基于本地对象生成资源名称
问题背景
你定义了如下本地对象:
first = { sns = "first-rzv3-sns-prod" s3 = "first-rzv3-s3-prod" sqs = "first-rzv3-sqs-prod" } second = { s3 = "second-rzv3-s3-prod" ec2 = "second-rzv3-ec2-prod" }
并定义变量 user = [first, second],尝试通过以下代码创建资源时无法得到期望的S3桶名称:
resource "create_s3_bucket" "example" { count = length(user) name = local.hashed_names_prod."${var.user[count.index]}".s3 }
期望得到的名称分别是 "first-rzv3-s3-prod" 和 "second-rzv3-s3-prod"。
错误原因
原代码中 var.user[count.index] 是对象本身,而非字符串类型的键名,无法直接用来访问 local.hashed_names_prod 这个映射结构。
解决方案
提供两种可行的解决方式,根据你的实际需求选择:
方式一:将user改为键名字符串列表
如果需要保留local.hashed_names_prod的映射结构,可以把user定义为包含对象键名的字符串列表,直接通过键名访问对应对象的s3属性:
# 定义本地映射 locals { hashed_names_prod = { first = { sns = "first-rzv3-sns-prod" s3 = "first-rzv3-s3-prod" sqs = "first-rzv3-sqs-prod" } second = { s3 = "second-rzv3-s3-prod" ec2 = "second-rzv3-ec2-prod" } } } # 定义变量为字符串列表 variable "user" { type = list(string) default = ["first", "second"] } # 创建资源 resource "create_s3_bucket" "example" { count = length(var.user) name = local.hashed_names_prod[var.user[count.index]].s3 }
方式二:直接使用对象列表访问属性
如果不需要local.hashed_names_prod的映射结构,直接利用user列表中的对象属性即可:
# 定义本地对象 locals { first = { sns = "first-rzv3-sns-prod" s3 = "first-rzv3-s3-prod" sqs = "first-rzv3-sqs-prod" } second = { s3 = "second-rzv3-s3-prod" ec2 = "second-rzv3-ec2-prod" } } # 定义变量为对象列表 variable "user" { type = list(object({ s3 = string # 可根据需要添加其他可选属性,如sns、sqs、ec2 })) default = [local.first, local.second] } # 创建资源 resource "create_s3_bucket" "example" { count = length(var.user) name = var.user[count.index].s3 }
两种方式都能生成你期望的S3桶名称。
内容的提问来源于stack exchange,提问作者minnie
相关产品推荐
相关产品推荐

