首页 > 解决方案 > Unable to read variables from Terraform variable file

问题描述

Here is my setup,

Terraform version - Terraform v0.12.17 OS - OSX 10.15.1

Use Case - define a provider file and access the variables defined in the vars file

Files main.tf - where the code is

provider "aws" {

}

variable "AWS_REGION" {
    type = string
}

variable "AMIS" {
    type = map(string)
    default = {
        us-west-1 = "my ami"
    }
}

resource "aws_instance" "awsInstall" {
    ami = var.AMIS[var.AWS_REGION]
    instance_type = "t2.micro"
}

awsVars.tfvars - where the region is defined

AWS_REGION="eu-region-1"

Execution

$ terraform console

var.AWS_REGION

Error: Result depends on values that cannot be determined until after "terraform apply".

What mistake I have done, I don't see any syntax but have issues in accessing the variables, any pointers would be helpful

Thanks

标签: terraformterraform-provider-aws

解决方案


Terraform 不会自动读取.tfvars文件,除非文件名以.auto.tfvars. 因此,当您在terraform console没有参数的情况下运行时,Terraform 不知道 variable 的值AWS_REGION

要保留现有文件名,您可以在命令行上显式传递此变量文件,如下所示:

terraform console -var-file="awsVars.tfvars"

或者,您可以将文件重命名为awsVars.auto.tfvars,然后 Terraform 将默认读取它,只要它在您运行 Terraform 时位于当前工作目录中。

在 Terraform 文档部分将值分配给根模块变量中提供了有关如何为根模块输入变量设置值的更多信息。


另请注意,输入变量和其他特定于 Terraform 的对象的通常命名约定是将名称保持为小写,并用下划线分隔单词。例如,将变量命名为aws_regionamis.

此外,如果您的目标是找到当前区域的 AMI(由AWS_DEFAULT_REGION环境变量或提供程序配置选择的那个),您可以使用数据aws_region来允许 Terraform 自动确定,因此您没有将其设置为变量:

variable "amis" {
  type = map(string)
  default = {
    us-west-1 = "my ami"
  }
}

data "aws_region" "current" {}

resource "aws_instance" "awsInstall" {
  ami           = var.amis[data.aws_region.current.name]
  instance_type = "t2.micro"
}

推荐阅读