Adding for_each causes deletion and re-creation

We have a custom module that wraps the Cloudflare module, and I’m attempting to add a domain name to it by using for_each. There’s already one domain name deployed and in our terraform state. Right now I’m just trying to convert our manifest to use for_each, but still with one domain name. I’m hoping to see terraform plan say nothing needs to be done. However, it says everything must be deleted and re-created. I did run terraform plan before I made these changes, and it did say no changes were necessary.

Previously it looked like:

module "cloudflare" {
  frontend_domain    = var.cloudflare_frontend_domain

It now looks like:

module "cloudflare" {
  for_each           = var.cloudflare_frontend_domains
  frontend_domain    = each.value

Terraform v1.2.7. Cloudflare 3.13.0.

Thanks

you state changed from module.cloudflare for this domain to module.cloudlfare["xxxx"] (xxxx => var.cloudflare_frontend_domains).

I suggest terraform state mv src dest before doing plan and apply.

Thanks @ramsateesh. This looks like what I need

If you can predict in your code exactly which instance key the previous single instance has moved to (that is: which key in your map describes the instance you want to preserve) then you can alternatively get a similar effect with a moved block placed alongside the module block:

1 Like

Thanks @apparentlymart

This worked for me:

moved {
    from = module.cloudflare
    to = module.cloudflare["some.domain.name"]
}
1 Like