terraform - 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
解决方案
Terraform 不会自动读取.tfvars
文件,除非文件名以.auto.tfvars
. 因此,当您在terraform console
没有参数的情况下运行时,Terraform 不知道 variable 的值AWS_REGION
。
要保留现有文件名,您可以在命令行上显式传递此变量文件,如下所示:
terraform console -var-file="awsVars.tfvars"
或者,您可以将文件重命名为awsVars.auto.tfvars
,然后 Terraform 将默认读取它,只要它在您运行 Terraform 时位于当前工作目录中。
在 Terraform 文档部分将值分配给根模块变量中提供了有关如何为根模块输入变量设置值的更多信息。
另请注意,输入变量和其他特定于 Terraform 的对象的通常命名约定是将名称保持为小写,并用下划线分隔单词。例如,将变量命名为aws_region
和amis
.
此外,如果您的目标是找到当前区域的 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"
}
推荐阅读
- python - 如何以正确答案结束 While 循环?
- hive - ParseException line 5:19 无法识别表达式规范中“SELECT”“MIN”“(”附近的输入(状态=42000,代码=40000)
- rest - 如何从我的 Spring Boot 应用程序控制器创建对另一个 API 的 PATCH 请求?
- java - 在单独的文件夹中获取所有库 jar
- scala - 在 Scala 中运行测试用例会给出“丢弃的非单元值”
- powershell - 有没有办法通过智能卡通过powershell远程激活Windows?
- batch-file - 批量循环数组
- javascript - 比较对象并提取深度差异
- python - 使用请求登录后无法使用 Selenium 获取配置文件名称
- sql-server - SSIS - 控制错误日志发送到 SSIS 目录