0
votes

I need to create optimize the structure of terraform.

Have on root path variables which I imported like module /variables.tf

variable "aws_profile" { default = "default" }
variable "aws_region" { default = "us-east-1" }

After have a module folder /ec2_instance/main.tf

module "global_vars" {
  source = "../"
}

provider "aws" {
  region  = module.global_vars.aws_region
  profile = module.global_vars.aws_profile
}

terraform {
  backend "s3" {
    encrypt = true
    bucket  = "some_bucket"
    key     = "path_to_statefile/terraform.tfstate"
    region  = "region"
    profile = "profile"
  }
}

module "instances_cluster" {
  some actions
}

It's working, but I need to move backend and provider part to main.tf on root folder and after include like the module. How I can do this?

I have tried to create /main.tf on root folder with backend part, but they are not working and backed writing state files locally.

1

1 Answers

0
votes

You'd have to a bit of refactoring but these are the steps I would take

  1. Run terraform plan in root and ec2_instance modules to verify zero changes so refactoring can begin
  2. Comment out the backend for ec2_instance/main.tf
  3. Place the backend from ec2_instance/main.tf into root main.tf
  4. In the root main.tf, make a reference to ec2_instance module
  5. Run terraform plan in root module and note the creations and deletions
  6. For each creations and deletion pair, create a terraform state mv statement and run each
  7. Verify the terraform plan has zero changes