2
3

More than 1 year has passed since last update.

Terraformで一部のリソースだけ削除したい|テスト環境での利用

Posted at

今回ご紹介する方法は基本的に本番環境では非推奨とされているようです。
テスト環境などで色々試しているという場面でしたら大丈夫だと思います。

Terraformで一部のリソースを削除するコマンド

以下のようにターゲットオプションを指定してリソースの2つをドット繋ぎで指定します。

terraformDestroy.sh

% terraform destroy -target=aws_s3_bucket.test-bucket

ちなみにこの削除したいリソースは以下のように指定されています。

testbucket.tr

resource "aws_s3_bucket" "test-bucket" {
  bucket = "test-bucket"
}

エラー

コマンド指定を間違えて以下のようなエラーが出ましたのでそちらも載せておきます。

error.sh

% terraform destroy -target="test-bucket"
Error: Invalid target "aws_s3_bucket"
│ 
│ Resource specification must include a resource type and name.

% terraform destroy -target=aws_s3_bucket -target=test-bucket
Error: Invalid target "aws_s3_bucket"
│ 
│ Resource specification must include a resource type and name.

ちなみに今回のようにS3を削除する場合はバケットが空でないと削除できないため以下のようなエラーが出ます。

error.sh

Error: deleting S3 Bucket (test-bucket): BucketNotEmpty: The bucket you tried to delete is not empty

コンソールからバケットの中身を削除するとTerraformからも削除できます。

Warning

以下はterraform destroy -target=aws_s3_bucket.test-bucketを実行した際に表示されます。ここで「このコマンドは日常使いはしないでくださいね」と警告してくれています。

warning.sh

│ Warning: Resource targeting is in effect
│ 
│ You are creating a plan with the -target option, which means that the result of this plan may not represent all of the changes requested by the current configuration.
│ 
│ The -target option is not for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when Terraform specifically suggests to use it as part of an error
│ message.

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3