Terraform’s moved
, import
, and removed
blocks are quite handy. However, it can be a hassle to remove them after you’ve run apply. In reality, there’s no particular restriction stopping you from just deleting them—it’s just tiresome to open a pull request and remove them manually. Although these blocks aren’t used that frequently, I decided to create a tool called tfclean (https://github.com/takaishi/tfclean) to make the removal process easier.
For example, let’s say we have a .tf file like this, containing one aws_security_group resource along with a moved block, an import block, and a removed block:
resource "aws_security_group" "example" {
name = "example-security-group"
description = "Example security group"
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "example-security-group"
}
}
# removed
removed {
from = aws_security_group.example
lifecycle {
destroy = false
}
}
# import
import {
id = "resource_id"
to = module.foo.hoge
}
# moved
moved {
from = module.foo.hoge
to = module.foo.piyo
}
When you run tfclean with the command below, it will automatically remove the moved
, import
, and removed
blocks for you:
./dist/tfclean ./dir/of/tffiles
After running tfclean, the file is modified as follows:
resource "aws_security_group" "example" {
name = "example-security-group"
description = "Example security group"
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "example-security-group"
}
}
# removed
# import
# moved
As you can see, the blocks that previously had to be removed by hand are automatically removed. To streamline this even further, I’ve automated the process in a GitHub Actions workflow:
- Run apply.
- Automatically remove the blocks using tfclean.
- Create a pull request for the changes.
Now, all I need to do is review the diff for the block removals, check the plan results, approve and merge the pull request. I no longer have to manually touch the code. You can find a sample GitHub Actions workflow in the tfclean repository, so feel free to refer to it.
By the way, tfclean can also reference the tfstate file to remove only blocks that have already been applied. Technically, that’s more accurate, but since we usually run it after apply anyway, I’m not sure how often that feature is needed.
% AWS_PROFILE=xxxxxxx tfclean --tfstate s3://path/to/tfstate /path/to/tffiles
Functionally, tfclean is mostly complete, although it might not work perfectly with an import block that uses for_each. If you’re someone who finds it tedious to remove these blocks by hand, I’d love for you to give it a try!
Top comments (0)