/tfmv

proof of concept: a tool to help refactoring Terraform resources

Primary LanguageGoMIT LicenseMIT

tfmv CircleCI

"Terraform Move", a tool to help with Terraform refactoring. The use case: Let's say you have a resource:

// terraform/main.tf
resource "aws_instance" "app" {
  // ...
}

If you change the resource name:

// "app" --> "webapp"
resource "aws_instance" "webapp" {
  // ...
}

or move it into a module:

// terraform/main.tf --> terraform/shared/main.tf
resource "aws_instance" "app" {
  // ...
}

the resource address is different, and Terraform treats it as the old resource being deleted, and the new one being created. Why not reuse them? terraform state mv allows you to update the addresses of resources by hand, but this can be tedious if you are moving more than a few resources.

Goals

In order:

  1. Improve algorithm for resource matching.
    • Currently it's just matching created resources with destroyed ones of the same type, in the order it comes across them. It could be better at guessing created/destroyed resources that are likely meant to be the same.
  2. Gain enough confidence in its functionality that it can be used in deployment pipelines, where it's hard to do state mv by hand.
  3. Propose merging into Terraform core.

Setup

  1. Install Go 1.6+.

  2. Install the package.

    go get github.com/afeld/tfmv

Usage

  1. Create a plan.

    cd <your module>
    terraform plan -out=tfplan
  2. Run the executable. It will compute state mv commands to efficiently reuse resources.

    $ tfmv
    terraform state mv aws_instance.my_instance module.shared.aws_instance.my_instance
    ...
    
  3. After double-checking the output, you can run the commands to avoid deleting and recreating resources unnecessarily.

See also

Development

  1. Install Terraform.

  2. Install dep.

  3. Install the dependencies.

    dep ensure
  4. Run tests.

    go test