Skip to content
Merged
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
b73f958
initial commit
Jun 19, 2024
ac4aba1
remove cd command
Jun 19, 2024
baa5490
added github project path
Jun 19, 2024
f4ec8f0
rename stacks
Jun 19, 2024
c5e078c
rename stage app stacks
Jun 19, 2024
191e7cb
added vpc stack and cross stack reference the vpc in ecs stack
Jun 20, 2024
1160de2
added cdk.context.json to .gitignore
jfan9 Jun 20, 2024
ef4b1d3
added synthCodeBuildDefaults to fix build stage permission issue
jfan9 Jun 20, 2024
e81e690
added architecture diagram
Jun 22, 2024
a381c71
added architecture diagram to README>md
Jun 22, 2024
528a480
add lambdaApiStack
Jun 27, 2024
365bfaf
Merge pull request #3 from kyoonkwon/issue#820
jfan9 Jun 27, 2024
8954f34
added import PolicyStatement from cdk lib
jfan9 Jun 27, 2024
044a279
Dockerfile and App code
Jun 27, 2024
dca5a5e
lesser requirement
Jun 27, 2024
c59bb62
added datastore stack
sonal-aws Jun 27, 2024
2f5739f
Update pipeline-stack.ts
sonal-aws Jun 27, 2024
e11b6bc
Update pipeline-stack.ts
sonal-aws Jun 27, 2024
ca14668
Merge pull request #4 from ruchirshetye-aws/issue#820
fanq10 Jun 27, 2024
5d7eb17
Merge pull request #5 from sonal-aws/issue#820
fanq10 Jun 27, 2024
30c750c
updated import resource format
Jun 27, 2024
ab43c72
added waves to eu-west-1 & us-west-2
Jun 27, 2024
1de7188
fix container missing waitress module error
Jun 27, 2024
f3a9ea2
Update README.md
ruchirshetye-aws Jun 27, 2024
cf2746f
Added sample stack for event sources mapped asynchronous lambda funct…
naxxster Jun 27, 2024
b3bf459
Merge pull request #7 from junsjang/issue/820
jfan9 Jun 27, 2024
eeea417
Merge pull request #6 from ruchirshetye-aws/patch-1
jfan9 Jun 27, 2024
86607f7
added @types/aws-lambda: ^8.10.140
jfan9 Jun 28, 2024
92d14c1
updated a new version of diagram
Jun 28, 2024
19a4369
Update README.md
jfan9 Jun 29, 2024
564af79
relocate async lambda function code to assets
Jun 29, 2024
021930f
Merge branch 'main' into issue#820
fanq10 Aug 7, 2024
7e5f053
Merge branch 'main' into issue#820
kaiz-io Sep 17, 2024
9124436
Merge branch 'main' into issue#820
jfan9 Sep 17, 2024
aa0a2fa
explicit add account id in the pipeline
jfan9 Sep 18, 2024
a953af9
Merge branch 'main' into issue#820
jfan9 Sep 18, 2024
7cf8ea7
moved variables to app.ts
Oct 15, 2024
8421b47
upgrade cdk app version to v2.162.1
Oct 15, 2024
f9e0c1e
Merge branch 'main' into issue#820
fanq10 Oct 15, 2024
ad87f4f
Merge branch 'main' into issue#820
kaiz-io Nov 2, 2024
972e3cb
Update README.md
kaiz-io Nov 2, 2024
3f29f8c
Delete typescript/aws-codepipeline-ecs-lambda/test/aws-codepipeline-e…
kaiz-io Nov 2, 2024
194c0e5
Update package.json
kaiz-io Nov 2, 2024
bc619a2
Delete typescript/aws-codepipeline-ecs-lambda/jest.config.js
kaiz-io Nov 2, 2024
0cb89cd
Update Dockerfile
kaiz-io Nov 2, 2024
62ff408
fix: add DNA for cross account and lookup
Nov 2, 2024
352b351
Merge branch 'main' into issue#820
kaiz-io Nov 2, 2024
5b6acfe
Merge branch 'main' into issue#820
jfan9 Nov 4, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
*.js
!jest.config.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out
cdk.context.json
6 changes: 6 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
59 changes: 59 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# AWS Codepipeline CI/CD Solution for ECS Fargate and Lambda

## Architect Design:
<img width="900" alt="image" src="https://github.com/jfan9/jfan9-aws-cdk-examples/blob/92d14c15f68fb2887f74de3b7203ab85cc5c0b71/typescript/aws-codepipeline-ecs-lambda/static_images/Architecture_diagram.png">

## Overview

This CDK package provides a production-grade template for setting up AWS resources to enable smooth migration from monolithic EC2-based architectures to cloud-native solutions on AWS. It's designed for startups looking to scale their infrastructure efficiently.

