在terraform.tfvars中声明列表和映射变量值

时间:2019-12-05 04:30:21

标签: variables terraform

我最近将自己的terraform代码中的变量值移到了terraform.tfvars。我现在收到一个错误,原因是我如何声明列表和映射变量。我收到错误的代码复制如下:

image_id             = var.web_amis[var.region]

这就是我在terraform.tfvars中指定这些变量的方式:

web_amis                      = ["ami-0dacb0c129b49f529", "ami-00068cd7555f543d5", ]

这是我得到的错误代码:

Error: Invalid index

  on autoscaling.tf line 3, in resource "aws_launch_configuration" "web_lc":
   3:   image_id             = var.web_amis[var.region]
    |----------------
    | var.region is "us-east-2"
    | var.web_amis is tuple with 2 elements

The given key does not identify an element in this collection value: a number
is required.

A screenshot of the error message given above, showing that Terraform has highlighted the var.region portion as being the problematic part of the source code snippet.

1 个答案:

答案 0 :(得分:0)

您正在尝试使用非索引键而不是按位置访问列表元素。

您可能想要让web_amis变量成为以区域名称作为键的地图:

main.tf

variable "region" {}
variable "web_amis" {}

resource "foo_bar" "baz" {
  # ...
  image_id = var.web_amis[var.region]
} 

terraform.tfvars

web_amis = {
  us-east-2 = "ami-0dacb0c129b49f529"
  us-west-2 = "ami-00068cd7555f543d5"
}

但是,这是一门非常古老的学校,如今与Terraform的处事方式很不雅。相反,您可以使用aws_ami data source根据诸如标签或AMI名称之类的过滤器为该区域查找AMI。

aws_instance resource documentation中给出了一个基本示例:

provider "aws" {
  region = "us-west-2"
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags = {
    Name = "HelloWorld"
  }
}