First of all: Log group data is always encrypted in Amazon CloudWatch Logs. By default, CloudWatch Logs uses server-side encryption for the log data at rest.
However, sometimes it is necessary - for example, because of compliance guidelines - to encrypt the logs with a customer managed key. No problem, you can use AWS Key Management Service (AWS KMS) for this encryption.
But how does this work with automatically created log groups by AWS services, like AWS Lambda? In this blog post, I want to show you what steps are necessary to do this.
Enough introduction, let's get to the code.
My code examples are written in TypeScript. I use the AWS Cloud Development Kit (CDK), which allows you to define your cloud infrastructure as code in any of the supported programming languages.
AWS KMS
I use the AWS KMS Construct to define a new KMS key:
const kmsKey = new aws_kms.Key(this, 'KmsKey');
Now I grant the CloudWatch Logs service encryption and decryption rights for my region using this KMS key:
kmsKey.grantEncryptDecrypt(
new aws_iam.ServicePrincipal(`logs.${this.region}.amazonaws.com`)
);
This was the necessary configuration for AWS KMS. The key can now be used.
AWS Lambda
AWS Lambda automatically creates a log group if it does not already exist. Unfortunately, the log group cannot really be configured using the AWS Lambda Construct. With one small exception: The logRetention
can be specified.
For completeness, I create a Lambda function where the log group is to be encrypted with a KMS key:
const lambdaFn = new aws_lambda_nodejs.NodejsFunction(this, 'LambdaFn', {
entry: '/path/to/my/file.ts'
});
Now I create a new log group using the AWS LogGroup Construct:
new aws_logs.LogGroup(this, 'LambdaLogGroup', {
encryptionKey: kmsKey,
logGroupName: `/aws/lambda/${lambdaFn.functionName}`
});
⚠️ With the encryptionKey
property I define which KMS key should be used to encrypt the log group. The important step is the logGroupName
property. By default, the log group of the Lambda function is created with the prefix /aws/lambda/
, followed by the function name. Naming the log group according to this naming scheme ensures that the Lambda function uses it.
Of course, you can also define the retention (retention
) or removal policy (removalPolicy
) for the log group.
Ready! The log group of the Lambda function is now encrypted with the KMS key.
If you have any kind of feedback, suggestions or ideas - feel free to comment this post!
Top comments (0)