【Terraform】Terraform ~ 特定リソースのみデプロイ・削除する ~

■ はじめに

小ネタ。

エラー「AlreadyExistsException: Workflow with name 'xxx-xxxx' already Exists」
が出たので、一つの解決案として、
「特定リソースのみデプロイする」ってのが
あったので、調査。

目次

【1】トラブル概要
 1)エラー内容
 2)原因および解決案
 補足:本来の解決案
【2】関連するTerraformコマンド
 1)terraform state list
 2)terraform apply --target=xxxx
 3)terraform destroy --target=xxxx
【3】コマンド例

【1】トラブル概要

Glue/S3 へのデプロイについて、
terraform apply コマンド実行後に
以下「エラー内容」が表示される

1)エラー内容

Error: creating Glue Trigger (xxx-xxxx-xxx):
AlreadyExistsException: Workflow with name 'xxx-xxxx-xxx' already Exists

 with yyy_yyy_yyyy,
 on xxxx.tf line 111, in resource "aws_glue_workflow" "xxxxx_xxxxxx":
 111: resource "aws_glue_workflow" "xxxxx_xxxxxx" {

2)原因および解決案

原因は、既にリソースをデプロイした上でデプロイ実行しようとしたことは
エラーの内容からは分かるし、エラー箇所のリソースを削除すれば解決するのは
分かっている上で、以下のサイトに

https://stackoverflow.com/questions/59757995/how-to-ignore-duplicate-resource-error-during-terraform-apply

より抜粋
~~~~~~~
use terraform apply --target=xxx to apply only
 resources you need to apply (NOT RECOMMENDED)
~~~~~~~
 => この方法も「NOT RECOMMENDED」なのだがやり方を調べたみた
 => 本当は、今のリソースと差分がなければ無視。
  差分があれば差分部分をUpdateって勝手にやってくれればいいのだが、、、

補足:本来の解決案

* 以下の関連記事を参照のこと

Terraform ~ tfstateファイル ~
https://dk521123.hatenablog.com/entry/2023/05/05/004939

【2】関連するTerraformコマンド

1)terraform state list

* 使用しているリソースを一覧表示
 => 「terraform apply --target=【対象リソース】」でデプロイするのだが
  この「【対象リソース】」を調べるためのコマンド

https://developer.hashicorp.com/terraform/cli/commands/state/list

2)terraform apply --target=xxxx

* 特定リソースのみデプロイする

# terraform plan --target="random_pet.bucket_name"
terraform apply --target="random_pet.bucket_name"

3)terraform destroy --target=xxxx

* 特定リソースのみ削除する

# terraform destroy --target=[リソース名] --target=[リソース名]
terraform destroy --target="random_pet.bucket_name"

【3】コマンド例

# Step1:「terraform state list」を実行して、リソース一覧を表示
terraform state list
 xxxx1
 xxxx2
 xxxx3
 ...

# Step2:Step1の中で対象リソースを確認し
# 「terraform apply --target=xxxx」を実行
terraform apply --target=xxxx2

関連記事

Terraform ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/05/000224
Terraform ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2019/12/09/222057
Terraform ~ 基本編 / tfstateファイル ~
https://dk521123.hatenablog.com/entry/2023/05/05/004939
Terraform ~ AWS S3 ~
https://dk521123.hatenablog.com/entry/2023/04/09/104204
Terraform ~ AWS IAM ~
https://dk521123.hatenablog.com/entry/2023/04/12/214311
Terraform ~ AWS Glue ~
https://dk521123.hatenablog.com/entry/2023/04/08/220411
Terraform ~ AWS Secrets Manager ~
https://dk521123.hatenablog.com/entry/2023/04/11/152801
Terraform ~ Docker ~
https://dk521123.hatenablog.com/entry/2023/04/10/193239
Terraform ~ 複数環境へデプロイすることを考える ~
https://dk521123.hatenablog.com/entry/2023/05/06/003645