Terraformで特定のモジュール、リソースを対象にしてplan/applyを実行する。
terraformで特定のモジュール、リソースに対してplan/applyを実行したいことってありますよね。
今回はその方法を以下に記載します。
フォルダ構造はこんな感じです。
.├── main.tf└── modules ├── s3 │ └── aws_s3_bucket.tf └── vpc └── aws_vpc.tf
通常の実行
通常、terraformリソースを環境に反映するのは以下のように実行します。
terraform planterraform apply
この場合、s3とvpcモジュールの中身が反映されます。
これをs3モジュールだけ反映させることもできます。
モジュールを指定して実行
モジュールを指定して実行するには以下の通り-target=module.<実行したいモジュール名>
とします。
terraform plan -target=module.s3terraform apply -target=module.s3
-target
は複数指定することが可能です。
s3とvpcモジュールを指定したい場合は以下のようにします。
terraform plan -target=module.s3 -target=module.vpcterraform apply -target=module.s3 -target=module.vpc
リソースを指定して実行
先程はモジュール指定まででしたが、次はリソースまで指定する方法です。
リソースまで指定する場合は、モジュールの後ろにリソース名を追記したらOKです。
指定する対象のリソースが以下のような場合を考えます。
resource "aws_s3_bucket" "this" { bucket = "teshima-sample-bucket"
tags = { Name = "sample" }}
この場合、リソースを識別するためにthis
を指定していますので、以下のような指定でリソースまで指定可能です。
terraform plan -target=module.s3.aws_s3_bucket.thisterraform apply -target=module.s3.aws_s3_bucket.this
注意点
モジュール/リソースを指定して実行するため、terraformが全体の整合性を見てくれません。
このため、以下のようなwarningが出ますのでご注意ください。
エラーや、何らかのミスからの復旧とか出ない限り、-target
オプションは普段利用しないでね。って警告です。
│ 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.