ライフサイクル制御

Terraform の lifecycle ブロックは、再作成でダウンタイムを避けたい、重要なリソースを誤削除から守りたい、特定の属性変更を Terraform の管理対象から外したい、といった要望に応えるための仕組みです。ここでは代表的な設定である create_before_destroy / prevent_destroy / ignore_changes の書き方と、使う場面を順に見ていきます。

1. 記載方法

1.1 ライフサイクルとは

ここまで、リソースの作成や依存関係について学んできました。通常、Terraformは設定ファイルの記述通りにリソースを「作成」したり、変更があれば「更新(または削除して再作成)」したりします。

しかし、運用していると以下のような要望が出てくることがあります。

  • 設定を変更したけど、リソースを作り直す時にダウンタイム(停止時間)を発生させたくない
  • 大事なデータベースだから、間違っても削除されないように保護したい
  • この設定値だけは、Terraformで管理せず、AWS側の自動変更に任せたい

こうしたリソースごとの「振る舞い」を細かく制御するために使うのが、lifecycle ブロックです。

1.2 create_before_destroy(削除する前に作成)

通常、リソースの再作成が必要な変更(例:EC2のAMI変更など)が発生した場合、Terraformは「古いものを削除」してから「新しいものを作成」します。これでは、リソースが存在しない時間ができてしまいます。

create_before_destroy = true を設定すると、「新しいものを作成」してから「古いものを削除」する動きに変わり、ダウンタイムを最小限に抑えられます。

記載方法としては、lifecycle のブロックの中に、create_before_destroy = true とすることで実現できます。

  lifecycle {
    create_before_destroy = true
  }

実際のサンプルコードを確認します。下記は、web_sg というセキュリティグループについて、「削除する前に再作成」を行う流れとなります。セキュリティグループは、名前を変更した場合、セキュリティグループが再作成されます。create_before_destroy を指定していないと、他のリソースに紐づいている時に挙動がおかしくなるため、create_before_destroy = true が有効になります。

resource "aws_security_group" "web_sg" {
  name        = "web-sg-v1"
  description = "Allow HTTP traffic"

  # インバウンドルールの定義
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  # ライフサイクル設定
  lifecycle {
    # 置換が必要な変更(nameの変更など)があった場合、
    # 新しいセキュリティグループを作成してから、古いものを削除する
    create_before_destroy = true
  }
}

1.3 prevent_destroy(削除の防止)

prevent_destroy = true を設定すると、そのリソースを削除しようとする操作(terraform destroy など)が実行されたときにエラーとなり、削除をブロックします。

本番環境のデータベースやストレージなど、絶対に消えてはいけないリソースを守るために使用します。

記載方法としては、lifecycle のブロックの中に、prevent_destroy = true とすることで実現できます。

  lifecycle {
    prevent_destroy = true
  }

以下のサンプルコードは、RDSに対して、prevent_destroy = true を指定することで、RDSを terraform destroy などで削除しようとすると、エラーとなります。

resource "aws_db_instance" "production_db" {
  allocated_storage    = 20
  engine               = "mysql"
  engine_version       = "8.0"
  instance_class       = "db.t3.micro"
  username             = "admin"
  password             = "password12345678" # 実際はSecrets Manager等での管理を推奨
  skip_final_snapshot  = true

  tags = {
    Name = "Production-DB"
  }

  # ライフサイクル設定
  lifecycle {
    # このRDSを削除しようとする操作(destroy)をブロックしてエラーにする
    prevent_destroy = true
  }
}

1.4 ignore_changes(変更の無視)

Terraformはコードと実際の環境の差異(差分)を検知して修正しようとします。しかし、Terraform以外の要因で変更された値を元に戻したくない場合があります。

ignore_changes を使うと、指定した属性の変更をTerraformが無視(スルー)するようになります。

以下のように、lifecycle ブロックの中に ignore_changes = [ 属性名 ] を定義することで設定できます。

lifecycle {
  ignore_changes = [
    属性名
  ]
}

実際の書き方を見てみましょう。

下記のサンプルでは、パラメータストアの作成時に、値としてダミーの値を設定しています。ignore_changes を設定することで、マネジメントコンソールで値を変更した場合でも、その変更がTerraformによって上書きされなくなります。ignore_changes を設定していないと、画面から変更してもダミーの値に戻されてしまいます。

