如何使用 CloudFormation 为 CloudWatch Logs 定义资源策略?

How to define Resource Policy for CloudWatch Logs with CloudFormation?

当我使用 Route53 配置 DNS 查询日志记录时,我可以为 Route53 创建资源策略以记录到我的日志组。我可以使用 cli aws logs describe-resource-policies 确认此政策并看到类似以下内容:

{
  "resourcePolicies": [
    {
        "policyName": "test-logging-policy", 
        "policyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"route53.amazonaws.com\"},\"Action\":[\"logs:CreateLogStream\",\"logs:PutLogEvents\"],\"Resource\":\"arn:aws:logs:us-east-1:xxxxxx:log-group:test-route53*\"}]}", 
        "lastUpdatedTime": 1520865407511
    }
  ]
}

cli 也有一个 put-resource-policy 来创建其中之一。我还看到 Terraform 有一个资源 aws_cloudwatch_log_resource_policy 做同样的事情。

所以问题是:如何使用 CloudFormation 执行此操作???

You can't use the CloudWatch console to create or edit a resource policy. You must use the CloudWatch API, one of the AWS SDKs, or the AWS CLI.

Cloudformation 目前不支持创建资源策略,但您可以创建自定义 lambda 资源来执行此操作。

https://gist.github.com/sudharsans/cf9c52d7c78a81818a4a47872982bd76

CloudFormation 自定义资源:

  AddResourcePolicy:
    Type: Custom::AddResourcePolicy
    Version: '1.0'
    Properties:
      ServiceToken: arn:aws:lambda:us-east-1:872673965194:function:test-lambda-deploy-Lambda-15R963QKCI80A
      CloudWatchLogsLogGroupArn: !GetAtt LogGroup.Arn
      PolicyName: "testpolicy"

拉姆达:

import cfnresponse
import boto3
def PutPolicy(arn,policyname):
    response = client.put_resource_policy(
      policyName=policyname,
      policyDocument="....",
    )
    return

def handler(event, context):
    ......
        if event['RequestType'] == "Delete":
            DeletePolicy(PolicyName)
        if event['RequestType'] == "Create":
            PutPolicy(CloudWatchLogsLogGroupArn,PolicyName)
        responseData['Data'] = "SUCCESS"
        status=cfnresponse.SUCCESS
     .....

4 年过去了,这似乎仍然无法通过 Cloudformation 发挥作用,尽管现在显然已经包含对此的支持