Search code examples
terraformterragrunt

why terragrunt destroy previous created resources


i organized our terraform code as below:

     $ tree infrastructure
    infrastructure
    ├── ecr
    │   └── terraform.tfvars
    ├── ecs
    │   ├── ecs-iam.json
    │   └── terraform.tfvars
    └── terraform.tfvars

    2 directories, 4 files
    $cat infrastructure/terraform.tfvars 
    terragrunt = {
     remote_state {
    backend = "s3"
    config {
      bucket     = "terraform-dev-state-west2"
      key        = "dev/terraform.tfstate"
      region     = "us-west-2"
      encrypt    = true
    }
  }
}

Under each component directory, i will define properties of shared module

$more infrastructure/ecr/terraform.tfvars
terragrunt = {
  include {
    path = "${find_in_parent_folders()}"
  }

  terraform {
    source = "git::ssh://[email protected]/deployment//modules/ecr"
  }
}

repository_names = [
  "web",
  "db",
  "cache",
  "log"
]

I can go to individual directory like ecr or ecs, run "terragrunt init; terragrunt apply" without problem. It will create AWS ECR or AWS ECS cluster. But when I run terragrunt in ECR directory, it will destroy previously created ECS cluster. If i created ECR resource first, then cd ecs to run terragrunt, it will destroy ECR resources. Even i put ECR dependencies in ECS terraform.tfvars file, it has the same result. I think it is because terragrunt doesn't include resource definition from all sub folders under "infrastructure". If that is the case, is it possible to structure terraform directories in such way?


Solution

  • yes, i can separate infrastructure components into different folders. However you must keep each component different key so different components do not share state between each other. Here is my change.

    $cat infrastructure/terraform.tfvars 
        terragrunt = {
         remote_state {
        backend = "s3"
        config {
          bucket     = "terraform-dev-state-west2"
          key        = "${path_relative_to_include()}/terraform.tfstate"
          region     = "us-west-2"
          encrypt    = true
        }
      }
    }
    

    After this change, i can run terragrunt under sub folder without impacting each other.