resource "aws_ssm_parameter" "db_password" {
  name  = "/production/database/password"
  type  = "SecureString"
  value = "dummy_initial_value"

  lifecycle {
    # value の変更を無視する
    # 運用中にパスワードを変更しても、Terraformが "dummy_initial_value" に戻さないようにする
    ignore_changes = [
      value,
    ]
  }
}

2. 実際に使ってみる

実際に、ライフサイクルを使った操作を行ってみます。

2.1 create_before_destroy

まずは、リソースの削除順序をコントロールする create_before_destroy から確認します。

少し長くなってしまいますが、以下のコードを main.tf に貼り付けてみてください。

provider "aws" {
 region = "ap-northeast-1"
}

# VPC
resource "aws_vpc" "vpc" {
 cidr_block = "10.0.0.0/16"
 tags = {
   Name = "test-vpc"
 }
}

# サブネット
resource "aws_subnet" "subnet" {
 vpc_id     = aws_vpc.vpc.id
 cidr_block = "10.0.1.0/24"
 tags = {
   Name = "test-subnet"
 }
}

# セキュリティグループ
resource "aws_security_group" "web_sg" {
 name        = "web-sg-v1"
 description = "Allow HTTP traffic"
  vpc_id      = aws_vpc.vpc.id

 ingress {
   from_port   = 80
   to_port     = 80
   protocol    = "tcp"
   cidr_blocks = ["0.0.0.0/0"]
 }
  egress {
   from_port   = 0
   to_port     = 0
   protocol    = "-1"
   cidr_blocks = ["0.0.0.0/0"]
 }
}

# EC2インスタンスを作成してセキュリティグループを割り当て
resource "aws_instance" "web_server" {
 ami           = "ami-03d1820163e6b9f5d"
 instance_type = "t3.micro"
 subnet_id     = aws_subnet.subnet.id
 vpc_security_group_ids = [aws_security_group.web_sg.id]
 tags = {
   Name = "test-ec2-instance"
 }
}

これは、テスト用のセキュリティグループを作り、EC2インスタンスに割り当てしています。関連するVPCやサブネットも一緒に作っています。

これを実行すると、web_server のEC2インスタンスに、web_sg のセキュリティグループが割り当てられます。

この状態で、セキュリティグループの名前を変更すると、AWSの仕様上、セキュリティグループの作り直しがされます。しかし、セキュリティグループはすでにEC2インスタンスに割り当てられているため、削除ができずエラーになります。そのため、create_before_destroy の設定が有効になってきます。

以下のコマンドで、Terraform がインストールされていることを確認します。

terraform --version

以下のように Terraform のバージョンが表示されれば、インストールは確認できています。

Terraform vX.X.X
on darwin_arm64

バージョンが表示されない場合は、Terraformのインストール を先に実施してください。

インストールが確認できたら、まず create_before_destroy が割り当てられていない状態で、terraform apply コマンドで関連リソースを作成します。

terraform apply
⚠️ 「InvalidAMIID.NotFound」エラーが出る場合
サンプルコードのAMI ID(ami-03d1820163e6b9f5d)は例示用のため、実際には存在しない可能性があります。
AWSコンソールでEC2の「AMI カタログ」から、現在利用可能なAmazon Linux 2023のAMI IDを確認し、置き換えてください。

terraform apply が正常終了したら、セキュリティグループの名前を変えてみます。web_sg の name 属性を、web-sg-v2 に変更してみます。

resource "aws_security_group" "web_sg" {
 name        = "web-sg-v2"  # ここを変更
 description = "Allow HTTP traffic"
  vpc_id      = aws_vpc.vpc.id

 ingress {
   from_port   = 80
   to_port     = 80
   protocol    = "tcp"
   cidr_blocks = ["0.0.0.0/0"]
 }
  egress {
   from_port   = 0
   to_port     = 0
   protocol    = "-1"
   cidr_blocks = ["0.0.0.0/0"]
 }
}

この状態で、まずは terraform plan を実行してみます。

terraform plan

以下のように二つの変更が読み取れます。

