Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform moved several element at once

Tags:

terraform

I'm using the terraform moved block to replace some resources without destroying/recreating them.

It's a list of resources, and for now, the only way I found to replace is using several moved blocks

moved {
  from = null_resource.default[0]
  to = null_resource.default["0"]
}

moved {
  from = null_resource.default[1]
  to = null_resource.default["1"]
}

moved {
  from = null_resource.default[2]
  to = null_resource.default["2"]
}

...

moved {
  from = null_resource.default[20]
  to = null_resource.default["20"]
}

Even if it works well, I'm almost sure it's not the most optimized way. I have 20 resources to replace and it's just 20 times copy/paste.

Is there a way to do that in a smarter way? using a loop for example

Thanks

like image 298
iAmoric Avatar asked Oct 21 '25 05:10

iAmoric


1 Answers

I don't know your full use case, but in cases where resources being moved are not part of a shared module so they are only present in a small number of states then it may be better to use classic method with the CLI to move the resources. terraform state mv {from} {to}

Another option would be, if you are not changing the keys of the resource id then you don't have to specify each key individually.

moved {
  from = null_resource.default
  to = null_resource.default_new
}

In your example however you are changing the key type from a number to a string. So if that is required this will not be as helpful.

The moved blocks are a great tool and very helpful with shared modules, but it does have this limitation. I would also very much like to see for_each support added to the moved block.

like image 109
Tom George Avatar answered Oct 23 '25 21:10

Tom George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!