我正在尝试使用 Terraform 设置一些非常简单的东西,但它给了我一个我以前从未见过的错误。
当我运行 terraform validate -var-file=secrets.tfvars
时,出现以下错误:
Error loading files open /home/MYUSER/Documents/git/packer-with-terraform/terratest/-var-file=secrets.tfvars: no such file or directory
当我运行 terraform plan -var-file=secrets.tfvars
我得到这个:
invalid value "secrets.tfvars" for flag -var-file: Error decoding Terraform vars file: At 1:10: root.variable: unknown type for string *ast.ObjectList
我在同一个文件夹中有三个文件,它们的内容很少:
供应商.tf
provider "aws" {
region = "us-west-1"
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
}
主.tf
resource "aws_instance" "master_proxy" {
ami = "ami-123sample"
instance_type = "t2.micro"
}
secret .tfvars
variable "access_key" { default = "sampleaccesskey" }
variable "secret_key" { default = "samplesecretkey" }
如果我直接设置 access_key
和 secret_key
,而不是通过变量,那么它就可以工作。与 secret 文件类似的设置和诸如此类的东西适用于我的另一个项目;我只是不明白这里出了什么问题。
最佳答案
首先,terraform validate
验证一个包含.tf
文件的文件夹,以检查语法是否正确。您不能将单独的 vars 文件传递给命令。事实上,terraform validate
甚至不会检查您的变量是否设置正确。
其次,您的 secrets.tfvars
文件使用了错误的语法。相反,您希望它看起来更像这样:
secret .tfvars:
access_key = "sampleaccesskey"
secret_key = "samplesecretkey"
但这会出错,因为您实际上没有定义 .tf
文件中的变量:
供应商.tf
variable "access_key" { default = "sampleaccesskey" }
variable "secret_key" { default = "samplesecretkey" }
provider "aws" {
region = "us-west-1"
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
}
如果您没有合理的变量默认值(例如在这种情况下通常如此),那么您可以删除该变量的 default
参数,这将使 Terraform 计划出错,因为未设置必需的变量:
供应商.tf
variable "access_key" {}
variable "secret_key" {}
provider "aws" {
region = "us-west-1"
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
}
关于validation - Terraform .tfvars 转换解码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586046/