有没有办法在 Terraform 脚本中引用嵌套变量?

Is there a way to refer to nested variable in Terraform script?

我有一个 terraform 脚本,它试图引用同一资源中的属性。我需要将“azurerm_container_group.aci_caddy.fqdn”传递给容器组内的容器实例。

resource "azurerm_container_group" "aci_caddy" {
  resource_group_name = "aci_caddy"
  location            = local.location
  name                = "aci_caddy"
  os_type             = "Linux"
  dns_name_label      = "aci-caddykang"

  container {
    name   = "app"
    image  = "apptest:latest"
    cpu    = "0.5"
    memory = "0.5"
    
    environment_variables = {
      SITE_ADDRESS = "${azurerm_container_group.aci_caddy.fqdn}"
    }

  }
}

但是,我收到了错误消息。

│ Error: Self-referential block
│ 
│   on aci-caddy-main.tf line 29, in resource "azurerm_container_group" "aci_caddy":
│   29:       SITE_ADDRESS = "${azurerm_container_group.aci_caddy.fqdn}"
│ 
│ Configuration for azurerm_container_group.aci_caddy may not refer to itself.

有办法实现吗?谢谢

您不能在自身内部引用资源:azurerm_container_group.aci_caddy.fqdn 因为它还没有被创建。您必须为 SITE_ADDRESS.

创建新变量或局部值

您应该可以使用 dns_name_label 导出 SITE_ADDRESS。所以,而不是硬编码 dns_name_label。您可以在 Terraform

中创建一个变量
variable "dns_label" {
type = string
}

然后在你的容器组资源中引用这个变量。

resource "azurerm_container_group" "aci_caddy" {
  resource_group_name = "aci_caddy"
  location            = local.location
  name                = "aci_caddy"
  os_type             = "Linux"
  dns_name_label      = var.dns_label

  container {
    name   = "app"
    image  = "apptest:latest"
    cpu    = "0.5"
    memory = "0.5"
    
    environment_variables = {
      SITE_ADDRESS = "${var.dns_label}-westus.azurecontainer.io"
    }

  }
}

如果您想进一步改进这一点,您可以了解如何从 azurerm 提供程序数据源获取 region/location。我没有接触过天蓝色的供应商,所以无法快速找到它。但我知道一个事实,即 FQDN 是使用您的 dns_name_label 和 .azurecontainer.io.

派生的