Skip to content

Instantly share code, notes, and snippets.

@sudharsans
Last active January 10, 2024 00:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sudharsans/cf9c52d7c78a81818a4a47872982bd76 to your computer and use it in GitHub Desktop.
Save sudharsans/cf9c52d7c78a81818a4a47872982bd76 to your computer and use it in GitHub Desktop.
Resource Policy for CloudWatch Logs with CloudFormation - Route53 query log
---
AWSTemplateFormatVersion: '2010-09-09'
Resources:
LambdaExecutionRole:
Type: "AWS::IAM::Role"
Properties:
RoleName: 'Enable-Role'
Path: "/"
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
RolePolicies:
Type: "AWS::IAM::ManagedPolicy"
Properties:
ManagedPolicyName: "LambdaExecutionRole-policy"
Roles:
- Ref: "LambdaExecutionRole"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- logs:PutResourcePolicy
- logs:DeleteResourcePolicy
Resource:
- "*"
Lambda:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.handler"
Role:
Fn::GetAtt:
- "LambdaExecutionRole"
- "Arn"
Code:
ZipFile: |
import json
import cfnresponse
import boto3
from botocore.exceptions import ClientError
client = boto3.client("logs")
def PutPolicy(arn,policyname):
response = client.put_resource_policy(
policyName=policyname,
policyDocument="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"route53.amazonaws.com\"},\"Action\":[\"logs:CreateLogStream\",\"logs:PutLogEvents\"],\"Resource\":\""+ arn + "\"}]}",
)
return
def DeletePolicy(policyname):
response = client.delete_resource_policy(
policyName=policyname
)
return
def handler(event, context):
CloudWatchLogsLogGroupArn = event['ResourceProperties']['CloudWatchLogsLogGroupArn']
PolicyName = event['ResourceProperties']['PolicyName']
responseData = {}
try:
if event['RequestType'] == "Delete":
DeletePolicy(PolicyName)
if event['RequestType'] == "Create":
PutPolicy(CloudWatchLogsLogGroupArn,PolicyName)
responseData['Data'] = "SUCCESS"
status=cfnresponse.SUCCESS
except ClientError as e:
responseData['Data'] = "FAILED"
status=cfnresponse.FAILED
print("Unexpected error: %s" % e)
cfnresponse.send(event, context, status, responseData, "CustomResourcePhysicalID")
Runtime: "python3.6"
import json
import cfnresponse
import boto3
from botocore.exceptions import ClientError
client = boto3.client("logs")
def PutPolicy(arn,policyname):
response = client.put_resource_policy(
policyName=policyname,
policyDocument="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"route53.amazonaws.com\"},\"Action\":[\"logs:CreateLogStream\",\"logs:PutLogEvents\"],\"Resource\":\""+ arn + "\"}]}",
)
return
def DeletePolicy(policyname):
response = client.delete_resource_policy(
policyName=policyname
)
return
def handler(event, context):
CloudWatchLogsLogGroupArn = event['ResourceProperties']['CloudWatchLogsLogGroupArn']
PolicyName = event['ResourceProperties']['PolicyName']
responseData = {}
try:
if event['RequestType'] == "Delete":
DeletePolicy(PolicyName)
if event['RequestType'] == "Create":
PutPolicy(CloudWatchLogsLogGroupArn,PolicyName)
responseData['Data'] = "SUCCESS"
status=cfnresponse.SUCCESS
except ClientError as e:
responseData['Data'] = "FAILED"
status=cfnresponse.FAILED
print("Unexpected error: %s" % e)
cfnresponse.send(event, context, status, responseData, "CustomResourcePhysicalID")
---
AWSTemplateFormatVersion: '2010-09-09'
Resources:
LogGroup:
Type: "AWS::Logs::LogGroup"
Properties:
RetentionInDays: 7
DNS:
DependsOn: AddResourcePolicy
Type: "AWS::Route53::HostedZone"
Properties:
HostedZoneConfig:
Comment: "My hosted zone for example.com"
Name: "google.com"
QueryLoggingConfig:
CloudWatchLogsLogGroupArn: !GetAtt LogGroup.Arn
AddResourcePolicy:
Type: Custom::AddResourcePolicy
Version: '1.0'
Properties:
ServiceToken: arn:aws:lambda:us-east-1:8xxxxx965194:function:test-lambda-deploy-Lambda-15R963QKCI80A
CloudWatchLogsLogGroupArn: !GetAtt LogGroup.Arn
PolicyName: "testpolicy"
@ewismer
Copy link

ewismer commented Jul 15, 2021

Hi, thanks! This is useful.

Do you have any tips for creating the policy to be passed to the custom resource? My use case is that I don't have access to create resources in higher environments for my application besides thru cloudformation, so I can't create the policy via the command line.

I tried creating the policy via Cloudformation, but it requires a Role, User, or Group to be specified during creation and may not allow specifying a principal in the policy (which in my case will be "es.amazonaws.com" since I am creating groups for publish elasticsearch logs).

Do you have any ideas on how I can accomplish this in cloudformation?

Edit: I guess it could be done with another custom resource, i will have to look into that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment