Adding count to terraform module

Viewed 1077

I have already deployed my VPC via this module listed below before I added a count.

This worked just fine, however do to changes in our infrastructure, I need to add a count to the module

module "core_vpc" {
  source = "./modules/vpc"

  count          = var.environment == "qa" || var.environment == "production" ? 1 : 0
  aws_region     = var.aws_region
  environment    = var.environment
  system         = var.system
  role           = var.system
  vpc_name       = var.system
  vpc_cidr       = var.vpc_cidr
  ssh_key_name   = var.ssh_key_name
  ssh_key_public = var.ssh_key_public
  nat_subnets    = var.nat_subnets
  nat_azs        = var.vpc_subnet_azs

}

Now Terraform wants to update my state file and destroy much of my configuration and replace it with what is shown in the example below. This is of course not just limited to route association, but all resources created within the module.I can't let this happen as I have production running and not want to mess with that.

 module.K8_subnets.aws_route_table_association.subnet[0] will be destroyed

and replace it with:

module.K8_subnets[0].aws_route_table_association.subnet[0] will be created

Is there a way of preventing Terraform of making these changes? Short of changing it manually in the tf-state. All I want is the for the VPC not to be deployed in DEV.

Thanks.

1 Answers

You can "move" the terraform state using tf state mv src target. Specifically you can move the old non-counter version into the new counted version at index 0:

terraform state mv 'module.K8_subnets' 'module.K8_subnets[0]'

This works for individual resources as well as for entire modules. And it works for for_each resource as well, there you would not have an index but a key to move to. And this even works the other way around, if you remove the count / for_each but want to still keep the resource(s).

Related