使用 Terragrunt 生成具有动态内容的文件

Generate file with dynamic content with Terragrunt

我是 Terragrunt 的新手。

我想知道有没有办法动态生成文件的内容?

例如,考虑以下代码:

generate "provider" {
    path      = "provider.tf"
    if_exists = "overwrite"
    contents = <<EOF
terraform {
 required_providers { 
    azurerm = { 
      source = "azurerm"
      version = "=2.49.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "xxxxxxxxxxxxxxxxx"
}
EOF
}

有没有办法动态设置subscription_id等值?我试过使用 ${local.providers.subscription_id} 之类的东西,但它不起作用:

provider "azurerm" {
  features {}
  subscription_id = "${local.providers.subscription_id}"
}

只要您在同一范围内定义局部变量,您所拥有的就应该完全按原样工作。刚刚使用 Terrag运行t v0.28.24.

测试了以下内容

common.hcl 中,位于某个父目录中的文件(但仍在同一个 Git 存储库中):

locals {
  providers = {
    subscription_id = "foo"
  }
}

在你的terragrunt.hcl中:

locals {
  common_vars = read_terragrunt_config(find_in_parent_folders("common.hcl"))
}

generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite"
  contents  = <<EOF
terraform {
 required_providers {
    azurerm = {
      source = "azurerm"
      version = "=2.49.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "${local.common_vars.locals.providers.subscription_id}"
}
EOF
}

在我运行terragrunt init之后,provider.tf生成了预期的内容:

provider "azurerm" {
  features {}
  subscription_id = "foo"
}