一つは、web-sg-v1 から web-sg-v2 に変更されることにより、セキュリティグループを削除して再作成されます。もう一つは、それに伴いEC2インスタンス(web_server)に割り当てられているセキュリティグループが、新しく作成されたものに更新されます。

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_instance.web_server will be updated in-place
  ~ resource "aws_instance" "web_server" {
        id                                   = "i-0e40109f4b7d2ba95"
        tags                                 = {
            "Name" = "test-ec2-instance"
        }
      ~ vpc_security_group_ids               = [
          - "sg-08456a9ffe5662ef6",
        ] -> (known after apply)
        # (39 unchanged attributes hidden)

        # (9 unchanged blocks hidden)
    }

  # aws_security_group.web_sg must be replaced
-/+ resource "aws_security_group" "web_sg" {
      ~ arn                    = "arn:aws:ec2:ap-northeast-1:125605020607:security-group/sg-08456a9ffe5662ef6" -> (known after apply)
      ~ id                     = "sg-08456a9ffe5662ef6" -> (known after apply)
      ~ name                   = "web-sg-v1" -> "web-sg-v2" # forces replacement
      + name_prefix            = (known after apply)
      ~ owner_id               = "125605020607" -> (known after apply)
      - tags                   = {} -> null
      ~ tags_all               = {} -> (known after apply)
        # (6 unchanged attributes hidden)
    }

この後 terraform apply を実行すると以下のようなエラーが発生します。ただ、実際にエラーが発生するまで数分〜10分ほど待機(あるいは即時エラー)になってしまうため、実際に試す必要はありません。

このエラーは、「削除しようとしているセキュリティグループがEC2インスタンスで利用されているため、削除できない」というものです。

│ Error: deleting Security Group (sg-08456a9ffe5662ef6): operation error EC2: DeleteSecurityGroup, https response error StatusCode: 400, RequestID: 14d75afa-4207-4bbd-a092-3bf48d2fabc2, api error DependencyViolation: resource sg-08456a9ffe5662ef6 has a dependent object

そのため、今回のような create_before_destroy の設定が有効になります。web_sg に以下のように、lifecycle の記載をお願いします。

# セキュリティグループ
resource "aws_security_group" "web_sg" {
  name        = "web-sg-v2"
  description = "Allow HTTP traffic"

  vpc_id      = aws_vpc.vpc.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }


  # ここを追記
  lifecycle {
    create_before_destroy = true
  }
}
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place
+/- create replacement and then destroy

Terraform will perform the following actions:

  # aws_instance.web_server will be updated in-place
  ~ resource "aws_instance" "web_server" {
        id                                   = "i-0e40109f4b7d2ba95"
        tags                                 = {
            "Name" = "test-ec2-instance"
        }
      ~ vpc_security_group_ids               = [
          - "sg-08456a9ffe5662ef6",
        ] -> (known after apply)
        # (39 unchanged attributes hidden)

        # (9 unchanged blocks hidden)
    }

  # aws_security_group.web_sg must be replaced
+/- resource "aws_security_group" "web_sg" {
      ~ arn                    = "arn:aws:ec2:ap-northeast-1:125605020607:security-group/sg-08456a9ffe5662ef6" -> (known after apply)
      ~ id                     = "sg-08456a9ffe5662ef6" -> (known after apply)
      ~ name                   = "web-sg-v1" -> "web-sg-v2" # forces replacement
      + name_prefix            = (known after apply)
      ~ owner_id               = "125605020607" -> (known after apply)
      - tags                   = {} -> null
      ~ tags_all               = {} -> (known after apply)
        # (6 unchanged attributes hidden)
    }

Plan: 1 to add, 1 to change, 1 to destroy.

今回のログでは、aws_security_group.web_sg の行頭が +/- になっています。 これは Terraform が「新しいセキュリティグループ(v2)を作成し、EC2インスタンスへの紐付けを新しい方に切り替えてから、古いセキュリティグループ(v1)を削除する」という手順を計画していることを表しており、意図通り設定が効いています。

Apply complete! Resources: 1 added, 1 changed, 1 destroyed.

最後に、作成したリソースは削除しておきましょう

terraform destroy

2.2 prevent_destroy

リソースの削除保護を行う prevent_destroy を試してみます。下記のような、シンプルなS3バケットを作り、削除保護を行うコードを、main.tf に記載してください。

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_s3_bucket" "example" {
  # ★重要: 世界中で一意なバケット名に書き換えてください
  bucket = "my-unique-bucket-name-20260101"

  tags = {
    Name = "Protected Bucket"
  }

  # --- 削除保護設定 ---
  lifecycle {
    # trueの場合、terraform destroy コマンドを実行してもエラーになり、
    # リソースが削除されるのを防ぎます。
    prevent_destroy = true
  }
}

