プログラミング学習サイト

プログラミングの学習を開始される方を対象としたプログラミング入門サイトです。

depends_on構文 【Terraform】

参考 : https://developer.hashicorp.com/terraform/language/meta-arguments/depends_on

The depends_on 構文

depends_on 構文を使用して、Terraformが自動的に推測できない暗黙的なリソースまたはモジュールの依存関係を処理します。 例えば、リソースまたはモジュールが別のリソースの動作に依存しているが、 引数でそのリソースのデータアクセス以外場合にのみ、依存関係を明示的に指定する必要があります。

注:depends_onのモジュールサポートはTerraformバージョン0.13に追加され、以前のバージョンはリソースでのみ使用できます。

depends_on構文は最後の手段

depends_on構文は、依存関係を宣言するオブジェクト上でアクションを実行する前に、依存関係オブジェクト上のすべてのアクション(読み取りアクションを含む)を完了するようにTerraformに指示します。 依存関係オブジェクトがモジュール全体である場合、依存関係は、Terraformがそのモジュールに関連するすべてのリソースとデータソースを処理する順序に影響します。詳細については、リソースの依存関係とデータリソース依存関係を参照してください。

depens_onは次の理由で最後の手段として使用する必要があります。

  • リソース間の依存関係が複雑になりやすく、コードの可読性が低下します。依存関係が多岐にわたると、問題が発生した場合にデバッグが困難になります。
  • Terraformはリソースの依存関係を解析し、自動的に適切な順序でリソースを作成・更新しますが、depends_on を使用することでこれが制限され、実行計画が非効率になる可能性があります。

depends_onの代わりに、可能な場合は式参照を使用して依存関係を暗示することをお勧めします。

使用例

リソースタイプに関係なく、モジュールブロックおよびすべてのリソースブロックでdepens_on構文を使用できます。

ちなみに、depends_onを使用する必要がある理由を説明するコメントを常に含めることをお勧めします。

resource "aws_iam_role" "example" {
  name = "example"

  # assume_role_policy is omitted for brevity in this example. Refer to the
  # documentation for aws_iam_role for a complete example.
  assume_role_policy = "..."
}

resource "aws_iam_instance_profile" "example" {
  # Because this expression refers to the role, Terraform can infer
  # automatically that the role must be created first.
  role = aws_iam_role.example.name
}

resource "aws_iam_role_policy" "example" {
  name   = "example"
  role   = aws_iam_role.example.name
  policy = jsonencode({
    "Statement" = [{
      # This policy allows software running on the EC2 instance to
      # access the S3 API.
      "Action" = "s3:*",
      "Effect" = "Allow",
    }],
  })
}

resource "aws_instance" "example" {
  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"

  # Terraform can infer from this that the instance profile must
  # be created before the EC2 instance.
  iam_instance_profile = aws_iam_instance_profile.example

  # However, if software running in this EC2 instance needs access
  # to the S3 API in order to boot properly, there is also a "hidden"
  # dependency on the aws_iam_role_policy that Terraform cannot
  # automatically infer, so it must be declared explicitly:
  depends_on = [
    aws_iam_role_policy.example
  ]
}

https://developer.hashicorp.com/terraform/language/meta-arguments/depends_on

page:https://minegishirei.hatenablog.com/entry/2024/06/11/141412