执行计划时,Terraform 输出“错误:不允许使用变量”

Sno*_*ash 6 terraform

我有一个variables.tf像这样声明的变量:

variable "MyAmi" {
  type = map(string)
}
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时:

terraform plan -var 'MyAmi=xxxx'
Run Code Online (Sandbox Code Playgroud)

我得到:

Error: Variables not allowed

  on <value for var.MyAmi> line 1:
  (source code not available)

Variables may not be used here.
Run Code Online (Sandbox Code Playgroud)

最小代码示例:

测试文件

provider "aws" {
}

# S3
module "my-s3" {
  source = "terraform-aws-modules/s3-bucket/aws"

  bucket = "${var.MyAmi}-bucket"
}
Run Code Online (Sandbox Code Playgroud)

变量.tf

variable "MyAmi" {
  type = map(string)
}
Run Code Online (Sandbox Code Playgroud)

terraform plan -var 'MyAmi=test'

Error: Variables not allowed

  on <value for var.MyAmi> line 1:
  (source code not available)

Variables may not be used here.
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Rtm*_*tmY 24

当尝试从动态资源(例如:子模块的输出)设置变量的值时,也会发生此错误:

variable  "some_arn" {
  description = "Some description"
  default     = module.some_module.some_output # <--- Error: Variables not allowed
}
Run Code Online (Sandbox Code Playgroud)

使用locals块代替变量可以解决这个问题:

locals {
  some_arn = module.some_module.some_output
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案是不完整的,因为在“.tfvars”文件中执行“foo = local.some_arn”时,我仍然得到“此处不允许变量”。 (3认同)
  • 这不起作用,我仍然收到“此处不允许变量” (2认同)

Ral*_*lph 16

我遇到了同样的错误,但就我而言,我忘记在 terraform.tfvars 文件中将变量值括在引号 (" ") 内。

这在官方 terraform 存储库上被记录为问题: https ://github.com/hashicorp/terraform/issues/24391


rcl*_*ent 7

我发现有两件事可能导致您所看到的错误。terraform plan 文档链接。

  1. 运行时terraform plan,它会自动加载.tfvars当前目录中的任何文件。如果您的.tfvars文件位于另一个目录中,则必须将其作为-var-file参数提供。您在问题中说您的变量位于文件中variables.tf,这意味着该terraform plan命令不会自动加载该文件。修复:重命名variables.tfvariables.tfvars

  2. 使用该-var参数时,应确保 HCL 能够正确解释传入的内容。如果您尝试传入的变量是映射,那么它需要可解析为映射。

相反,terraform plan -var 'MyAmi=xxxx'我会期待更多类似的东西terraform plan -var 'MyAmi={"us-east-1":"ami-123", "us-east-2":"ami-456"}'

有关声明变量以及具体通过命令行传递变量的更多信息,请参阅此文档。