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が実行されます。