1
votes

I want to refactor my Terraform scripts a bit.

Before:

resource "aws_s3_bucket" "abc" {
  bucket = "my-bucket"
  acl    = "private"
  region = "${var.aws_region}"

  tags = {
    Name = "My bucket"
  }

  versioning {
    enabled = true
    mfa_delete = false
  }
}

After:

resource "aws_s3_bucket" "def" {
  bucket = "my-bucket"
  acl    = "private"
  region = "${var.aws_region}"

  tags = {
    Name = "My bucket"
  }

  versioning {
    enabled = true
    mfa_delete = false
  }
}

As you can see, only the name in Terraform has changed (abc -> def).

However, this causes a create / destroy of the bucket in terraform plan.

I expected Terraform recognize the buckets as the same (they have the same attributes, including bucket).

Questions:

  • Why is this?
  • Is there a way to refactor Terraform scripts without destroying infrastructure?
1
because of the resource state is not changed, you just changed the code only. So you have to follow the answer.Lamanus

1 Answers

7
votes

You can use terraform state mv, to reflect this change in the state.

In you case, this would be

terraform state mv aws_s3_bucket.abc aws_s3_bucket.def

From my own experience, this works well and I recommend doing it instead of working with bad names.

Terraform does not recognize such changes, no :-)