简体   繁体   中英

aws terraform cloudwatch rule as lambda trigger

I'm trying to configure cloudwatch rules that'll trigger lambda functions on a specific day/time with the following:

resource "aws_lambda_function" "cleanup_daily" {
  filename          = "name"
  function_name     = "name"
  role              = "arn<removed>"
  handler           = "snapshotcleanup.lambda_handler"
  source_code_hash  = "${base64sha256(file("file_name"))}"
  runtime           = "python2.7"
  timeout           = "20"
  description       = "desc"
}

resource "aws_cloudwatch_event_rule" "daily_rule" {
  name                = "name"
  description         = "desc"
  schedule_expression = "cron(....)"
}

resource "aws_cloudwatch_event_target" "daily_target" {
  rule  = "${aws_cloudwatch_event_rule.daily_rule.name}"
  arn   = "${aws_lambda_function.cleanup_daily.arn}"
}

However the lambda functions do not run. If I look at lambda and check the triggers tab, there's nothing there. If I look at the cloudwatch rules and look under Targets, the lambda function shows up and if I click on it I'm redirected to the function itself. Any ideas what might wrong here?

For one of the cloudwatch rules I clicked on edit -> save -> configure details -> update without changing anything and that now shows up under the trigger tab in lambda but still need to get the others to work w/o this step,

Whenever distinct AWS services interact it is necessary to grant them the necessary access permissions using AWS IAM.

In this case, it's necessary for Cloudwatch Events to have access to execute the Lambda function in question.

Step 2 of the AWS tutorial describes how to do this using the AWS CLI. The Terraform equivalent of the aws lambda add-permission command is the aws_lambda_permission resource , which can be used with the configuration example from the question as follows:

data "aws_caller_identity" "current" {
  # Retrieves information about the AWS account corresponding to the
  # access key being used to run Terraform, which we need to populate
  # the "source_account" on the permission resource.
}

resource "aws_lambda_permission" "allow_cloudwatch" {
  statement_id   = "AllowExecutionFromCloudWatch"
  action         = "lambda:InvokeFunction"
  function_name  = "${aws_lambda_function.cleanup_daily.function_name}"
  principal      = "events.amazonaws.com"
  source_account = "${data.aws_caller_identity.current.account_id}"
  source_arn     = "${aws_cloudwatch_event-rule.daily_rule.arn}"
}

AWS Lambda permissions are an abstraction over IAM roles and policies. For some general background information on IAM roles and policies, see my longer answer to another question where more manual configuration was required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM