Generate file with dynamic content with Terragrunt

Viewed 579

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}"
}
1 Answers

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"
}
Related