terraform apply コマンドにより、まずはリソースを作成します。

terraform apply
⚠️ 「BucketAlreadyExists」エラーが出る場合
S3バケット名は全世界で一意である必要があります。
my-unique-bucket-name-20260101の部分を、日付やランダムな文字列を追加して一意な名前に変更してください。

正常終了することを確認します。

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

terraform destroy コマンドを実行して、リソースの削除を行ってみます。

terraform destroy

そうすると、以下のようなエラーが発生します。

│ Error: Instance cannot be destroyed
│
│   on main.tf line 5:
│    5: resource "aws_s3_bucket" "example" {
│
│ Resource aws_s3_bucket.example has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. To avoid this error and continue with
│ the plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using the -target option.

このエラーは、lifecycle.prevent_destroy set の部分から、リソースに対して削除保護が働いていることが読み取れます。そのため、期待通りの動作です。

このリソースを削除したい場合は、lifecycle ブロックの部分をまず削除します。

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_s3_bucket" "example" {
  # ★重要: 世界中で一意なバケット名に書き換えてください
  bucket = "my-unique-bucket-name-20260101"

  tags = {
    Name = "Protected Bucket"
  }
}

コードから lifecycle ブロックを削除した時点で、Terraform上の削除保護設定は解除されます(この設定はコード上だけのルールなので、設定変更を反映させるための terraform apply は不要です)。

その上で、terraform destroy コマンドでリソースの削除を行います。

terraform destroy

無事にコマンドが正常終了すれば、ここまではOKです。

Destroy complete! Resources: 1 destroyed.

2.3 ignore_changes

最後に、リソースの変更検知から特定の項目を除外する ignore_changes の動作を確認します。

今回は「データベースのパスワード管理」を想定したシナリオで進めます。 通常、Terraformでパスワードリソースを作ると、コードに書かれた値とAWS上の値が常に一致するように管理されます。しかし、運用中に管理者がAWSコンソールからパスワードを変更した場合、次回の terraform apply でコードに書かれた古いパスワード(ダミー値)に戻されてしまうと事故になります。

そこで、「作成時はダミー値を入れるが、その後の値の変更はTerraformで関知しない(無視する)」という設定を行います。

まずは通常通り、ライフサイクル設定を行わずにパラメータストア(パスワード保存場所)を作成します。 main.tf を以下の内容に書き換えてください。

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_ssm_parameter" "db_password" {
  name  = "/production/database/password"
  type  = "SecureString"
  value = "dummy"

}

まずはこれを作成します。

terraform apply
⚠️ 「AccessDeniedException」エラーが出る場合
IAMユーザにssm:PutParameterの権限がありません。
IAMコンソールで、使用しているユーザにAmazonSSMFullAccessポリシーをアタッチするか、Systems Manager Parameter Storeへの書き込み権限を追加してください。

続いて、パラメータストアのダッシュボードを開き、今作成した /production/database/password のリンクを開きます。

すると、値の部分に dummy という内容が設定されています。

これについて、画面上で「編集」をクリックし、値を任意の内容に変えてください。

この状態で、一度 terraform plan を実行してみます。

$ terraform plan
aws_ssm_parameter.db_password: Refreshing state... [id=/production/database/password]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # aws_ssm_parameter.db_password will be updated in-place
  ~ resource "aws_ssm_parameter" "db_password" {
        id              = "/production/database/password"
        name            = "/production/database/password"
        tags            = {}
      ~ value           = (sensitive value)
      ~ version         = 2 -> (known after apply)
        # (10 unchanged attributes hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

すると、パスワードが変更されるという結果になります。なお、パラメータストアの実際の値は、セキュリティのため表示されず、(sensitive value) とマスキングされます。

続けて、下記のように lifecycle ブロックを指定してみます。

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_ssm_parameter" "db_password" {
  name  = "/production/database/password"
  type  = "SecureString"
  value = "dummy"

  lifecycle {
    ignore_changes = [
      value,
    ]
  }
}

この状態で、再び terraform plan を実行すると、今度は結果が No changes となります。これにより、無事に変更検知の対象外となったことが読み取れます。

No changes. Your infrastructure matches the configuration.

最後に、作成したリソースを削除しておきましょう。

terraform destroy