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

时间:2018-03-12 18:20:08

标签: amazon-web-services amazon-cloudformation amazon-cloudwatchlogs

当我使用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 ???

1 个答案:

答案 0 :(得分:3)

  

您无法使用CloudWatch控制台创建或编辑资源政策。您必须使用CloudWatch API,其中一个AWS软件开发工具包或   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
     .....