Open4

【Terraform】循環参照を解決する

not75743not75743

コード

循環参照するコード
data "archive_file" "example_zip" {
  type        = "zip"
  source_dir  = "${path.module}/lambda_function"
  output_path = "${path.module}/example_lambda.zip"
}

resource "aws_lambda_function" "example_lambda" {
  function_name    = "example-lambda"
  handler          = "main.handler"
  runtime          = "python3.10"
  filename         = data.archive_file.example_zip.output_path
  source_code_hash = filebase64sha256(data.archive_file.example_zip.output_path)
  role = aws_iam_role.lambda_role.arn
}

resource "aws_iam_role" "lambda_role" {
  name = "example-lambda-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
  managed_policy_arns = [
    aws_iam_policy.log_policy.arn,
  ]
}

resource "aws_iam_policy" "log_policy" {
  name        = "example-lambda-policy"
  description = "IAM policy for the example Lambda function"

  policy = jsonencode({
    Version   = "2012-10-17"
    Statement = [
      {
        Effect   = "Allow"
        Action   = [
          "logs:CreateLogGroup",
          "logs:CreateLogStream",
          "logs:PutLogEvents"
        ]
        Resource = [
          "arn:aws:logs:*:*:log-group:/aws/lambda/${aws_lambda_function.example_lambda.function_name}:*"
        ]
      }
    ]
  })
}

resource "aws_cloudwatch_log_group" "example_log_group" {
  name = "/aws/lambda/${aws_lambda_function.example_lambda.function_name}"
  retention_in_days = 30
}

エラーログ

│ Error: Cycle: aws_lambda_function.example_lambda, aws_iam_policy.log_policy, aws_iam_role.lambda_role
not75743not75743

依存関係

  • aws_lambda_function.example_lambdaaws_iam_role.lambda_roleのARNを必要とする
  • aws_iam_role.lambda_roleaws_iam_policy.log_policyのARNを必要とする
  • aws_iam_policy.log_policyaws_lambda_function.example_lambdaのfunction_nameを必要とする

図解

not75743not75743

解決方法

いずれかの依存を解消してあげればよいです。
例えば以下のようにLambda関数名を直接入力すれば本事象は解決します。(良い悪いは置いておいて)

        Resource = [
-          "arn:aws:logs:*:*:log-group:/aws/lambda/${aws_lambda_function.example_lambda.function_name}:*"
+          "arn:aws:logs:*:*:log-group:/aws/lambda/example-lambda:*"
        ]

ドキュメントではaws_security_group_ruleを追加することで、
セキュリティグループ同士の依存関係をなくしています。(aws_security_group_rule経由としている)
https://developer.hashicorp.com/terraform/tutorials/configuration-language/troubleshooting-workflow#correct-a-cycle-error