Search code examples
terragrunt

how to get and pass in terragrutn a variable in a child file terragrunt


I am writing this post to ask if anyone is willing to provide an explanation of how the variables in terragrunt and the outputs provided by the modules work. example must keep these conditions in mind:

--> The structure must have this form

── sandbox
   ├── common.tfvars
   ├── eu-west-1
   │   ├── aws-data
   │   │   └── terragrunt.hcl
   │   ├── ecs-cluster
   │   │   └── terragrunt.hcl
   │   ├── ecs-service
   │   │   └── terragrunt.hcl
   │   ├── regional.tfvars
   │   └── vpc
   │       └── terragrunt.hcl
   └── terragrunt.hcl

and also the variables such as enviroment and region are taken from the name of the folders.

--> In addition to the local variables must be taken variables from the tfvars.

If you can also provide a practical example that would be great. i thank all those who will answer in advance


Solution

  • I write this answer after succeeding using my folder configuration to pass both the variables in common that were in the terragrunt.hcl present in the root, within all the services scattered in different environments (sandbox, dev) and regions (eu-west-1,eu-west-2).

    pass the variables and call them back

    locals {
      rel_path = get_path_from_repo_root()
      environment = split("/", local.rel_path)[1] 
      
      common_vars = jsondecode(read_tfvars_file(find_in_parent_folders("common.tfvars")))
      regional_vars = jsondecode(read_tfvars_file(find_in_parent_folders("regional.tfvars")))
      
      aws_profile   = get_env("AWS_PROFILE", "<company>-${local.environment}")
      cluster_name  = get_env("AWS_CLUSTER_NAME", "${local.environment}-terragrunt")
    
      tfvars = merge(merge(local.common_vars, {region = get_env("AWS_REGION", split("/", local.rel_path)[2])}),local.regional_vars) // priority= regional.tfvars -> env -> folder name -> common.tfvars
    }
    
    inputs = { // mutch important for pass deta
      environment = local.environment
      aws_profile = local.aws_profile
      cluster_name = local.cluster_name
      tfvars      = local.tfvars
      rel_path   = local.rel_path
    }
    // sandbox/eu-west-1/vpc
    include "root" {
      path   = find_in_parent_folders()
      expose = true
    }
    
    // for call = include.root.locals.environment 
    

    how to dynamically get the enviroment name and region

    rel_path = get_path_from_repo_root()
    environment = split("/", local.rel_path)[1] 
    

    to keep in mind

    for lanch all run = terragrunt run-all apply on eu-west-1 directory