如何在 terraform 代码中访问 terragrunt 变量

How to access terragrunt variables in terraform code

我有 terragrunt 配置,其中已在根级别使用如下局部变量声明变量。在子模块中,声明了名为 (terragrunt.hcl) 的子 terragrunt 配置文件。 父 terragrunt 文件具有以下代码:

locals {
  location = "East US"
}

子模块 terragrunt 文件具有以下代码:

include {
  path = find_in_parent_folders()
}

locals {
  myvars = read_terragrunt_config(find_in_parent_folders("terragrunt.hcl"))
  location = local.myvars.locals.location
}

现在,尝试使用以下代码访问 terraform 代码 (main.tf) 中的 location 变量:

 location = "${var.location}"

但它抛出错误:

Error: Reference to undeclared input variable

  on main.tf line 13, in resource "azurerm_resource_group" "example":
  13:   location = "${var.location}"

不知道如何访问 terraform 代码中 terragrunt 文件中定义的变量。请推荐

此错误消息表示您的根模块未声明它期望被赋予 location 值,因此您无法引用它。

在您的根 Terraform 模块中,您可以通过使用 variable 块声明它来声明您期望这个变量,如错误消息提示:

variable "location" {
  type = string
}

此声明将使其在根模块中的其他地方引用 var.location 有效,如果您不小心 运行 它 ,它也会导致 Terraform 产生错误没有为此location变量提供值。