5
4

More than 1 year has passed since last update.

[AWS][Terraform]Iot ruleをLambdaのトリガーに設定する方法

Last updated at Posted at 2023-01-11

はじめに

  • 最近業務でTerraformを使ってLambdaのトリガーにIot ruleを追加する機会があったので、設定方法を備忘録として残しておきます。
  • バージョン
    • Terraform:1.3.5
    • aws provider:4.49.0

やりたいこと

  • TerraformでLambdaのトリガーにIot ruleを追加したい
    ※マネジメントコンソールから追加する場合は下記のようにLambda設定画面から「トリガーを追加」をクリックし、「AWS Iot」を選択し、「Rule」のARNを入力すればOK
    image.png

ハマったこと

以下のIot ruleリソースを作成するTerraformコードを作成し、lambdaブロックのfunction_arnに対象Lambdaを記述したのですが、terraform apply後、Lambdaのコンソールで確認したら該当トリガーが追加されませんでした。

resource "aws_iot_topic_rule" "sample_iot_topic_rule" {
  name        = var.sample_iot_topic_rule.name
  enabled     = true
  sql         = "SELECT * FROM '${var.sample_iot_topic_rule.topic}'"
  sql_version = "2016-03-23"

  lambda {
    function_arn = aws_lambda_function.test_lambda.arn
  }
}

原因

aws_lambda_permissionリソースも記述しないといけないので、aws_iot_topic_ruleリソースのlambdaブロックにfunction_arnを記述するだけではダメでした。
しかし、aws_lambda_permissionが記述されていなくてもterraform applyが通ってしまうので、少しややこしかったですね。

以下、Terraform公式ドキュメントからの引用

To give an external source (like an EventBridge Rule, SNS, or S3) permission to access the Lambda function, use the aws_lambda_permission resource. See Lambda Permission Model for more details. On the other hand, the role argument of this resource is the function's execution role for identity and access to AWS services and resources.

EventBridge RuleやSNSなどと同様に、Iot ruleをLambdaのトリガーに追加する際もaws_lambda_permissionを記述する必要がありました。

修正後のコード

resource "aws_iot_topic_rule" "sample_iot_topic_rule" {
  name        = var.sample_iot_topic_rule.name
  enabled     = true
  sql         = "SELECT * FROM '${var.sample_iot_topic_rule.topic}'"
  sql_version = "2016-03-23"

  lambda {
    function_arn = aws_lambda_function.test_lambda.arn
  }
}

resource "aws_lambda_permission" "sample_iot_topic_rule_permission" {
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.test_lambda.function_name
  principal     = "iot.amazonaws.com"
  source_arn    = aws_iot_topic_rule.sample_iot_topic_rule.arn
}

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4