Last active
September 22, 2022 09:33
-
-
Save ritesh/e75aed153008f4a4288a083510ff9d61 to your computer and use it in GitHub Desktop.
lib/aws-lambda-to-secrets-manager-in-private-subnet-stack.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as cdk from 'aws-cdk-lib'; | |
import { Construct } from 'constructs'; | |
import { aws_ec2 as ec2 } from 'aws-cdk-lib'; | |
import { PythonFunction } from "@aws-cdk/aws-lambda-python-alpha"; | |
import { Runtime } from 'aws-cdk-lib/aws-lambda'; | |
import { Effect, PolicyStatement } from 'aws-cdk-lib/aws-iam'; | |
import { Stack, StackProps, Duration } from 'aws-cdk-lib'; | |
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager'; | |
export class AwsLambdaPrivSubnetStack extends cdk.Stack { | |
constructor(scope: Construct, id: string, props?: cdk.StackProps) { | |
super(scope, id, props); | |
const privateLambdaVPC = new ec2.Vpc(this, "PrivateLambdaVPC", { | |
vpcName: "PrivateLambdaVPC", | |
subnetConfiguration: [ | |
{ | |
name: 'Isolated', | |
subnetType: ec2.SubnetType.PRIVATE_ISOLATED, | |
} | |
] | |
}); | |
const lambdaSecurityGroup = new ec2.SecurityGroup(this, 'PrivateLambdaSG', { | |
securityGroupName: 'PrivateLambdaSG', | |
vpc: privateLambdaVPC | |
}); | |
const secretsManagerEndpointSecurityGroup = new ec2.SecurityGroup(this, 'SecretsManagerEndpointSG', { | |
securityGroupName: 'SecretsManagerEndpointSG', | |
vpc: privateLambdaVPC | |
}); | |
const lambdaFunctionPrivate = new PythonFunction(this, `LambdaFunctionPrivate`, { | |
entry: `lambda/LambdaFunctionPrivate`, | |
index: 'handler.py', | |
handler: 'lambda_handler', | |
functionName: 'LambdaFunctionPrivate', | |
runtime: Runtime.PYTHON_3_9, | |
memorySize: 128, | |
securityGroups: [lambdaSecurityGroup], | |
vpc: privateLambdaVPC, | |
timeout: Duration.seconds(60) | |
}); | |
lambdaFunctionPrivate.addToRolePolicy(new PolicyStatement({ | |
"effect": Effect.ALLOW, | |
"actions": [ | |
"secretsmanager:ListSecrets", | |
"ec2:CreateNetworkInterface", | |
"ec2:DeleteNetworkInterface", | |
"ec2:DescribeNetworkInterfaces" | |
], | |
"resources": ["*"] | |
})); | |
const secretsManagerInterfaceEndpoint = privateLambdaVPC.addInterfaceEndpoint('SecretsManagerEndpoint', { | |
service: ec2.InterfaceVpcEndpointAwsService.SECRETS_MANAGER, | |
privateDnsEnabled: true, | |
subnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED }, | |
securityGroups: [secretsManagerEndpointSecurityGroup] | |
}); | |
const secret = new secretsmanager.Secret(this, 'CDKExampleSecret'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment