2

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}"
}
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86

1 Answers1

1

What you have there should work exactly as is, so long as you define the local in the same scope. Just tested the following with Terragrunt v0.28.24.

In common.hcl, a file located in some parent directory (but still in the same Git repo):

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

In your 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
}

After I run terragrunt init, the provider.tf is generated with the expected contents:

provider "azurerm" {
  features {}
  subscription_id = "foo"
}
Ben Whaley
  • 32,811
  • 7
  • 87
  • 85
  • Thanks Ben. By "same scope" you mean defining the local in the same file? My idea was to have the local variables such as `subscription_id` defined somewhere else, as these will change per environment. – Rui Jarimba Jun 10 '21 at 06:42
  • Ahh, should be able to accommodate that with `read_terragrunt_config()`. Answer updated accordingly. – Ben Whaley Jun 10 '21 at 18:50