Closed2
terraformのリソース名を変更してしまった時の対処方法

そもそも運用が始まっているリソース名は慎重に変更してね、というのは前提として。
チーム開発だと色々あるので。
ここでいうリソース名は実リソース名ではなく、terraformコード上でのリソース名です。
問題
terraformコード内で、SGfoo
のリソース名が'fooo'に変更されてしまったとき。
Error: deleting Security Group (sg-foo): operation error EC2: DeleteSecurityGroup, https response error StatusCode: 400, RequestID: xxxxxxxxxxxxx, api error DependencyViolation: resource sg-foo has a dependent object
Error: creating Security Group (sg-fooo): operation error EC2: CreateSecurityGroup, https response error StatusCode: 400, RequestID: xxxxxxxxxxxxx, api error InvalidGroup.Duplicate: The security group 'sg-fooo' already exists for VPC 'vpc-xxxxxxxxxx'
こんなエラーが出ました。
fooはすでにVPC内で使用されているので、削除できません。
変更先であるfoooがすでに存在しているのも不可解ですが、実行に時間がかかるから、途中でctrl+cとか押しちゃったんでしょうね。

結論
stateを直接整理しましょう
状況確認
terraform state list
...
aws_security_group.foo
...
aws_security_group.fooo
...
変更前後のSGが両方存在してしまっていました。
terraform state rm aws_security_group.fooo
terraform state mv aws_security_group.foo aws_security_group.fooo
terraform apply <---無事通った
変更後のSGのstateを削除することで、無事移行できました。
このスクラップは2025/02/28にクローズされました