aws-cdk-lib#RemovalPolicy TypeScript Examples
The following examples show how to use
aws-cdk-lib#RemovalPolicy.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: 004_SlackFederationAuthsTable.ts From flect-chime-sdk-demo with Apache License 2.0 | 6 votes |
createSlackFederationAuthsTable = (scope: Construct, id: string) => {
const slackFederationAuthsTable = new dynamo.Table(scope, "slackFederationAuthsTable", {
tableName: `${id}_SlackFederationAuthsTable`,
partitionKey: {
name: "TeamId",
type: dynamo.AttributeType.STRING,
},
readCapacity: 2,
writeCapacity: 2,
removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
});
return { slackFederationAuthsTable }
}
Example #2
Source File: 003_ConnectionTable.ts From flect-chime-sdk-demo with Apache License 2.0 | 6 votes |
createConnectionTable = (scope: Construct, id: string) => {
const connectionTable = new dynamo.Table(scope, "connectionTable", {
tableName: `${id}_ConnectionTable`,
partitionKey: {
name: "MeetingId",
type: dynamo.AttributeType.STRING,
},
sortKey: {
name: "AttendeeId",
type: dynamo.AttributeType.STRING,
},
readCapacity: 2,
writeCapacity: 2,
removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
});
return { connectionTable }
}
Example #3
Source File: 002_AttendeeTable.ts From flect-chime-sdk-demo with Apache License 2.0 | 6 votes |
createAttendeeTable = (scope: Construct, id: string) => {
const attendeeTable = new dynamo.Table(scope, "attendeeTable", {
tableName: `${id}_AttendeeTable`,
partitionKey: {
name: "AttendeeId",
type: dynamo.AttributeType.STRING,
},
readCapacity: 2,
writeCapacity: 2,
removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
});
return { attendeeTable }
}
Example #4
Source File: 001_MeetingTable.ts From flect-chime-sdk-demo with Apache License 2.0 | 6 votes |
createMeetingTable = (scope: Construct, id: string) => {
const meetingTable = new dynamo.Table(scope, "meetingTable", {
tableName: `${id}_MeetingTable`,
partitionKey: {
name: "MeetingName",
type: dynamo.AttributeType.STRING,
},
readCapacity: 2,
writeCapacity: 2,
removalPolicy: RemovalPolicy.DESTROY, // NOT recommended for production code
});
meetingTable.addGlobalSecondaryIndex({
indexName: "MeetingId",
partitionKey: {
name: "MeetingId",
type: dynamo.AttributeType.STRING,
},
projectionType: dynamo.ProjectionType.ALL,
readCapacity: 2,
writeCapacity: 2,
});
return { meetingTable }
}
Example #5
Source File: url-shortener.integ.ts From cloudstructs with Apache License 2.0 | 6 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const userPool = new cognito.UserPool(this, 'UserPool', {
removalPolicy: RemovalPolicy.DESTROY,
});
const urlShortener = new UrlShortener(this, 'UrlShortener', {
hostedZone: route53.HostedZone.fromHostedZoneAttributes(this, 'HostedZone', {
hostedZoneId: 'ZKEU89CLZS8GH',
zoneName: 'goldex.be',
}),
recordName: 'short',
apiGatewayAuthorizer: new apigateway.CognitoUserPoolsAuthorizer(this, 'Authorizer', {
cognitoUserPools: [userPool],
}),
corsAllowOrigins: ['*'],
});
const bucket = urlShortener.node.tryFindChild('Bucket') as s3.Bucket;
bucket.applyRemovalPolicy(RemovalPolicy.DESTROY);
new CfnOutput(this, 'ApiEndpoint', { value: urlShortener.apiEndpoint });
}
Example #6
Source File: StaticWebsite.ts From lift with MIT License | 6 votes |
getBucketProps(): BucketProps {
return {
// Enable static website hosting
websiteIndexDocument: "index.html",
websiteErrorDocument: this.errorPath(),
// public read access is required when enabling static website hosting
publicReadAccess: true,
// For a static website, the content is code that should be versioned elsewhere
removalPolicy: RemovalPolicy.DESTROY,
};
}
Example #7
Source File: code-pipeline.ts From cdk-examples with MIT License | 5 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
///////////////////////////////
// Part 7
const websiteBucket = Bucket.fromBucketArn(this, 'websiteBucket', websiteBucketArn)
const hugoBuildProject = new PipelineProject(this, 'hugoBuild', {
buildSpec: BuildSpec.fromSourceFilename('buildspec.yml'),
environment: {
buildImage: LinuxBuildImage.STANDARD_5_0,
computeType: ComputeType.SMALL
}
})
const artifactBucket = new Bucket(this, 'websitePipelineArtifactBucket', {
bucketName: 'hugo-pipeline-artifact-bucket',
removalPolicy: RemovalPolicy.DESTROY
})
const gitOutput = new Artifact('hugoRepoLatestMaster')
const buildOutput = new Artifact('hugoBuildOutput')
new Pipeline(this, 'hugoPipeline', {
artifactBucket,
pipelineName: 'examplePipeline',
stages: [
{
stageName: 'SourceCode',
actions: [
new CodeCommitSourceAction({
actionName: 'readLatestMasterCommit',
branch: 'main',
output: gitOutput,
repository: Repository.fromRepositoryArn(this, 'hugoGitRepo', hugoRepoArn)
})
]
},
{
stageName: 'Build',
actions: [
new CodeBuildAction({
actionName: 'buildHugoWebsite',
input: gitOutput,
outputs: [buildOutput],
project: hugoBuildProject
})
]
},
{
stageName: 'Deploy',
actions: [
new S3DeployAction({
actionName: 'DeployHugoWebsite',
input: buildOutput,
bucket: websiteBucket
})
]
}
]
})
///////////////////////////////
}
Example #8
Source File: pipeline-stack.ts From minwiz with BSD 2-Clause "Simplified" License | 5 votes |
constructor(app: App, id: string, props: PipelineStackProps) {
super(app, id, props);
const siteBuild = new PipelineProject(this, "MinWizBuild", {
description: "minwiz.com site build",
buildSpec: BuildSpec.fromObject({
version: "0.2",
phases: {
install: {
commands: ["npm ci"],
},
build: {
commands: "npm run build",
},
},
artifacts: {
"base-directory": "dist",
files: ["**/*"],
},
}),
environment: {
buildImage: LinuxBuildImage.STANDARD_5_0,
computeType: ComputeType.SMALL,
},
});
const siteBuildOutput = new Artifact("SiteBuildOutput");
const sourceOutput = new Artifact("SrcOutput");
const artifactBucket = new Bucket(this, "MinWizPipelineArtifacts", {
removalPolicy: RemovalPolicy.DESTROY,
encryption: BucketEncryption.S3_MANAGED,
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
autoDeleteObjects: true,
});
new Pipeline(this, "MinWiz", {
restartExecutionOnUpdate: true,
artifactBucket,
stages: [
{
stageName: "Source",
actions: [
new GitHubSourceAction({
actionName: "Checkout",
output: sourceOutput,
owner: "zeplia",
repo: "minwiz",
oauthToken: SecretValue.plainText(props.githubToken),
trigger: GitHubTrigger.WEBHOOK,
}),
],
},
{
stageName: "Build",
actions: [
new CodeBuildAction({
actionName: "Site_Build",
project: siteBuild,
input: sourceOutput,
outputs: [siteBuildOutput],
}),
],
},
{
stageName: "Deploy",
actions: [
new S3DeployAction({
actionName: "DeployStaticSite",
input: siteBuildOutput,
bucket: props.websiteBucket,
}),
],
},
],
});
}
Example #9
Source File: cloudfront.ts From minwiz with BSD 2-Clause "Simplified" License | 5 votes |
constructor(scope: Construct, id: string, props: CloudfrontStackProps) {
super(scope, id, props);
this.websiteBucket = new Bucket(this, "websiteBucket", {
removalPolicy: RemovalPolicy.DESTROY,
bucketName: website_domain,
autoDeleteObjects: true,
});
new CfnOutput(this, "websiteBucketArn", {
value: this.websiteBucket.bucketArn,
});
const cachePolicy = new CachePolicy(this, "MinWizPolicy", {
defaultTtl: Duration.hours(24),
minTtl: Duration.hours(24),
maxTtl: Duration.hours(24),
enableAcceptEncodingGzip: true,
enableAcceptEncodingBrotli: true,
});
const distribution = new Distribution(this, "MinWizDistribution", {
defaultBehavior: {
origin: new S3Origin(this.websiteBucket),
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachePolicy,
compress: true,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
domainNames: [website_domain /*, `www.${website_domain}`*/],
certificate: props.websiteCert,
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2019,
defaultRootObject: "index.html",
enableIpv6: true,
enabled: true,
httpVersion: HttpVersion.HTTP2,
priceClass: PriceClass.PRICE_CLASS_ALL,
});
new ARecord(this, "aliasForCloudfront", {
target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
zone: props.hostedZone,
recordName: website_domain,
});
new HttpsRedirect(this, "wwwToNonWww", {
recordNames: [`www.${website_domain}`],
targetDomain: website_domain,
zone: props.hostedZone,
});
}
Example #10
Source File: 001_FrontendBucket.ts From flect-chime-sdk-demo with Apache License 2.0 | 5 votes |
createFrontendS3 = (scope: Construct, id: string, USE_CDN: boolean) => {
const frontendBucket = new s3.Bucket(scope, "StaticSiteBucket", {
bucketName: `${id}-Bucket`.toLowerCase(),
removalPolicy: RemovalPolicy.DESTROY,
publicReadAccess: true,
});
let frontendCdn: cloudfront.CloudFrontWebDistribution | null = null;
if (USE_CDN) {
const oai = new cloudfront.OriginAccessIdentity(scope, "my-oai");
const myBucketPolicy = new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["s3:GetObject"],
principals: [new iam.CanonicalUserPrincipal(oai.cloudFrontOriginAccessIdentityS3CanonicalUserId)],
resources: [frontendBucket.bucketArn + "/*"],
});
frontendBucket.addToResourcePolicy(myBucketPolicy);
// Create CloudFront WebDistribution
frontendCdn = new cloudfront.CloudFrontWebDistribution(scope, "WebsiteDistribution", {
viewerCertificate: {
aliases: [],
props: {
cloudFrontDefaultCertificate: true,
},
},
priceClass: cloudfront.PriceClass.PRICE_CLASS_ALL,
originConfigs: [
{
s3OriginSource: {
s3BucketSource: frontendBucket,
originAccessIdentity: oai,
},
behaviors: [
{
isDefaultBehavior: true,
minTtl: Duration.seconds(0),
maxTtl: Duration.days(365),
defaultTtl: Duration.days(1),
pathPattern: "my-contents/*",
},
],
},
],
errorConfigurations: [
{
errorCode: 403,
responsePagePath: "/index.html",
responseCode: 200,
errorCachingMinTtl: 0,
},
{
errorCode: 404,
responsePagePath: "/index.html",
responseCode: 200,
errorCachingMinTtl: 0,
},
],
});
}
return { frontendBucket, frontendCdn }
}
Example #11
Source File: StaticWebsiteAbstract.ts From lift with MIT License | 5 votes |
getBucketProps(): BucketProps {
return {
// For a static website, the content is code that should be versioned elsewhere
removalPolicy: RemovalPolicy.DESTROY,
};
}
Example #12
Source File: s3cloudfront.ts From cdk-examples with MIT License | 5 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
///////////////////////////////
// Part 2
const bucket = new Bucket(this, 'websiteBucket', {
removalPolicy: RemovalPolicy.DESTROY,
bucketName: website_domain,
autoDeleteObjects: true
})
new CfnOutput(this, 'websiteBucketArn', {
value: bucket.bucketArn
})
///////////////////////////////
///////////////////////////////
// Part 3
const certificate = Certificate.fromCertificateArn(this, 'websiteCert', websiteCertArn)
const cachePolicy = new CachePolicy(this, 'examplePolicy', {
defaultTtl: Duration.hours(24),
minTtl: Duration.hours(24),
maxTtl: Duration.hours(24),
enableAcceptEncodingGzip: true,
enableAcceptEncodingBrotli: true
})
const distribution = new Distribution(this, 'exampleDistribution', {
defaultBehavior: {
origin: new S3Origin(bucket),
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachePolicy,
compress: true,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS
},
domainNames: [website_domain],
certificate,
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
defaultRootObject: 'index.html',
enableIpv6: true,
enabled: true,
httpVersion: HttpVersion.HTTP2,
priceClass: PriceClass.PRICE_CLASS_ALL
})
///////////////////////////////
///////////////////////////////
// Part 4
const hostedZone = HostedZone.fromHostedZoneAttributes(this, 'hostedZoneWithAttrs', {
hostedZoneId,
zoneName: website_domain
})
new ARecord(this, 'aliasForCloudfront', {
target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
zone: hostedZone,
recordName: website_domain
})
///////////////////////////////
///////////////////////////////
// Part 5
new HttpsRedirect(this, 'wwwToNonWww', {
recordNames: ['www.example.com'],
targetDomain: website_domain,
zone:hostedZone
})
const repo = new Repository(this, 'reactSourceCode', {
repositoryName: 'example',
description: `react repo for ${website_domain}`
})
new CfnOutput(this, 'reactRepoArn', {
value: repo.repositoryArn
})
///////////////////////////////
}
Example #13
Source File: code-pipeline.ts From cdk-examples with MIT License | 5 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
///////////////////////////////
// Part 7
const websiteBucket = Bucket.fromBucketArn(this, 'websiteBucket', websiteBucketArn)
const reactBuildProject = new PipelineProject(this, 'reactBuild', {
buildSpec: BuildSpec.fromSourceFilename('buildspec.yml'),
environment: {
buildImage: LinuxBuildImage.STANDARD_5_0,
computeType: ComputeType.SMALL
}
})
const artifactBucket = new Bucket(this, 'reactPipelineArtifactBucket', {
bucketName: 'react-pipeline-artifact-bucket',
removalPolicy: RemovalPolicy.DESTROY
})
const gitOutput = new Artifact('reactRepoLatestMaster')
const buildOutput = new Artifact('reactBuildOutput')
new Pipeline(this, 'reactPipeline', {
artifactBucket,
pipelineName: 'examplePipeline',
stages: [
{
stageName: 'SourceCode',
actions: [
new CodeCommitSourceAction({
actionName: 'readLatestMasterCommit',
branch: 'main',
output: gitOutput,
repository: Repository.fromRepositoryArn(this, 'reactGitRepo', reactRepoArn)
})
]
},
{
stageName: 'Build',
actions: [
new CodeBuildAction({
actionName: 'buildReactApp',
input: gitOutput,
outputs: [buildOutput],
project: reactBuildProject
})
]
},
{
stageName: 'Deploy',
actions: [
new S3DeployAction({
actionName: 'DeployReactApp',
input: buildOutput,
bucket: websiteBucket
})
]
}
]
})
///////////////////////////////
}
Example #14
Source File: lambda-cost-stack.ts From cdk-examples with MIT License | 5 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
const powerValues = '128,256,512,1024,2048'
new CfnApplication(this, 'powerTuner', {
location: {
applicationId: 'arn:aws:serverlessrepo:us-east-1:451282441545:applications/aws-lambda-power-tuning',
semanticVersion: '4.2.0'
},
parameters: {
"lambdaResource": "*",
"PowerValues": powerValues
},
timeoutInMinutes: 15
})
const todoTable = new Table(this, 'todoTable', {
partitionKey: {
name: 'id',
type: AttributeType.STRING
},
billingMode: BillingMode.PAY_PER_REQUEST,
removalPolicy: RemovalPolicy.DESTROY
})
new CfnOutput(this, 'todoTableName', {
value: todoTable.tableName
})
const getTodoFn = new NodejsFunction(this, 'getTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/get-todo/index.ts`,
handler: 'getTodo',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadData(getTodoFn)
const createTodoFn = new NodejsFunction(this, 'createTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/create-todo/index.ts`,
handler: 'createTodo',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(createTodoFn)
const deleteTodoFn = new NodejsFunction(this, 'deleteTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/delete-todo/index.ts`,
handler: 'deleteTodo',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(deleteTodoFn)
}
Example #15
Source File: index.ts From cloudstructs with Apache License 2.0 | 4 votes |
constructor(scope: Construct, id: string, props: UrlShortenerProps) {
super(scope, id);
const domainName = props.recordName ? `${props.recordName}.${props.hostedZone.zoneName}` : props.hostedZone.zoneName;
// Table to save a counter
const table = new dynamodb.Table(this, 'Table', {
partitionKey: {
name: 'key',
type: dynamodb.AttributeType.STRING,
},
removalPolicy: RemovalPolicy.DESTROY,
});
// Bucket to save redirects
const bucket = new s3.Bucket(this, 'Bucket', {
lifecycleRules: [{
expiration: props.expiration ?? Duration.days(365),
}],
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
bucketName: props.bucketName ?? `cloudstructs-url-shortener-${domainName}`,
});
// Redirect function
const redirectFunction = new RedirectFunction(this, 'Redirect');
bucket.grantRead(redirectFunction);
// CloudFront distribution
const certificate = new acm.DnsValidatedCertificate(this, 'Certificate', {
domainName,
hostedZone: props.hostedZone,
region: 'us-east-1',
});
const distribution = new cloudfront.Distribution(this, 'Distribution', {
defaultBehavior: {
origin: new origins.S3Origin(bucket),
edgeLambdas: [
{
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
functionVersion: redirectFunction,
},
],
},
certificate,
domainNames: [domainName],
});
// Route53 records
new route53.ARecord(this, 'ARecord', {
zone: props.hostedZone,
target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),
recordName: props.recordName,
});
new route53.AaaaRecord(this, 'AaaaRecord', {
zone: props.hostedZone,
target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),
recordName: props.recordName,
});
// Lambda function to increment counter and write redirect in bucket
const shortenerFunction = new ShortenerFunction(this, 'Shortener', {
logRetention: logs.RetentionDays.ONE_MONTH,
environment: {
DOMAIN_NAME: domainName,
BUCKET_NAME: bucket.bucketName,
TABLE_NAME: table.tableName,
},
});
if (props.corsAllowOrigins) {
shortenerFunction.addEnvironment('CORS_ALLOW_ORIGINS', props.corsAllowOrigins.join(' '));
}
bucket.grantPut(shortenerFunction);
table.grant(shortenerFunction, 'dynamodb:UpdateItem');
// API
this.api = new apigateway.RestApi(this, `UrlShortener${props.hostedZone.zoneName}`, {
endpointTypes: props.apiGatewayEndpoint ? [apigateway.EndpointType.PRIVATE] : undefined,
policy: props.apiGatewayEndpoint
? new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['execute-api:Invoke'],
principals: [new iam.AnyPrincipal()],
resources: [Fn.join('', ['execute-api:/', '*'])],
conditions: {
StringEquals: { 'aws:SourceVpce': props.apiGatewayEndpoint.vpcEndpointId },
},
}),
],
})
: undefined,
defaultCorsPreflightOptions: props.corsAllowOrigins
? { allowOrigins: props.corsAllowOrigins }
: undefined,
});
this.api.root.addMethod('ANY', new apigateway.LambdaIntegration(shortenerFunction), {
authorizer: props.apiGatewayAuthorizer,
});
this.api.root
.addResource('{proxy+}')
.addMethod('ANY', new apigateway.LambdaIntegration(shortenerFunction), {
authorizer: props.apiGatewayAuthorizer,
});
this.apiEndpoint = this.api.url;
}
Example #16
Source File: ServerSideWebsite.ts From lift with MIT License | 4 votes |
constructor(
scope: Construct,
private readonly id: string,
readonly configuration: Configuration,
private readonly provider: AwsProvider
) {
super(scope, id);
if (configuration.domain !== undefined && configuration.certificate === undefined) {
throw new ServerlessError(
`Invalid configuration in 'constructs.${id}.certificate': if a domain is configured, then a certificate ARN must be configured as well.`,
"LIFT_INVALID_CONSTRUCT_CONFIGURATION"
);
}
if (configuration.errorPage !== undefined && !configuration.errorPage.endsWith(".html")) {
throw new ServerlessError(
`Invalid configuration in 'constructs.${id}.errorPage': the custom error page must be a static HTML file. '${configuration.errorPage}' does not end with '.html'.`,
"LIFT_INVALID_CONSTRUCT_CONFIGURATION"
);
}
const bucket = new Bucket(this, "Assets", {
// Assets are compiled artifacts, we can clear them on serverless remove
removalPolicy: RemovalPolicy.DESTROY,
});
/**
* We create custom "Origin Policy" and "Cache Policy" for the backend.
* "All URL query strings, HTTP headers, and cookies that you include in the cache key (using a cache policy) are automatically included in origin requests. Use the origin request policy to specify the information that you want to include in origin requests, but not include in the cache key."
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html
*/
const backendOriginPolicy = new OriginRequestPolicy(this, "BackendOriginPolicy", {
originRequestPolicyName: `${this.provider.stackName}-${id}`,
comment: `Origin request policy for the ${id} website.`,
cookieBehavior: OriginRequestCookieBehavior.all(),
queryStringBehavior: OriginRequestQueryStringBehavior.all(),
headerBehavior: this.headersToForward(),
});
const backendCachePolicy = new CachePolicy(this, "BackendCachePolicy", {
cachePolicyName: `${this.provider.stackName}-${id}`,
comment: `Cache policy for the ${id} website.`,
// For the backend we disable all caching by default
defaultTtl: Duration.seconds(0),
// Authorization is an exception and must be whitelisted in the Cache Policy
// This is the reason why we don't use the managed `CachePolicy.CACHING_DISABLED`
headerBehavior: CacheHeaderBehavior.allowList("Authorization"),
});
const apiId =
configuration.apiGateway === "rest"
? this.provider.naming.getRestApiLogicalId()
: this.provider.naming.getHttpApiLogicalId();
const apiGatewayDomain = Fn.join(".", [Fn.ref(apiId), `execute-api.${this.provider.region}.amazonaws.com`]);
// Cast the domains to an array
this.domains = configuration.domain !== undefined ? flatten([configuration.domain]) : undefined;
const certificate =
configuration.certificate !== undefined
? acm.Certificate.fromCertificateArn(this, "Certificate", configuration.certificate)
: undefined;
this.distribution = new Distribution(this, "CDN", {
comment: `${provider.stackName} ${id} website CDN`,
defaultBehavior: {
// Origins are where CloudFront fetches content
origin: new HttpOrigin(apiGatewayDomain, {
// API Gateway only supports HTTPS
protocolPolicy: OriginProtocolPolicy.HTTPS_ONLY,
}),
// For a backend app we all all methods
allowedMethods: AllowedMethods.ALLOW_ALL,
cachePolicy: backendCachePolicy,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
// Forward all values (query strings, headers, and cookies) to the backend app
// See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html#managed-origin-request-policies-list
originRequestPolicy: backendOriginPolicy,
functionAssociations: [
{
function: this.createRequestFunction(),
eventType: FunctionEventType.VIEWER_REQUEST,
},
],
},
// All the assets paths are created in there
additionalBehaviors: this.createCacheBehaviors(bucket),
errorResponses: this.createErrorResponses(),
// Enable http2 transfer for better performances
httpVersion: HttpVersion.HTTP2,
certificate: certificate,
domainNames: this.domains,
});
// CloudFormation outputs
this.bucketNameOutput = new CfnOutput(this, "AssetsBucketName", {
description: "Name of the bucket that stores the website assets.",
value: bucket.bucketName,
});
let websiteDomain = this.getMainCustomDomain();
if (websiteDomain === undefined) {
// Fallback on the CloudFront domain
websiteDomain = this.distribution.distributionDomainName;
}
this.domainOutput = new CfnOutput(this, "Domain", {
description: "Website domain name.",
value: websiteDomain,
});
this.cnameOutput = new CfnOutput(this, "CloudFrontCName", {
description: "CloudFront CNAME.",
value: this.distribution.distributionDomainName,
});
this.distributionIdOutput = new CfnOutput(this, "DistributionId", {
description: "ID of the CloudFront distribution.",
value: this.distribution.distributionId,
});
}
Example #17
Source File: gitlab-runner-instance.ts From cdk-gitlab-runner with Apache License 2.0 | 4 votes |
constructor(scope: Construct, id: string, props: GitlabContainerRunnerProps) {
super(scope, id);
const spotFleetId = id;
const defaultProps = {
gitlabRunnerImage: 'public.ecr.aws/gitlab/gitlab-runner:alpine',
gitlaburl: 'https://gitlab.com/',
ec2type: 't3.micro',
tags: ['gitlab', 'awscdk', 'runner'],
};
const runnerProps = { ...defaultProps, ...props };
const runnerBucket = new Bucket(this, 'runnerBucket', {
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
const shell = UserData.forLinux();
shell.addCommands(...this.createUserData(runnerProps, runnerBucket.bucketName));
this.runnerRole =
runnerProps.ec2iamrole ??
new Role(this, 'runner-role', {
assumedBy: new ServicePrincipal('ec2.amazonaws.com'),
description: 'For Gitlab EC2 Runner Role',
});
this.validUntil = runnerProps.validUntil;
const instanceProfile = new CfnInstanceProfile(this, 'InstanceProfile', {
roles: [this.runnerRole.roleName],
});
runnerBucket.grantWrite(this.runnerRole);
this.vpc =
runnerProps.selfvpc ??
new Vpc(this, 'VPC', {
cidr: '10.0.0.0/16',
maxAzs: 2,
subnetConfiguration: [
{
cidrMask: 26,
name: 'RunnerVPC',
subnetType: SubnetType.PUBLIC,
},
],
natGateways: 0,
});
this.defaultRunnerSG = new SecurityGroup(this, 'SpotFleetSg', {
vpc: this.vpc,
});
this.defaultRunnerSG.connections.allowFromAnyIpv4(Port.tcp(22));
const spotOrOnDemand = runnerProps.spotFleet ?? false;
if (spotOrOnDemand) {
//throw new Error('yes new spotfleet');
const imageId = MachineImage.latestAmazonLinux({
generation: AmazonLinuxGeneration.AMAZON_LINUX_2,
}).getImage(this).imageId;
const lt = new CfnLaunchTemplate(this, 'LaunchTemplate', {
launchTemplateData: {
imageId,
instanceType: runnerProps.ec2type,
blockDeviceMappings: [
{
deviceName: '/dev/xvda',
ebs: {
volumeSize: runnerProps.ebsSize ?? 60,
},
},
],
userData: Fn.base64(shell.render()),
keyName: runnerProps.keyName,
tagSpecifications: [
{
resourceType: 'instance',
tags: [
{
key: 'Name',
value: `${Stack.of(this).stackName
}/spotFleetGitlabRunner/${spotFleetId}`,
},
],
},
],
instanceMarketOptions: {
marketType: 'spot',
spotOptions: {
blockDurationMinutes:
runnerProps.blockDuration ?? BlockDuration.ONE_HOUR,
instanceInterruptionBehavior:
runnerProps.instanceInterruptionBehavior ??
InstanceInterruptionBehavior.TERMINATE,
},
},
securityGroupIds: this.defaultRunnerSG.connections.securityGroups.map(
(m) => m.securityGroupId,
),
iamInstanceProfile: {
arn: instanceProfile.attrArn,
},
},
});
const spotFleetRole = new Role(this, 'FleetRole', {
assumedBy: new ServicePrincipal('spotfleet.amazonaws.com'),
managedPolicies: [
ManagedPolicy.fromAwsManagedPolicyName(
'service-role/AmazonEC2SpotFleetTaggingRole',
),
],
});
const vpcSubnetSelection = runnerProps.vpcSubnet ?? {
subnetType: SubnetType.PUBLIC,
};
const subnetConfig = this.vpc
.selectSubnets(vpcSubnetSelection)
.subnets.map((s) => ({
subnetId: s.subnetId,
}));
const cfnSpotFleet = new CfnSpotFleet(this, id, {
spotFleetRequestConfigData: {
launchTemplateConfigs: [
{
launchTemplateSpecification: {
launchTemplateId: lt.ref,
version: lt.attrLatestVersionNumber,
},
overrides: subnetConfig,
},
],
iamFleetRole: spotFleetRole.roleArn,
targetCapacity: 1,
validUntil: Lazy.string({ produce: () => this.validUntil }),
terminateInstancesWithExpiration: true,
},
});
const onEvent = new lambda.Function(this, 'OnEvent', {
code: lambda.Code.fromAsset(path.join(__dirname, '../assets/functions')),
handler: 'index.on_event',
runtime: lambda.Runtime.PYTHON_3_8,
timeout: Duration.seconds(60),
});
const isComplete = new lambda.Function(this, 'IsComplete', {
code: lambda.Code.fromAsset(path.join(__dirname, '../assets/functions')),
handler: 'index.is_complete',
runtime: lambda.Runtime.PYTHON_3_8,
timeout: Duration.seconds(60),
role: onEvent.role,
});
const myProvider = new cr.Provider(this, 'MyProvider', {
onEventHandler: onEvent,
isCompleteHandler: isComplete,
logRetention: logs.RetentionDays.ONE_DAY,
});
onEvent.addToRolePolicy(
new PolicyStatement({
actions: ['ec2:DescribeSpotFleetInstances'],
resources: ['*'],
}),
);
const fleetInstances = new CustomResource(this, 'GetInstanceId', {
serviceToken: myProvider.serviceToken,
properties: {
SpotFleetRequestId: cfnSpotFleet.ref,
},
});
fleetInstances.node.addDependency(cfnSpotFleet);
this.spotFleetInstanceId = Token.asString(
fleetInstances.getAtt('InstanceId'),
);
this.spotFleetRequestId = Token.asString(
fleetInstances.getAtt('SpotInstanceRequestId'),
);
new CfnOutput(this, 'InstanceId', { value: this.spotFleetInstanceId });
new CfnOutput(this, 'SpotFleetId', { value: cfnSpotFleet.ref });
} else {
this.runnerEc2 = new Instance(this, 'GitlabRunner', {
instanceType: new InstanceType(runnerProps.ec2type),
instanceName: 'Gitlab-Runner',
vpc: this.vpc,
vpcSubnets: runnerProps.vpcSubnet ?? {
subnetType: SubnetType.PUBLIC,
},
machineImage: MachineImage.latestAmazonLinux({
generation: AmazonLinuxGeneration.AMAZON_LINUX_2,
}),
role: this.runnerRole,
userData: shell,
securityGroup: this.defaultRunnerSG,
blockDevices: [
{
deviceName: '/dev/xvda',
volume: BlockDeviceVolume.ebs(runnerProps.ebsSize ?? 60),
},
],
});
new CfnOutput(this, 'Runner-Instance-ID', {
value: this.runnerEc2.instanceId,
});
}
const unregisterRunnerOnEvent = new lambda.Function(this, 'unregisterRunnerOnEvent', {
code: lambda.Code.fromAsset(path.join(__dirname, '../assets/functions')),
handler: 'unregister_runner.on_event',
runtime: lambda.Runtime.PYTHON_3_8,
timeout: Duration.seconds(60),
});
const unregisterRunnerProvider = new cr.Provider(this, 'unregisterRunnerProvider', {
onEventHandler: unregisterRunnerOnEvent,
logRetention: logs.RetentionDays.ONE_DAY,
});
const unregisterRunnerCR = new CustomResource(this, 'unregisterRunnerCR', {
resourceType: 'Custom::unregisterRunnerProvider',
serviceToken: unregisterRunnerProvider.serviceToken,
properties: {
BucketName: runnerBucket.bucketName,
GitlabUrl: runnerProps.gitlaburl,
},
});
runnerBucket.grantReadWrite(unregisterRunnerOnEvent);
unregisterRunnerCR.node.addDependency(runnerBucket);
this.runnerRole.addManagedPolicy(
ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'),
);
new CfnOutput(this, 'Runner-Role-Arn', {
value: this.runnerRole.roleArn,
});
}
Example #18
Source File: test-stack.ts From cdk-ssm-document with Apache License 2.0 | 4 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
let file = path.join(
__dirname,
'../documents/command/hello-world-yaml.yml'
);
const docA = new Document(this, 'SSM-Document-HelloWorld-Yaml', {
name: `${this.stackName}-HelloWorld-from-yaml-file`,
content: fs.readFileSync(file).toString(),
});
file = path.join(__dirname, '../documents/command/hello-world-json.json');
const docB = new Document(this, 'SSM-Document-HelloWorld-Json', {
name: `${this.stackName}-HelloWorld-from-json-file`,
content: fs.readFileSync(file).toString(),
});
file = path.join(
__dirname,
'../documents/automation/automation-document.yml'
);
const docC = new Document(this, `SSM-Document-Automation`, {
documentType: 'Automation',
name: 'Test-Automation',
content: fs.readFileSync(file).toString(),
});
const docD = new Document(this, 'SSM-Document-HelloWorld-Inline', {
name: `${this.stackName}-HelloWorld-from-inline`,
content: {
schemaVersion: '2.2',
description: 'Echo Hello World!',
parameters: {
text: {
default: 'Hello World!',
description: 'Text to echo',
type: 'String',
},
},
mainSteps: [
{
name: 'echo',
action: 'aws:runShellScript',
inputs: {
runCommand: ['echo "{{text}}"'],
},
precondition: {
StringEquals: ['platformType', 'Linux'],
},
},
],
},
});
/**
* Distributor example.
*
* Requires a bucket to hold install/update/uninstall scripts.
*/
const bucketName = `${Stack.of(this).account}-cdk-ssm-document-storage`;
const bucket = new aws_s3.Bucket(this, 'DistributorPackages', {
bucketName: bucketName,
blockPublicAccess: aws_s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
encryption: aws_s3.BucketEncryption.KMS_MANAGED,
// Makes for easy destroy and rerun of this stack over and over.
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
const packageDeploy = new aws_s3_deployment.BucketDeployment(
this,
'distribution-packages',
{
sources: [
aws_s3_deployment.Source.asset('../test/documents/distributor'),
],
destinationBucket: bucket,
}
);
let attachments: { [key: string]: any } = {};
// flip this condition to test an attachment update
if (true) {
file = path.join(__dirname, '../documents/distributor/v1/manifest.json');
attachments = {
versionName: '1.0-Custom-Name',
attachments: [{ key: 'SourceUrl', values: [`s3://${bucketName}/v1`] }],
};
} else {
file = path.join(__dirname, '../documents/distributor/v2/manifest.json');
attachments = {
versionName: '2.0-Better-Than_Sliced_Bread',
attachments: [{ key: 'SourceUrl', values: [`s3://${bucketName}/v2`] }],
};
}
const docE = new Document(this, `SSM-Distribution-Package`, {
documentType: 'Package',
name: 'Test-Distribution-Package',
content: fs.readFileSync(file).toString(),
...attachments,
});
/**
* The owner/creator of the document must have read access to the
* s3 files that make up a distribution. Since that is the lambda in this
* case we must give it `GetObject` permissions before they will can become
* `Active`.
*/
docE.lambda.role?.addToPrincipalPolicy(
new aws_iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [`${bucket.arnForObjects('*')}`],
})
);
docE.node.addDependency(docD);
docE.node.addDependency(packageDeploy);
docD.node.addDependency(docC);
docC.node.addDependency(docB);
docB.node.addDependency(docA);
const dir = path.join(__dirname, '../documents/command');
const files = fs.readdirSync(dir);
var last: Document | undefined = undefined;
for (const i in files) {
const name = files[i];
const shortName = name.split('.').slice(0, -1).join('.'); // removes file extension
const file = `${dir}/${name}`;
const doc = new Document(this, `SSM-Document-Loop-${shortName}`, {
name: `${this.stackName}-${shortName}`,
content: fs.readFileSync(file).toString(),
});
if (typeof last !== 'undefined') {
last.node.addDependency(doc);
}
last = doc;
}
}
Example #19
Source File: password-protect-s3-static-site-stack.ts From cdk-examples with MIT License | 4 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
///////////////////////////////
// Part 1
const hostedZone = HostedZone.fromHostedZoneAttributes(this, 'HostedZoneWithAttr', {
hostedZoneId: hostedZoneId,
zoneName: website_domain
})
const previewCert = new DnsValidatedCertificate(this, 'previewSSL', {
domainName: preview_domain,
hostedZone
})
const previewBucket = new Bucket(this, 'previewBucket', {
removalPolicy: RemovalPolicy.DESTROY,
bucketName: preview_domain,
autoDeleteObjects: true,
websiteIndexDocument: 'index.html',
websiteErrorDocument: '404.html'
})
new CfnOutput(this, 'previewBucketWebsiteUrl', {
value: previewBucket.bucketWebsiteUrl
})
///////////////////////////////
///////////////////////////////
// Part 2
previewBucket.addToResourcePolicy(new PolicyStatement({
sid: 'allow request from cloudfront to s3 website',
effect: Effect.ALLOW,
principals: [new AnyPrincipal()],
actions: ['s3:GetObject'],
resources: [`${previewBucket.bucketArn}/*`],
conditions: {
"StringLike": {
"aws:Referer": [previewSecret]
}
}
}))
const previewCachePolicy = new CachePolicy(this, 'previewCachePolicy', {
defaultTtl: Duration.minutes(30),
minTtl: Duration.minutes(25),
maxTtl: Duration.minutes(35),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
headerBehavior: CacheHeaderBehavior.allowList('authorization')
})
const edgeAuth = new experimental.EdgeFunction(this, 'edgeAuthFn', {
runtime: Runtime.NODEJS_14_X,
handler: 'index.handler',
code: Code.fromAsset(`${__dirname}/../lambda-fns/basic-auth/deployment.zip`),
memorySize: 128
})
///////////////////////////////
///////////////////////////////
// Part 3
const previewDistribution = new Distribution(this, 'previewDistribution', {
defaultBehavior: {
origin: new HttpOrigin(previewBucketWebsiteUrl, {
protocolPolicy: OriginProtocolPolicy.HTTP_ONLY,
customHeaders: {
'Referer': previewSecret
}
}),
edgeLambdas: [{
functionVersion: edgeAuth.currentVersion,
eventType: LambdaEdgeEventType.VIEWER_REQUEST
}],
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachePolicy: previewCachePolicy,
compress: true,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS
},
domainNames: [preview_domain],
certificate: previewCert,
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
httpVersion: HttpVersion.HTTP2,
priceClass: PriceClass.PRICE_CLASS_ALL
})
///////////////////////////////
///////////////////////////////
// Part 4
new ARecord(this, 'aliasForPreview', {
target: RecordTarget.fromAlias(new CloudFrontTarget(previewDistribution)),
zone: hostedZone,
recordName: preview_domain
})
///////////////////////////////
}
Example #20
Source File: backend-infra-stack.ts From cdk-examples with MIT License | 4 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
const ecrRepo = new Repository(this, 'nextJSRepo', {
repositoryName: 'next-starter',
removalPolicy: RemovalPolicy.DESTROY,
imageScanOnPush: true,
lifecycleRules: [
{
tagPrefixList: ['prod'],
maxImageCount: 5
},
{
maxImageAge: Duration.days(30)
}
]
})
new CfnOutput(this, 'repoUrl', {
value: ecrRepo.repositoryUri
})
const vpc = new Vpc(this, 'fargateVpc', {
maxAzs: 2
})
const cluster = new Cluster(this, 'fargateCluster', {
clusterName: 'fargateCluster',
containerInsights: true,
vpc
})
const domainZone = HostedZone.fromHostedZoneAttributes(this, 'hostedZoneWithAttributes', {
zoneName: website_domain,
hostedZoneId
})
const fargateService = new ApplicationLoadBalancedFargateService(this, 'fargateService', {
cluster,
assignPublicIp: true,
cpu: 256,
desiredCount: 1,
memoryLimitMiB: 512,
redirectHTTP: true,
protocol: ApplicationProtocol.HTTPS,
deploymentController: {
type: DeploymentControllerType.ECS
},
domainName: website_domain,
domainZone,
taskImageOptions: {
// image from docker hub
// image: ContainerImage.fromRegistry('apoorvmote/next:prod-v1'),
// image from public ecr registry
// image: ContainerImage.fromRegistry('public.ecr.aws/abc123xyz/next:prod-v1'),
// image from private ecr registry
image: ContainerImage.fromEcrRepository(ecrRepo, 'prod-v1'),
}
})
const scalableTarget = fargateService.service.autoScaleTaskCount({
minCapacity: 1,
maxCapacity: 20
})
scalableTarget.scaleOnCpuUtilization('cpuScaling', {
targetUtilizationPercent: 70
})
new HttpsRedirect(this, 'wwwToNonWww', {
recordNames: ['www.example.com'],
targetDomain: website_domain,
zone: domainZone
})
const nextRepo = new codecommit.Repository(this, 'nextJSSourceCode', {
repositoryName: 'next-blog',
description: 'Pipeline source code'
})
new CfnOutput(this, 'sourceCodeUrl', {
value: nextRepo.repositoryCloneUrlSsh
})
const containerBuildProject = new PipelineProject(this, 'containerBuild', {
buildSpec: BuildSpec.fromSourceFilename('buildspec.yml'),
environment: {
buildImage: LinuxBuildImage.STANDARD_5_0,
computeType: ComputeType.SMALL,
privileged: true
},
environmentVariables: {
'docker_username': {
value: dockerUsername
},
'docker_password': {
value: dockerPassword
}
}
})
ecrRepo.grantPullPush(containerBuildProject.grantPrincipal)
const artifactBucket = new Bucket(this, 'containerBuildArtifactBucket', {
bucketName: 'example-pipeline-artifact',
removalPolicy: RemovalPolicy.DESTROY
})
const gitOutput = new Artifact('nextJSLatestMaster')
const buildOutput = new Artifact('ContainerBuildOutput')
new Pipeline(this, 'containerPipeline', {
artifactBucket,
pipelineName: 'examplePipeline',
stages: [
{
stageName: 'SourceCode',
actions: [
new CodeCommitSourceAction({
actionName: 'readCode',
output: gitOutput,
repository: nextRepo,
branch: 'main'
})
]
},
{
stageName: 'build',
actions: [
new CodeBuildAction({
actionName: 'buildContainer',
input: gitOutput,
outputs: [buildOutput],
project: containerBuildProject
})
]
},
{
stageName: 'deploy',
actions: [
new EcsDeployAction({
actionName: 'deployContainer',
service: fargateService.service,
input: buildOutput,
deploymentTimeout: Duration.minutes(30)
})
]
}
]
})
}
Example #21
Source File: s3cloudfront.ts From cdk-examples with MIT License | 4 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
///////////////////////////////
// Part 2
const bucket = new Bucket(this, 'websiteBucket', {
removalPolicy: RemovalPolicy.DESTROY,
bucketName: website_domain,
autoDeleteObjects: true,
websiteIndexDocument: 'index.html',
websiteErrorDocument: '404.html'
})
bucket.addToResourcePolicy(new PolicyStatement({
effect: Effect.ALLOW,
principals: [new AnyPrincipal()],
actions: ['s3:GetObject'],
resources: ['arn:aws:s3:::example.com/*'],
conditions: {
"StringLike":{"aws:Referer":[bucketRefererSecret]}
}
}))
new CfnOutput(this, 'websiteBucketArn', {
value: bucket.bucketArn
})
new CfnOutput(this, 'websiteBucketUrl', {
value: bucket.bucketWebsiteUrl
})
///////////////////////////////
///////////////////////////////
// Part 3
const certificate = Certificate.fromCertificateArn(this, 'websiteCert', websiteCertArn)
const cachePolicy = new CachePolicy(this, 'examplePolicy', {
defaultTtl: Duration.hours(24),
minTtl: Duration.hours(24),
maxTtl: Duration.hours(24),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true
})
const distribution = new Distribution(this, 'exampleDistribution', {
defaultBehavior: {
origin: new HttpOrigin(bucketWebsiteUrl, {
protocolPolicy: OriginProtocolPolicy.HTTP_ONLY,
customHeaders: {
'Referer': bucketRefererSecret
}
}),
allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
cachePolicy,
compress: true,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS
},
domainNames: [website_domain],
certificate,
minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
enableIpv6: true,
enabled: true,
httpVersion: HttpVersion.HTTP2,
priceClass: PriceClass.PRICE_CLASS_ALL
})
///////////////////////////////
///////////////////////////////
// Part 4
const hostedZone = HostedZone.fromHostedZoneAttributes(this, 'hostedZoneWithAttrs', {
hostedZoneId,
zoneName: website_domain
})
new ARecord(this, 'aliasForCloudfront', {
target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
zone: hostedZone,
recordName: website_domain
})
///////////////////////////////
///////////////////////////////
// Part 5
new HttpsRedirect(this, 'wwwToNonWww', {
recordNames: ['www.example.com'],
targetDomain: website_domain,
zone:hostedZone
})
const repo = new Repository(this, 'hugoSourceCode', {
repositoryName: 'example',
description: `hugo repo for ${website_domain}`
})
new CfnOutput(this, 'hugoRepoArn', {
value: repo.repositoryArn
})
///////////////////////////////
}
Example #22
Source File: dynamodb-crud-stack.ts From cdk-examples with MIT License | 4 votes |
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
const todoTable = new Table(this, 'todoTable', {
partitionKey: {
name: 'id',
type: AttributeType.STRING
},
billingMode: BillingMode.PAY_PER_REQUEST,
removalPolicy: RemovalPolicy.DESTROY
})
todoTable.addGlobalSecondaryIndex({
indexName: 'ownerIndex',
partitionKey: {
name: 'owner',
type: AttributeType.STRING
}
})
new CfnOutput(this, 'todoTableName', {
value: todoTable.tableName
})
const createTodoFn = new NodejsFunction(this, 'createTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/create/index.ts`,
handler: 'createTodo',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(createTodoFn)
const getAllTodoFn = new NodejsFunction(this, 'getAllTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/getAll/index.ts`,
handler: 'getAll',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadData(getAllTodoFn)
const getOneTodoFn = new NodejsFunction(this, 'getOneTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/getOne/index.ts`,
handler: 'getOne',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadData(getOneTodoFn)
const updateTodoFn = new NodejsFunction(this, 'updateTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/update/index.ts`,
handler: 'update',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(updateTodoFn)
const deleteTodoFn = new NodejsFunction(this, 'deleteTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/delete/index.ts`,
handler: 'deleteTodo',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(deleteTodoFn)
const tableWithIndex = Table.fromTableAttributes(this, 'tableWithIndex', {
tableName: todoTableName,
globalIndexes: ['ownerIndex']
})
const queryTodoFn = new NodejsFunction(this, 'queryTodoFn', {
runtime: Runtime.NODEJS_16_X,
entry: `${__dirname}/../lambda-fns/query/index.ts`,
handler: 'queryTodo',
architecture: Architecture.ARM_64,
environment: {
TODO_TABLE_NAME: todoTableName
}
})
tableWithIndex.grantReadData(queryTodoFn)
}