Key features:
- CICD pipeline using AWS CodePipeline
- Lambda functions (async triggered and REST endpoints behind API Gateway)
- ECS Fargate based service with automatic deployment
- Integration with private GitHub repositories
- Reference to CDK created VPCs
- Creates RDS Instances with credentials managed by AWS Secrets Manager
- Event-driven architecture using SQS, SNS, and EventBridge

## Getting Started

### Prerequisites

- Create a Private Github Repository with source code inside 'aws-codepipeline-ecs-lambda' directory.
- Create a connection to GitHub or GitHub Enterprise Cloud, see [Create a connection to GitHub](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-create-github.html).
- Modify the `connectionArn` in `pipeline-stack.ts` file.
- Modify `githubOrg`, `githubRepo`, `githubBranch` with your private repository details.

## Project Structure

The project is organized into six main stacks:

1. `VpcStack`: Network infrastructure resources
2. `DataStoresStack`: Database resources
3. `PubSubStack`: Event-based infrastructure (SQS, SNS, EventBridge)
4. `AsyncLambdasStack`: Asynchronously triggered Lambda functions
5. `LambdaApisStack`: Lambda functions as REST endpoints behind API Gateway
6. `EcsFargateStack`: ECS Fargate Service, Cluster, Tasks, and Containers

You can easily customize the infrastructure by modifying or removing specific stacks in the `lib/pipeline-stage.ts` file.

## Solution overview

The CDK application is structured as follows:

`lib/pipeline-stack.ts` contains the definition of the CI/CD pipeline. The main component here is the CodePipeline construct that creates the pipeline for us

`lib/stage-app.ts` contains definitions of all the six stacks which the pipeline will deploy.

`lib/stage-app-vpc-stack.ts` creates new vpc resource along with subnets, nat gateways and remaining networking infrastructure.

`lib/stage-app-datastore-stack.ts` creates a Aurora Serverless V2 Cluster along with KMS key to encrypt the database.

`lib/stage-app-ecs-fargate-stack.ts` builds the `Dockerfile` and creates ecs fargate service along with loadbalancer.

`lib/stage-app-lambda-api-stack.ts` creates lambda functions as REST endpoints behind API Gateway resource.

`lib/PubSubStack.ts` creates sns, eventbridge and lambda function.

---
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { EventBridgeEvent, Context } from 'aws-lambda';

export const handler = async (event: EventBridgeEvent<string, any>) => {
console.log('LogEvent');
console.log('Received event:', JSON.stringify(event, null, 2));
return 'Finished';
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { SQSEvent, SQSBatchResponse, SQSBatchItemFailure } from 'aws-lambda';

export const handler = (event: SQSEvent): SQSBatchResponse | void => {
if (event) {
const batchItemFailures: SQSBatchItemFailure[] = [];
event?.Records.forEach(record => {
try {
// process record
} catch (err) {
batchItemFailures.push({
itemIdentifier: record.messageId
});
}
});

return { batchItemFailures };
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { SNSEvent, SNSEventRecord } from 'aws-lambda';

export const handler = async (event: SNSEvent) => {
for (const record of event.Records) {
await processMessageAsync(record);
}
console.info("done");
};

async function processMessageAsync(record: SNSEventRecord) {
try {
const message = JSON.stringify(record.Sns.Message);
console.log(`Processed message ${message}`);
await Promise.resolve(1); //Placeholder for actual async work
} catch (err) {
console.error("An error occurred");
throw err;
}
}
72 changes: 72 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"app": "npx ts-node --prefer-ts-exts lib/app.ts",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"**/*.d.ts",
"**/*.js",
"tsconfig.json",
"package*.json",
"yarn.lock",
"node_modules",
"test"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false
}
}
8 changes: 8 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
};
15 changes: 15 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/lib/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { pipelineStack } from './pipeline-stack';

const app = new cdk.App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }

const pipeline_stack = new pipelineStack(app, 'aws-codepipeline-stack', {
env,
});
cdk.Tags.of(pipeline_stack).add('managedBy', 'cdk');
cdk.Tags.of(pipeline_stack).add('environment', 'dev');

app.synth();
61 changes: 61 additions & 0 deletions typescript/aws-codepipeline-ecs-lambda/lib/pipeline-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { CodePipeline, CodePipelineSource, ManualApprovalStep, ShellStep, Wave } from 'aws-cdk-lib/pipelines';
import { pipelineAppStage } from './stage-app';
import { PolicyStatement } from 'aws-cdk-lib/aws-iam';

export class pipelineStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

