首页 > 解决方案 > Generate file with dynamic content with Terragrunt

问题描述

I'm really new to Terragrunt.

I was wondering if there is a way to dynamically generate the content of a file?

For example, consider the following piece of code:

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
}

Is there a way to set values such as subscription_id dynamically? I've tried using something like ${local.providers.subscription_id} but it doesn't work:

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

标签: terraformterragrunt

解决方案


只要您在同一范围内定义本地,您所拥有的就应该完全按原样工作。刚刚使用 Terragrunt 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"
}

推荐阅读