2

我想配置會在特定日期/時間與以下觸發lambda函數CloudWatch的規則:AWS terraform CloudWatch的規則爲lambda觸發

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}" 
} 

然而lambda函數不運行。如果我查看lambda並檢查觸發器選項卡,那裏沒有任何內容。如果我查看cloudwatch規則並查看目標下的lambda函數,則會顯示出來,如果我點擊它,則會重定向到函數本身。任何想法可能在這裏錯了嗎?

對於我點擊編輯 - >保存 - >配置詳細信息 - >更新而不更改任何內容的一個cloudwatch規則,現在顯示在lambda的觸發器選項卡下,但仍需要讓其他人無法工作W/O這一步,

回答

6

無論何時不同的AWS服務交互,都需要使用AWS IAM授予他們必要的訪問權限。

在這種情況下,Cloudwatch Events必須有權執行相關的Lambda函數。

the AWS tutorial的第2步描述瞭如何使用AWS CLI執行此操作。所述Terraform當量aws lambda add-permission命令的是the aws_lambda_permission resource,其可以與結構例從問題如下使用:

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權限是在IAM的角色和策略的抽象。有關IAM角色和策略的一些常規背景信息,請參閱需要更多手動配置的my longer answer to another question