如何使用CloudFormation加密Lambda变量及配置KMS密钥
Here's a complete AWS CloudFormation template that sets up a Lambda function with sensitive environment variables encrypted using a custom KMS key (you can also use the default AWS Lambda KMS key if preferred). This template includes all necessary IAM permissions and resource dependencies to secure your variables:
AWSTemplateFormatVersion: '2010-09-09' Description: Lambda function with encrypted sensitive environment variables using KMS Resources: # Custom KMS Key for encrypting Lambda environment variables LambdaEnvEncryptionKey: Type: AWS::KMS::Key Properties: Description: KMS key for encrypting Lambda sensitive environment variables KeyPolicy: Version: '2012-10-17' Id: lambda-env-key-policy Statement: - Sid: Allow root access Effect: Allow Principal: AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root' Action: 'kms:*' Resource: '*' - Sid: Allow Lambda execution role to use the key Effect: Allow Principal: AWS: !GetAtt LambdaExecutionRole.Arn Action: - 'kms:Encrypt' - 'kms:Decrypt' - 'kms:ReEncrypt*' - 'kms:GenerateDataKey*' - 'kms:DescribeKey' Resource: '*' # Lambda Execution Role with permissions for KMS and basic execution LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Policies: - PolicyName: LambdaKMSAccessPolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - 'kms:Encrypt' - 'kms:Decrypt' - 'kms:ReEncrypt*' - 'kms:GenerateDataKey*' - 'kms:DescribeKey' Resource: !Ref LambdaEnvEncryptionKey # Lambda Function with encrypted sensitive environment variables LambdaFunction: Type: AWS::Lambda::Function DependsOn: - LambdaExecutionRole - LambdaEnvEncryptionKey Properties: FunctionName: EncryptedEnvLambda Runtime: python3.9 Role: !GetAtt LambdaExecutionRole.Arn # Use custom KMS key for encrypting environment variables KmsKeyId: !Ref LambdaEnvEncryptionKey # To use the default AWS Lambda KMS key instead, replace above line with: # KmsKeyId: alias/aws/lambda Environment: Variables: key: AKIAJ6W7WERITYHYUHJGHN secret: PGDzQ8277Fg6+SbuTyqxfrtbskjnaslkchkY1 dest: !Ref dstBucket Code: ZipFile: | from __future__ import print_function import os import json def lambda_handler(event, context): # Access encrypted environment variables sensitive_key = os.environ['key'] sensitive_secret = os.environ['secret'] dest_bucket = os.environ['dest'] print(f"Destination bucket: {dest_bucket}") # Add your function logic here return { 'statusCode': 200, 'body': json.dumps('Function executed successfully') } # Optional: Destination bucket referenced in Lambda variables dstBucket: Type: AWS::S3::Bucket Properties: BucketName: !Sub 'lambda-dest-bucket-${AWS::AccountId}-${AWS::Region}'
Key Details:
- Custom KMS Key: The
LambdaEnvEncryptionKeyresource creates a customer-managed key that gives you full control over encryption/decryption permissions. The key policy explicitly allows the Lambda execution role to use the key for environment variable operations. - Lambda Execution Role: Grants Lambda permissions to write logs to CloudWatch and interact with the KMS key.
- Encrypted Environment Variables: The
KmsKeyIdproperty in the Lambda function specifies which KMS key to use for encrypting the variables at rest. If you prefer using the default AWS Lambda KMS key, swap theKmsKeyIdvalue withalias/aws/lambda.
Best Practice Note:
Hardcoding secrets directly in the template is not ideal for production. For better secret management, consider storing sensitive values in AWS Secrets Manager or AWS Systems Manager Parameter Store (both can use KMS encryption) and have your Lambda function retrieve them at runtime instead.
内容的提问来源于stack exchange,提问作者user9075162
相关产品推荐
相关产品推荐

