LoginSignup
22
11

More than 5 years have passed since last update.

TerraformでLambdaのScheduled Eventを使う

Posted at

AWSのLambdaをcronで定期的に実行する場合は、CloudWatchのScheduled Eventを使います。
それをTerraformを使って実現する場合は、下記のように記述します。

resource "aws_lambda_function" "output_report" {
    filename      = "output_report.zip"
    function_name = "outputReport"
    role          = "arn:aws:iam::XXXXXXXXXXXX:role/YYYYY"
    handler       = "index.handler"
}

resource "aws_cloudwatch_event_rule" "every_month" {
    name                = "every_month"
    description         = "Fires every month"
    schedule_expression = "cron(0 0 1 * ? *)"
}

resource "aws_cloudwatch_event_target" "output_report_every_month" {
    rule      = "${aws_cloudwatch_event_rule.every_month.name}"
    target_id = "output_report"
    arn       = "${aws_lambda_function.output_report.arn}"
}

resource "aws_lambda_permission" "allow_cloudwatch_to_call_output_report" {
    statement_id  = "AllowExecutionFromCloudWatch"
    action        = "lambda:InvokeFunction"
    function_name = "${aws_lambda_function.output_report.function_name}"
    principal     = "events.amazonaws.com"
    source_arn    = "${aws_cloudwatch_event_rule.every_month.arn}"
}

これで毎月1日0時(GMT)に、outputReportのLambdaが実行されます。

22
11
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
22
11