const pipelineAccountId = process.env.PIPELINE_ACCOUNT_ID || "111111111111"; // replace with your pipeline account id
const pipelineRegion = process.env.PIPELINE_REGION || "us-east-1"; // replace with your pipeline region
const githubOrg = process.env.GITHUB_ORG || "aws-6w8hnx"; // replace with your GitHub Org
const githubRepo = process.env.GITHUB_REPO || "aws-codepipeline-ecs-lambda"; // replace with your GitHub Repo
const githubBranch = process.env.GITHUB_BRANCH || "main"; // replace with your GitHub repo branch
const devEnv = process.env.DEV_ENV || "dev"; // replace with your environment
const devAccountId = process.env.DEV_ACCOUNT_ID || "222222222222"; // replace with your dev account id
const primaryRegion = process.env.PRIMARY_REGION || "us-west-2"; // replace with your primary region
const secondaryRegion = process.env.SECONDARY_REGION || "eu-west-1"; // replace with your secondary region

const pipeline = new CodePipeline(this, 'pipeline', {
selfMutation: true,
crossAccountKeys: true,
reuseCrossRegionSupportStacks: true,
synth: new ShellStep('Synth', {
input: CodePipelineSource.connection(`${githubOrg}/${githubRepo}`, `${githubBranch}`,{
// You need to replace the below code connection arn:
connectionArn: `arn:aws:codestar-connections:${pipelineRegion}:${pipelineAccountId}:connection/0ce75950-a29b-4ee4-a9d3-b0bad3b2c0a6`
}),
commands: [
'npm ci',
'npm run build',
'npx cdk synth'
]
}),
synthCodeBuildDefaults: {
rolePolicy: [
new PolicyStatement({
resources: [ '*' ],
actions: [ 'ec2:DescribeAvailabilityZones' ],
}),
]}
});

const devStage = pipeline.addStage(new pipelineAppStage(this, `${devEnv}`, {
env: { account: `${pipelineAccountId}`, region: `${pipelineRegion}`}
}));
devStage.addPost(new ManualApprovalStep('approval'));

// add waves:
const devWave = pipeline.addWave(`${devEnv}Wave`);

devWave.addStage(new pipelineAppStage(this, `${devEnv}-${primaryRegion}`, {
env: { account: `${devAccountId}`, region: `${primaryRegion}`}
}));

devWave.addStage(new pipelineAppStage(this, `${devEnv}-${secondaryRegion}`, {
env: { account: `${devAccountId}`, region: `${secondaryRegion}`}
}));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as events from 'aws-cdk-lib/aws-events';
import * as eventsTargets from 'aws-cdk-lib/aws-events-targets';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import { SnsEventSource, SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
import * as path from 'path';
import { Function, Code, Runtime } from 'aws-cdk-lib/aws-lambda';

export class asyncLambdaStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// EventBridge event as an event source for a SNS topic and a SQS queue
const rule = new events.Rule(this, 'Rule', {
eventPattern: {
source: ['aws.ecs']
}
});

// Shared code asset
const code = Code.fromAsset(path.join(__dirname, '../assets/lambda-functions'));

// Lambda Function that will be invoked asynchronously when there is any event that matches the rule
const eventsFunction = new Function(this, 'EventFunction', {
runtime: Runtime.NODEJS_20_X,
code,
handler: 'events_handler.handler'
});
const eventsDLQ = new sqs.Queue(this, 'LambdaDLQ');
rule.addTarget(new eventsTargets.LambdaFunction(eventsFunction, {
deadLetterQueue: eventsDLQ,
maxEventAge: cdk.Duration.minutes(2),
retryAttempts: 2
}));

// Lambda Function that will be invoked asynchronously by a SNS topic
const topic = new sns.Topic(this, 'Topic');
rule.addTarget(new eventsTargets.SnsTopic(topic, {
deadLetterQueue: eventsDLQ,
maxEventAge: cdk.Duration.minutes(2),
retryAttempts: 2
}));

const topicFunction = new Function(this, 'TopicLambdaFunction', {
runtime: Runtime.NODEJS_20_X,
code,
handler: 'topic_message_handler.handler'
});
const topicDLQ = new sqs.Queue(this, 'TopicDLQ');
topicFunction.addEventSource(new SnsEventSource(topic, {
deadLetterQueue: topicDLQ
}));

// Lambda Function that will be invoked asynchronously with the event source of a SQS queue
const queue = new sqs.Queue(this, 'JobQueue');
rule.addTarget(new eventsTargets.SqsQueue(queue, {
deadLetterQueue: eventsDLQ,
maxEventAge: cdk.Duration.minutes(2),
retryAttempts: 2
}));

const queueFunction = new Function(this, 'QueueLambdaFunction', {
runtime: Runtime.NODEJS_20_X,
code,
handler: 'queue_message_handler.handler'
});
queueFunction.addEventSource(new SqsEventSource(queue, {
batchSize: 5,
maxBatchingWindow: cdk.Duration.seconds(5),
reportBatchItemFailures: true
}));
}
}
Loading