This post introduces tfmv, a CLI tool that simplifies refactoring Terraform resource names with just one command.
For instance, to replace hyphens (-
) with underscores (_
), you can run:
tfmv -r '-/_'
Then resource are renamed:
-resource "github_repository" "example-1" {
+resource "github_repository" "example_1" {
name = "example-1"
}
data "github_branch" "example" {
- repository = github_repository.example-1.name
+ repository = github_repository.example_1.name
branch = "example"
}
And a moved block is created:
moved {
from = github_repository.example-1
to = github_repository.example_1
}
Features of tfmv
- Rename Terraform Resources, Data Sources, and Modules
- Modify resource references
- Generate moved blocks
-
Easy to install
- tfmv is a single binary written in Go. You only need to put tfmv into $PATH
- Cross platform: Windows, macOS, and Linux
- Flexible Resource Filtering with Regular Expressions
- Use
--include <regexp>
to rename only resources matching a specific pattern - Use
--exclude <regexp>
to skip renaming for resources matching a specific pattern
- Use
- Support for Multiple Renaming Methods
- Fixed String Replacement: Use
--replace (-r)
to specify straightforward string substitutions - Regular Expression: Use
--regexp
to perform pattern-based renaming -
Jsonnet: Use
--jsonnet (-j)
for advanced, programmatically controlled renaming logic
- Fixed String Replacement: Use
These features make tfmv a powerful and flexible tool for refactoring Terraform configurations.
Quick start
- Install tfmv according to the guide
- Create
main.tf
and make a backup of it asmain.tf.bak
:
echo 'resource "github_repository" "example-1" {
name = "example-1"
}
data "github_branch" "example-2" {
repository = github_repository.example-1.name
branch = "example"
}' > main.tf
cp main.tf main.tf.bak
- Run tfmv to replace
-
with_
:
tfmv -r '-/_'
Then check the result:
diff main.tf main.tf.bak
1c1
< resource "github_repository" "example_1" {
---
> resource "github_repository" "example-1" {
5,6c5,6
< data "github_branch" "example_2" {
< repository = github_repository.example_1.name
---
> data "github_branch" "example-2" {
> repository = github_repository.example-1.name
moved.tf:
moved {
from = github_repository.example-1
to = github_repository.example_1
}
Congratulations! 🎉 You’ve successfully refactored Terraform resource names with just one command.
Conclusion
In this post I introduced tfmv, a powerful Terraform refactoring tool.
Using tfmv, you can efficiently rename Terraform resources and generate moved blocks.
For more details, check out the README.md on GitHub.
Top comments (0)