Skip to content

Instantly share code, notes, and snippets.

@therightstuff
Last active June 23, 2020 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therightstuff/fa38aa86f83ae5e8da73a22e9b01a931 to your computer and use it in GitHub Desktop.
Save therightstuff/fa38aa86f83ae5e8da73a22e9b01a931 to your computer and use it in GitHub Desktop.
Code samples for A templated guide to AWS serverless development with CDK
// this configuration results in the creation of AwsStack-dev,
// AwsStack-prod-us, AwsStack-test-eu and AwsStack-test-us
let stages:stagesType = {
prod: ["us"],
test: ["eu", "us"],
dev: [""]
}
for (let name in stages) {
let stage:string[] = stages[name];
for (let i in stage) {
let region = stage[i];
if (region.length == 0) {
// deploy region-agnostic when no region is specified
new AwsStack(app, `AwsStack-${name}`);
} else {
new AwsStack(app, `AwsStack-${name}-${region}`, { env: regions[region] });
}
}
}
Outputs:
AwsStack-dev.layerapiEndpointXXXXXXXX = https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/prod/
AwsStack-dev.dynamodbapiEndpointXXXXXXXX = https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/prod/
AwsStack-dev.simpleapiEndpointXXXXXXXX = https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/prod/
Stack ARN:
arn:aws:cloudformation:us-east-1:XXXXXXXXXXXX:stack/AwsStack-dev/a0b1c2d3-a0b1-a0b1-a0b1-a0b1c2d3e4f5
exports.handler = async (event) => {
const promise = new Promise(function(resolve, reject) {
// randomly return success or failure with the appropriate status code
let success = Math.floor(Math.random() * 2) == 1;
let statusCode = (success ? 200 : 500)
let returnObject = {
"success": success
};
resolve({
"isBase64Encoded": false,
"statusCode": statusCode,
"headers": {},
"body": JSON.stringify(returnObject)
});
});
return promise;
}
{
"isBase64Encoded": false,
"statusCode": 200,
"headers": {},
"body": JSON.stringify(returnObject)
}
export class AwsStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// simple test function
const simpleFunction = new Function(this, 'simple-function', {
runtime: Runtime.NODEJS_12_X,
handler: 'index.handler',
code: Code.asset('./handlers/simple'),
environment: {
GREETING: "Hello, World!"
},
});
const simpleApi = new RestApi(this, 'simple-api', {
restApiName: 'Simple API sample',
description: "Simple API sample with no dependencies"
});
simpleApi.root.addMethod('GET', new LambdaIntegration(simpleFunction));
...
{
"eu": {
"region": "eu-west-1",
"account": "XXXXXXXXXXXX"
},
"us": {
"region": "us-east-1",
"account": "XXXXXXXXXXXX"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment