Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding count to terraform module

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.

like image 256
dinodam Avatar asked Apr 24 '26 07:04

dinodam


2 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).

like image 163
luk2302 Avatar answered Apr 26 '26 13:04

luk2302


More suitable answer is the one in comments of accepted answer.

Terraform has introduced a moved { } block from Terraform v1.1 and later.

https://developer.hashicorp.com/terraform/language/modules/develop/refactoring

like image 42
hassanbsalimi Avatar answered Apr 26 '26 12:04

hassanbsalimi