Terraform执行plan报错:给定键不在map集合,需定义变量类型?
Terraform报错问题解答
问题描述
我的TF文件中有以下代码:
existing_alerting_sns_topic = "arn:aws:sns:${var.aws_region}:${module.account.id["ab-cd"]}:cd-prod-${var.aws_region}-slack-notifier-infrastructure-alerts"
尚未在variable.tf中定义相关内容,执行terraform plan时出现如下报错:
│ │ existing_alerting_sns_topic = "arn:aws:sns:${var.aws_region}:${module.account.id["ab-cd"]}:cd-prod-${var.aws_region}-slack-notifier-infrastructure-alerts" │ ├──────────────── │ │ module.account.id is map of string with 105 elements │ │ The given key does not identify an element in this collection value
疑问:是否需要定义map(any)或map(list(string))这类变量类型?
解答
不需要额外定义map(any)或map(list(string))类型的变量,当前报错的核心原因是你引用的module.account.id这个map里不存在"ab-cd"这个键,和变量定义无关。
解决步骤:
- 检查
module.account的实现,确认其输出的idmap包含的键,核对"ab-cd"是否存在拼写错误(比如误用中文引号、大小写不匹配) - 如果
"ab-cd"是业务需要的键,需确保module.account能正确生成或包含该键对应的账号ID - 另外,代码中的
var.aws_region未在variable.tf定义,后续执行也会报错,建议补充定义:
variable "aws_region" { type = string description = "AWS区域" }
内容的提问来源于stack exchange,提问作者TinA
相关产品推荐
相关产品推荐

