Terraform 键未标识此集合中的元素

Terraform key does not identify an element in this collection

我正在关注 terraform tutorial on using variables in AWS

它定义了 AMI 变量,如:

variable "amis" {
  type = "map"
  default = {
    "us-east-1" = "ami-b374d5a5"
    "us-west-2" = "ami-fc0b939c"
  }
}

然后像这样分配 AMI 变量:

resource "aws_instance" "example" {
  ami           = var.amis[var.region]
  instance_type = "t2.micro"
}

如果我以这种方式尝试示例,我会收到错误消息:

Error: Invalid index

  on main.tf line 17, in resource "aws_instance" "example":
  17:   ami                    = var.amis[var.region]

The given key does not identify an element in this collection value: string
required.

但是我可以通过硬编码来设置变量:

var.amis["us-west-2"] # <-- this works

如何使用 ami = var.amis[var.region] 正确设置变量?

您需要定义变量 var.region 或者您可以在计划期间将值传递给变量/应用为 terraform plan -var 'region=us-west-2'terraform apply -var 'region=us-west-2'