Skip to content

Commit b8b10ed

Browse files
maskeradeDoug-AWSorozcoadrianElad Ben-Israelsimalexan
authored
feat: add typescript example of a Fargate service with efs mount (#274)
* Fix broken links (aws-samples#42) * Fixed broken links * Update README.md * minor wording changes in readme files * minor wording changes * modernize python and typescript examples * add default region in env * feat: add example for AppSync GraphQL w/ DynamoDB CRUD resolvers (aws-samples#44) Add a AWS CDK example for an AppSync GraphQL API with an API Key, and CRUD Resolvers with DynamoDB. There are different Resolvers doing two Queries to Get One, All and two Mutations doing Save Item and Delete Item. Should be useful for developers starting with AWS CDK on how to run a GraphQL API with Resolvers and DynamoDB. . * Updated Python examples to work with 0.33. Note that this still doesn't fix #483 but is a precursor to that. * fix(elasticbeanstalk-bg-pipeline): Converted 'getContext' to 'tryGetContext' (aws-samples#49) * fix(elasticbeanstalk-environment): Converted 'getContext' to 'tryGetContext' (aws-samples#49) * fix(static-site): Converted 'getContext' to 'tryGetContext' (aws-samples#49) * fix(static-site): Converted 'AliasRecord' to new 'ARecord' and converted props accordingly (aws-samples#49) * fix(typescript): Replaced all instances of 'app.run()' with 'app.synth()' (aws-samples#49) To comply with new standard nomenclature * Update ecs typescript examples to v0.36.1 * Updating Python examples to 0.36.1 (aws-samples#64) * WIP: Updating Python examples to 0.36.1 * Adding some ECS examples * Adding more ECS examples * Adding final ECS examples * fix: many updates to fix for CDK 0.36.0 (aws-samples#62) * Change @aws-cdk/cdk to @aws-cdk/core * change in typescript files as well * changed values for resoruce overrides * more updates to latest apis * more updates * added commet * more cleanup * updates to more files * static site patch * fix time * Update CONTRIBUTING.md - Update documentation to align version `0.36.0` Co-Authored-By: Tom Dufall <tom@tomdufall.co.uk> * fix instance type constructor to include a combincation of class and size * fix path resolution for fromAsset * nit cleanup * better definition of instane type * timeout to 300 seconds * change from AssetCode to Code * added cluster capacity for further investigation * added optional properities back * extra space * uncomment code for further investigation * added timeout duration * feat: README - add table of contents (aws-samples#51) Proposing adding a "table of contents" to the README * fix: ecs-service-with-logging - ECS, not Fargate (aws-samples#52) * ecs-service-with-logging - ECS, not Fargate ecs-service-with-logging uses ECS, not Fargate * actually want this to say 'Starting a container fronted by a load balancer on ECS' not frontend * chore(ecs-cluster): remove comment from the ecs cluster example (aws-samples#67) * fix: update Python StepFunctions project layout (aws-samples#66) * chore(overrides): add README to "overrides" example (aws-samples#69) The README explains that the example does not end up in a deployable state. Also slighly edit example to use some of the nicer new features. Fixes aws-samples#68. * Updating all Python examples for CDK release 0.38 (aws-samples#70) * Update VPCProps to us maxAzs (aws-samples#72) * feat: README updates 0.39.0. Builds confirmed (aws-samples#71) * fix: rename flasks app.synth to app.run (aws-samples#74) flasks app.run was accidentally renamed to app.synth in global rename * fix: remove duplicate grant in ddb example (aws-samples#75) * fix: CDK General Availability (1.0.0) updates (aws-samples#76) Also build all examples in the PR build. * Delete README.txt * Fixes an invalid function name in the lambda-cron Java example, and updates test assertions to match. * Removed * imports in favour of fully qualified single imports at the request of @rhboyd. * Remove functionName from java lambda-cron example. * Update java lambda-cron example expected CFT to have more realistic resource names. * Reverted changes to java lambda-cron example back to using SingletonFunction, without functionName. * sets removal policy on S3 and DynamoDB to DESTROY * chore: added issue/pr templates + mergify/semanticprs config (aws-samples#101) * url-shortner from aws online tech talk Add the python example for the url-shortener service demo in the online tech talk about the AWS CDK. * Updates * un-ignore and add waltersco_common * annotated with comments all around * some minor cr tweaks * dummy values for external resources the build system of aws-cdk-examples will attempt to synth all sample apps (which is a great thing), but since we have external resources, we need some dummy values as defaults. * handle fake context in all builds * dont fail synth * chore: fix build for ElasticBeanStalk TypeScript examples * feat: include DNS-validated ACM certificate and S3 bucket deployment for static site (aws-samples#118) * feat: example using S3 trigger for Lambda (aws-samples#106) * feat: Python example for APIGW with lambda integration and CORS (aws-samples#104) * chore: update version of maven-compiler-plugin (aws-samples#98) * feat: add Python example for Kinesis+Lambda (aws-samples#77) * fix: updated Policy Name to match new parameter format (aws-samples#86) * Reference to Typescript >Python translation docs (aws-samples#90) Added reference to doc that provides guidance on how to read TypeScript code and translating it to Python. * feat: add C# port of TypeScript 'my-widget-service' (aws-samples#92) * feat: make Python load balancer example start an actual HTTP server (aws-samples#97) * feat: (python) added my-widget-service example (aws-samples#122) * added my-widget-service * added PR feedback * fixed merge conflict with gitignore * added my-widget-service * added PR feedback * fixed merge conflict with gitignore * added more robust gitignore * feat: Add python example for appsync-graphql-dynamodb (aws-samples#121) * add appsync-graphql-dynamodb * add appsync-graphql-dynamodb * Delete README.md * feat: add appsync-graphql-dynamodb python example * pep8 lint * rm setup.py * feat: add python/appsync-graphql-dynamodb/README.md (aws-samples#124) * feat: add python/appsync-graphql-dynamodb/README.md * feat: add python/appsync-graphql-dynamodb/README.md * fix: Update Fargate LoadBalance Service examples (aws-samples#126) Update Fargate load balanced service example for TypeScript and Python based on aws/aws-cdk#3719. * fix: update static site example after breaking changes * fix: update fargate-service-with-auto-scaling (aws-samples#139) broke here: https://github.com/aws/aws-cdk/pull/4369/files#diff-3311a7940b009157ac675f59ce84e301L35 * fix: update ecs-patterns examples to use the latest version of the cdk (aws-samples#136) * Fix ecs-patterns examples to use the latest version of the cdk * Fix merge conflicts * feat: added a CodePipeline Python example building a Docker image (aws-samples#140) * feat(ecs/elbv2): add example showing how to share LB across stacks * chore: update lambda.Runtime to NODEJS_10_X (aws-samples#133) * chore: update lambda.Runtime to NODEJS_10_X Node.js 8.x EoL is on 31 Dec 2019 https://endoflife.date/nodejs * update dependencies * The Python version specified in the Lambda runtime has been changed from PYTHON_2_X to PYTHON_3_6. (aws-samples#146) * fix: correct minor typos in code (aws-samples#150) * chore: update Java examples (aws-samples#144) * chore: update Java examples * fixup dependency declarations * chore: clean up C# example (aws-samples#143) - Added the dependency on the JSII Roslyn analyzers package. - Removed now-unnecessary `null` arguments for "default props". - Upgraded Lambda's runtime to Node-10.x (Node-8.x being deprecated) * Change to loadBalancerTarget() (aws-samples#142) * feat: add RandomWriter C# example (aws-samples#153) * custom resource example for Java * fix: update the Python URL shortener example with the new cdk.context.json used by the VPC provider (aws-samples#170) Fixes the build of the project. * implemented Builder.create() pattern for the resources * chore: refresh Java examples with latest syntax elements (aws-samples#162) * Fix typos in appsync-graphql-dynamodb/requirements.txt (aws-samples#157) * adding java examples for static site and stepfunctions-job-poller * feat: add RDS sample in Python (aws-samples#158) * fix: Allow ingress traffic from public internet for NLB Ec2/Fargate Service (aws-samples#155) * Allow ingress traffic from public internet * Fix load balancer service examples * Fix README * Added .NET link to README. (#193) * feat: Add C# Static-Site (aws-samples#173) * Add C# Static-Site * some semantic fixes * Readme updates for clarity * Example Formatting Formatted new example source code with the google java formatter. * feat: Add C# StepFunctions Job Poller (aws-samples#174) * Add C# StepFunctions Job Poller * semantic fixes * feat(Java): add Java code for resource-overrides example. (aws-samples#167) * feat(Java): add Java code for resource-overrides example. * Add simple test. * Address PR comments * feat: my-widget-service example for Java (aws-samples#172) * my-widget-service java example * cleaned up output.json * Updated Readme for my-widget-service * Updated pom.xml fix the build * removed org.codehaus.mojo plugin from pom.xml * updated the reference to app class in pom.xml * updated cdk.json to point to App class, cleaned up the stack code with consistent formatting * updated gitignore for bin directory * format updates to stack class * updated cdk version to 1.18.0 * add .class to gitignore * java syntax updates updated to use "Builder" syntax for construct library * feat: Add C# Classic Load Balancer (aws-samples#180) * Add C# Classic Load Balancer * minor semantic/typo fixes * added the static site and stepfunctions java examples info to ReadMe * feat: Format Java Code (#199) Formats existing java examples using google-java-format. Adds 'style and formatting' section to CONTRIBUTING.md regarding java code formatting. Fixes #198 * update cdk version numbers (aws-samples#171) * Upgrade typescript version to resolve implicitly issue (aws-samples#159) * fix(java/resource-overrides): example uses method toPrettyString() which doesn't exist (#201) * feat: c# project with a c# lambda function handler (#202) There is no clear guidance at the moment on how to use C# lambda function handler within a CDK project. Adding an example here for customers to discover or for us to direct them. aws/aws-cdk#5340 is a customer question on this. * feat: added ECS fargate-load-balanced-service Java example (aws-samples#160) * Initial commit of Java fargate-load-balanced-service * Removed unused code and updated ECSFargateLoadBalancedStack * Linked Java version of fargate-load-balanced-service to the README.md * Updated expected CloudFormation for the JUnit test * Removed unused imports * Added some comments and did some code cleanup * Updated SG to include VPC Cide (#191) * updated Python Fargate Service load balance example for security groups (#192) * updated ts version (#207) * feat(new-ex): add an Amplify Console App Example (aws-samples#59) * adding the Amplify Console App example * minor updates due to cdk changes * update readme to standard format Co-authored-by: Noah Litov <noahlitov@gmail.com> * feat: Add C# ElasticBeanstalk (#182) * Add C# ElasticBeanstalk Authored-by: Richard H Boyd <58230111+richardhboyd@users.noreply.github.com> Co-authored-by: Noah Litov <noahlitov@gmail.com> * fix: update travis to use jsii superchain (#219) * update travis to use jsii superchain * update maven version custom-resource * feat(new-ex): add AppSync triggering Event Bridge Example (aws-samples#103) * Add AppSync2EventBridge Example * update lambda node version * latest ts and cdk versions * some package build fixes Co-authored-by: Noah Litov <noahlitov@gmail.com> * Add requirements.txt for python/api-cors-lambda (#200) Co-authored-by: Noah Litov <noahlitov@gmail.com> * Update README.md (#213) * fix: update CDK versions for Java examples to latest (#217) Updated all Java examples to the latest CDK version. We switched to use a version range in `pom.xml`, so we will now always use the latest versions as they are available. Also fixed the expected CFN output for the ECS examples tests (the updated CDK versions brought with them more taggable resources in the CFN spec). Fixes #216 * feat(new-ex): custom logical names (aws-samples#120) * custom logical names an example for how to implement custom logical name allocation. related: aws/aws-cdk#4045 * Use `ApplicationLoadBalancedFargateService` * fix: broken build (#225) The resource-overrides code build was broken because desiredCapacity is not calculated all of the time. Ref: aws/aws-cdk@0adf6c7#diff-ab28b1e5c6b252f017045680eb86f108 Also, outputting the current project being built into STDOUT for better future diagnosis. * feat(repo): add dotnet buildscripts (#229) - Adds dotnet build script build-csharp.sh and modified build.sh to run the former - Minor fixes to build scripts to improve consistency * chore(csharp): update cdk configs for new csharp CI builds - Added package-lambda script to capitalize-string - Added context to elasticbeanstalk-environment - Added DO_NOT_AUTOTEST to static-site (requires user credentials in code) - Added context to static-site Fixes #228 <!-- Please create a new issue if none exists yet --> * feat(repo): add actions CI to repo (#231) * feat: add actions CI to repo * make build-csharp.sh executable * make build-csharp.sh executable * make build-csharp.sh executable * fix random-writer versioning * feat(py-stepfunctions): add step-mapping to example (#215) * Added Mapping to step function * Added Mapping to step function * Added Mapping to step function * Made suggested corrections. Co-authored-by: Noah Litov <noahlitov@gmail.com> * feat: add 3 tier app, usage of userdata, sec grps (#214) * feat: add 3 tier app, usage of userdata, sec grps * fix: correct the naming of directory * fix: correct the naming of directory * Delete nextcloud_docker_cdk_stack.py * Update setup.py * Update setup.py Co-authored-by: Noah Litov <noahlitov@gmail.com> * feat: Passing resources between stacks (#210) * resource passing * fix comment * Update setup.py Co-authored-by: Noah Litov <noahlitov@gmail.com> * feat: add VPC, EC2 Python Example (#204) This pull request is aimed at creating the following Python Examples: - Import VPC - Create new VPC with 2 AZs and 6 Subnets, Public, Private and DataBase. - Sharing VPC between two stacks - Create ALB/EC2/AutoscalingGroup in the VPC - How to define EC2 to specify AMI or auto-selection - Define property override for EC2 Instance with BlockStorageMapping - Define userdata for EC2 to setup httpd - Create NAT GW and Bastion - Chain the Security Groups * feat: Add EKS cluster with VPC and self managed ASG example (#224) Adds a typescript example EKS cluster with a VPC & auto-scaling group. * feat: DynamoDB, Lambda and CloudWatch Example (#220) * Added Mapping to step function * Added Mapping to step function * Added Mapping to step function * Made suggested corrections. * cdk dynamo-lambda example * fix requirements.txt to include packages Co-authored-by: Noah Litov <noahlitov@gmail.com> * chore: remove Travis CI config file (#233) Remove the Travis configuration file so Github Actions is the only CI for repo. * feat: Add codebuild cdk examples to create Project, ReportGroup… (#235) * feat: Add codebuild cdk examples to create Project, ReportGroup and SourceCredentials This commit adds three CDK sample examples for the aws codebuild in java. It will help customers use the sample for better understanding of using CDK for codebuild. * feat: Java :implementation of classic load balancer sample (#187) * Java implementation of classic load balancer Co-authored-by: netanir <neta1nir@gmail.com> Co-authored-by: Noah Litov <noahlitov@gmail.com> * fix: change ecs local example to ALB (#242) * fix: Fixes broken link for ecs-network-load-balanced-service exa… (#243) * feat: Java api cors lambda crud dynamodb (#196) * Java implementation of classic load balancer * Java Sample for api-cors-lambda-dynamodb * Refactored to two seaparate module - lambda and cd stack * Need some dummy files for build to succeed with maven sub-modules. * need a cdk.json for build to go through * Need some dummy files for build to succeed with maven sub-modules. Co-authored-by: Mitchell Valine <mitchellvaline@gmail.com> * chore: update version of checkout action in workflow (#247) * feat(newex): example of Cognito-protected APIGateway backed by L… (#252) This makes a Cognito-protected APIG backed by a simple Hello World Lambda. Signed-off-by: campionfellin <campionfellin@gmail.com> * fix: broken build (#255) * update Cognito example to incorporate the recent breaking change. * eks/cluster typescript project to exclude re-compiling dependencies in `node_modules/`. * feat: add lambda-ddb-mysql-etl-pipeline python service (aws-samples#134) * Contributing new Python CDK example project * feat: Add context vars & fix: README update * feat: added layers, context vars, fixed mysql exmpl & gen refactor * feat:add a multi rule ALB sample with host and path based routing (#257) * add a multi rule ALB sample with a combination of host and path based routing * Update java/alb-multi-rule-response/README.md * fix: Typo in README (#258) * fix: csharp example RandomWriter does not build CDK and JSII versions were not pinned and the latest release included breaking changes. Also modified the dependencies to be pinned to the latest version * Revert "fix: csharp example RandomWriter does not build" This reverts commit 8492843. * fix: csharp example RandomWriter does not work CDK and JSII versions were not pinned and the latest release included breaking changes. Also modified the dependencies to be pinned to the latest version * chore: unpin cdk versions so they can serve as canaries for changes that might be breaking in the future * chore: remove pinned dependencies for csharp examples Rationale: these should work with the latest release and also serve as a canary if they break. * fix: indicate port 80 is http NOT ssh (#273) fixes a comment typo indicating that port 80 was assigned to ssh * Add example of fargate service with an efs filesystem mount * Update with requested changes & add readme - also bump cdk packages to latest version * Fix aws-cdk package versions Co-authored-by: Doug <dougsch@amazon.com> Co-authored-by: Adrian Orozco <orozcoadrian@gmail.com> Co-authored-by: Elad Ben-Israel <benisrae@amazon.com> Co-authored-by: Alexander Simovic <alexander.simovic@gmail.com> Co-authored-by: Mitch Garnaat <mitch@garnaat.com> Co-authored-by: Noah Litov <litovng@amazon.com> Co-authored-by: Piradeep Kandasamy <piradeep@amazon.com> Co-authored-by: tbadlov <zvika@badalov.us> Co-authored-by: Scott Brenner <scott@scottbrenner.me> Co-authored-by: Richard Boyd <rboyd@gatech.edu> Co-authored-by: Rico Huijbers <rix0rrr@gmail.com> Co-authored-by: Noah Litov <noahlitov@gmail.com> Co-authored-by: Brian Pfeil <brian.pfeil@gmail.com> Co-authored-by: Jan Sepke <625043+jansepke@users.noreply.github.com> Co-authored-by: Adam Ruka <adamruka85@gmail.com> Co-authored-by: Nathan Peck <peckn@amazon.com> Co-authored-by: Stephen Nutbrown <steveswfc@gmail.com> Co-authored-by: Andrew Chatfield <hellnation@gmail.com> Co-authored-by: Adam Ruka <adamruka@amazon.com> Co-authored-by: Clare Liguori <liguori@amazon.com> Co-authored-by: Pubudu Jayawardana <pubudusj@gmail.com> Co-authored-by: Shay Elmualem <wowshay@Gmail.com> Co-authored-by: sullis <github@seansullivan.com> Co-authored-by: Joseph Snell <joepsnell@gmail.com> Co-authored-by: Steven Bryen <726838+stevenbryen@users.noreply.github.com> Co-authored-by: Geoff Weinhold <gweinhold@gmail.com> Co-authored-by: StevenSu <suwei007@gmail.com> Co-authored-by: zanhsieh <zanhsieh@gmail.com> Co-authored-by: करतोफ्फेलस्क्रिप्ट™ <netroy@users.noreply.github.com> Co-authored-by: Josh Jay <josjaf@gmail.com> Co-authored-by: Rico Huijbers <huijbers@amazon.com> Co-authored-by: Trivikram Kamat <16024985+trivikr@users.noreply.github.com> Co-authored-by: curry9999 <curry123456789@gmail.com> Co-authored-by: mounick-mallow <52061259+mounick-mallow@users.noreply.github.com> Co-authored-by: Romain Marcadier-Muller <rmuller@amazon.com> Co-authored-by: Penghao He <penghaoh@amazon.com> Co-authored-by: Kasina <zechak@a483e77ecef5.ant.amazon.com> Co-authored-by: Wing-Kam <wingkwong.code@gmail.com> Co-authored-by: Mitchell Valine <valinm@amazon.com> Co-authored-by: Piotr Mlocek <pimlock@gmail.com> Co-authored-by: Srihari Prabaharan <srihariph@gmail.com> Co-authored-by: Mitchell Valine <mitchellvaline@gmail.com> Co-authored-by: zechariahks <zechariahks@outlook.com> Co-authored-by: Niranjan Jayakar <16217941+nija-at@users.noreply.github.com> Co-authored-by: Vinay Selvaraj <vinay@selvaraj.com> Co-authored-by: David Christian <dchristian3188@gmail.com> Co-authored-by: Ed Lima <awsed@users.noreply.github.com> Co-authored-by: no-brand <35508092+no-brand@users.noreply.github.com> Co-authored-by: Sarvesh <sarveshbhagat@gmail.com> Co-authored-by: Evan <esn89@users.noreply.github.com> Co-authored-by: Richard H Boyd <58230111+richardhboyd@users.noreply.github.com> Co-authored-by: huangzbaws <50089877+huangzbaws@users.noreply.github.com> Co-authored-by: Andreas Skarmutsos Lindh <andreas@superblock.se> Co-authored-by: Jigar Bhatt <60162196+jigar-lab@users.noreply.github.com> Co-authored-by: djiten75 <57147167+djiten75@users.noreply.github.com> Co-authored-by: netanir <neta1nir@gmail.com> Co-authored-by: Chris Nankervis <chris@nankervis.com> Co-authored-by: Campion Fellin <campionfellin@users.noreply.github.com> Co-authored-by: Benjamin E. Farr <benfarr@users.noreply.github.com> Co-authored-by: Nas Taibi <36194441+nataibi@users.noreply.github.com> Co-authored-by: Mohamed Elzarei <mohamed.elzarei@gmail.com> Co-authored-by: Shiv Lakshminarayan <shivlaks@amazon.com> Co-authored-by: ColWillis <col.willis@gmail.com>
1 parent ffae700 commit b8b10ed

File tree

8 files changed

+365
-0
lines changed

8 files changed

+365
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,10 @@ $ cdk destroy
4949
| [ecs-service-with-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/ecs-service-with-logging/) | Starting a container fronted by a load balancer on ECS |
5050
| [fargate-service-with-logging](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-logging/) | Starting a container fronted by a load balancer on Fargate |
5151
| [custom-logical-names](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/custom-logical-names/) | Example of how to override logical name allocation |
52+
| [fargate-service-with-efs](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/fargate-service-with-efs/) | Starting a container fronted by an application load balancer on Fargate with an EFS Mount |
5253
| [http-proxy-apigateway](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/http-proxy-apigateway/) | Use ApiGateway to set up a http proxy |
5354

55+
5456
## Java examples <a name="Java"></a>
5557

5658
To run the Java examples:
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Fargate Service using EFS
2+
This example creates a Public Facing load balanced Fargate service with an EFS Filesystem mount to demo the
3+
recently added feature to Fargate.
4+
5+
Is based on this blog post: https://aws.amazon.com/blogs/aws/amazon-ecs-supports-efs/
6+
7+
Also gives examples of using the following:
8+
9+
* AWS SDK Api call Custom resource to create Efs Access Point (not currently supported by cfn)
10+
* Lambda Custom Resource to create ECS TaskDefinition with EFS Mount (not currently supported by cfn) & initiate an update of the service
11+
* Cfn property override to set Fargate Service' PlatformVersion' to '1.4.0' (not currently tagged as Latest)
12+
13+
14+
## Build
15+
16+
To build this app, you need to be in this example's root folder. Then run the following:
17+
18+
```bash
19+
npm install -g aws-cdk
20+
npm install
21+
npm run build
22+
```
23+
24+
This will install the necessary CDK, then this example's dependencies, and then build your TypeScript files and your CloudFormation template.
25+
26+
## Deploy
27+
28+
Run `cdk deploy`. This will deploy / redeploy your Stack to your AWS Account.
29+
30+
After the deployment you will see the API's URL, which represents the url you can then use.
31+
32+
## Synthesize Cloudformation Template
33+
34+
To see the Cloudformation template generated by the CDK, run `cdk synth`, then check the output file in the "cdk.out" directory.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"app": "node index"
3+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import * as lambda from '@aws-cdk/aws-lambda';
2+
import * as cdk from '@aws-cdk/core';
3+
import * as iam from '@aws-cdk/aws-iam';
4+
import * as cr from '@aws-cdk/custom-resources';
5+
import fs = require('fs');
6+
7+
8+
export interface FargateEfsCustomResourceProps {
9+
/**
10+
* Custom Resource Properties
11+
*/
12+
TaskDefinition: string;
13+
EcsService: string;
14+
EcsCluster: string;
15+
EfsFileSystemId: string;
16+
EfsMountName: string
17+
}
18+
19+
20+
export class FargateEfsCustomResource extends cdk.Construct {
21+
public readonly response: string;
22+
23+
constructor(scope: cdk.Construct, id: string, props: FargateEfsCustomResourceProps) {
24+
super(scope, id);
25+
26+
const onEvent = new lambda.SingletonFunction(this, 'Singleton', {
27+
uuid: 'f7d4f730-4ee1-11e8-9c2d-fa7ae01bbebc',
28+
code: new lambda.InlineCode(fs.readFileSync('lambda.js', { encoding: 'utf-8' })),
29+
handler: 'index.handler',
30+
timeout: cdk.Duration.seconds(300),
31+
runtime: lambda.Runtime.NODEJS_12_X,
32+
initialPolicy:[
33+
new iam.PolicyStatement({
34+
actions: [ 'ecs:UpdateService', 'ecs:RegisterTaskDefinition', 'ecs:DescribeTaskDefinition', 'iam:PassRole', 'iam:GetRole' ],
35+
resources: [ '*' ]
36+
})
37+
]
38+
});
39+
40+
const myProvider = new cr.Provider(this, 'MyProvider', {
41+
onEventHandler: onEvent
42+
});
43+
44+
const resource = new cdk.CustomResource(this, 'Resource1', {
45+
serviceToken: myProvider.serviceToken,
46+
properties: props
47+
});
48+
49+
this.response = resource.getAtt('Response').toString();
50+
}
51+
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import * as cdk from '@aws-cdk/core';
2+
import * as ec2 from '@aws-cdk/aws-ec2';
3+
import * as ecs from '@aws-cdk/aws-ecs';
4+
import * as ecs_patterns from '@aws-cdk/aws-ecs-patterns';
5+
import * as efs from '@aws-cdk/aws-efs';
6+
import * as cr from '@aws-cdk/custom-resources';
7+
import {FargateEfsCustomResource} from "./efs-mount-fargate-cr";
8+
9+
10+
11+
class FargateEfs extends cdk.Stack {
12+
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
13+
super(scope, id, props);
14+
15+
const vpc = new ec2.Vpc(this, 'DefaultVpc', { maxAzs: 2});
16+
const ecsCluster = new ecs.Cluster(this, 'DefaultEcsCluster', {vpc: vpc});
17+
18+
const fileSystem = new efs.FileSystem(this, 'MyEfsFileSystem', {
19+
vpc: vpc,
20+
encrypted: true,
21+
lifecyclePolicy: efs.LifecyclePolicy.AFTER_14_DAYS,
22+
performanceMode: efs.PerformanceMode.GENERAL_PURPOSE,
23+
throughputMode: efs.ThroughputMode.BURSTING
24+
});
25+
26+
27+
const params = {
28+
FileSystemId: fileSystem.fileSystemId,
29+
PosixUser: {
30+
Gid: 1000,
31+
Uid: 1000
32+
},
33+
RootDirectory: {
34+
CreationInfo: {
35+
OwnerGid: 1000,
36+
OwnerUid: 1000,
37+
Permissions: '755'
38+
},
39+
Path: '/uploads'
40+
},
41+
Tags: [
42+
{
43+
Key: 'Name',
44+
Value: 'ecsuploads'
45+
}
46+
]
47+
};
48+
49+
const efsAccessPoint = new cr.AwsCustomResource(this, 'EfsAccessPoint', {
50+
onUpdate: {
51+
service: 'EFS',
52+
action: 'createAccessPoint',
53+
parameters: params,
54+
physicalResourceId: cr.PhysicalResourceId.of('12121212121'),
55+
},
56+
policy: cr.AwsCustomResourcePolicy.fromSdkCalls({resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE})
57+
});
58+
59+
efsAccessPoint.node.addDependency(fileSystem);
60+
61+
const taskDef = new ecs.FargateTaskDefinition(this, "MyTaskDefinition", {
62+
memoryLimitMiB: 512,
63+
cpu: 256,
64+
});
65+
66+
const containerDef = new ecs.ContainerDefinition(this, "MyContainerDefinition", {
67+
image: ecs.ContainerImage.fromRegistry("coderaiser/cloudcmd"),
68+
taskDefinition: taskDef
69+
});
70+
71+
containerDef.addPortMappings({
72+
containerPort: 8000
73+
});
74+
75+
const albFargateService = new ecs_patterns.ApplicationLoadBalancedFargateService(this, 'Service01', {
76+
cluster: ecsCluster,
77+
taskDefinition: taskDef,
78+
desiredCount: 2
79+
});
80+
81+
albFargateService.targetGroup.setAttribute('deregistration_delay.timeout_seconds', '30');
82+
83+
// Override Platform version (until Latest = 1.4.0)
84+
const albFargateServiceResource = albFargateService.service.node.findChild('Service') as ecs.CfnService;
85+
albFargateServiceResource.addPropertyOverride('PlatformVersion', '1.4.0')
86+
87+
// Allow access to EFS from Fargate ECS
88+
fileSystem.connections.allowDefaultPortFrom(albFargateService.service.connections);
89+
90+
//Custom Resource to add EFS Mount to Task Definition
91+
const resource = new FargateEfsCustomResource(this, 'FargateEfsCustomResource', {
92+
TaskDefinition: taskDef.taskDefinitionArn,
93+
EcsService: albFargateService.service.serviceName,
94+
EcsCluster: ecsCluster.clusterName,
95+
EfsFileSystemId: fileSystem.fileSystemId,
96+
EfsMountName: 'uploads'
97+
});
98+
99+
resource.node.addDependency(albFargateService);
100+
}
101+
}
102+
103+
const app = new cdk.App();
104+
new FargateEfs(app, 'FargateEfsDemo01');
105+
app.synth();
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
var AWS = require('aws-sdk');
2+
var ecs = new AWS.ECS();
3+
4+
exports.handler = function(event, context, callback) {
5+
6+
var taskDefParams = {
7+
taskDefinition: event["ResourceProperties"]["TaskDefinition"],
8+
};
9+
10+
var ecsParams = {
11+
service: event["ResourceProperties"]["EcsService"],
12+
cluster: event["ResourceProperties"]["EcsCluster"]
13+
};
14+
15+
var volume = {
16+
name: event["ResourceProperties"]["EfsMountName"],
17+
efsVolumeConfiguration: { fileSystemId: event["ResourceProperties"]["EfsFileSystemId"], rootDirectory: '/' }
18+
};
19+
20+
var mountPoint = {
21+
sourceVolume: event["ResourceProperties"]["EfsMountName"],
22+
containerPath: '/' + event["ResourceProperties"]["EfsMountName"],
23+
readOnly: false
24+
};
25+
26+
console.log(event);
27+
console.log(event["ResourceProperties"]);
28+
try {
29+
console.log("Getting Task Definition");
30+
ecs.describeTaskDefinition(taskDefParams, function(err, data) {
31+
if (err)
32+
console.log(err, err.stack);
33+
else
34+
data['taskDefinition']['volumes'].push(volume);
35+
data['taskDefinition']['containerDefinitions'][0]['mountPoints'].push(mountPoint);
36+
delete data['taskDefinition']['taskDefinitionArn'];
37+
delete data['taskDefinition']['revision'];
38+
delete data['taskDefinition']['status'];
39+
delete data['taskDefinition']['requiresAttributes'];
40+
delete data['taskDefinition']['compatibilities'];
41+
42+
console.log("Register New Task Definition");
43+
ecs.registerTaskDefinition(data['taskDefinition'], function(err, data) {
44+
if (err)
45+
console.log(err, err.stack);
46+
else
47+
console.log(data);
48+
console.log("Update Service");
49+
ecs.updateService({
50+
service: ecsParams['service'],
51+
cluster: ecsParams['cluster'],
52+
taskDefinition: data['taskDefinition']['taskDefinitionArn'],
53+
54+
},
55+
function (err, data) {
56+
if (err)
57+
console.log(err, err.stack);
58+
else
59+
console.log(data);
60+
sendResponse(event, context, 'SUCCESS', { 'Message': 'Resource creation successful!' });
61+
});
62+
console.log(data);
63+
});
64+
});
65+
} catch (e) {
66+
console.log('Errors' + e);
67+
sendResponse(event, context, 'FAILED')
68+
}
69+
};
70+
71+
72+
// Send response to the pre-signed S3 URL
73+
function sendResponse (event, context, responseStatus, responseData) {
74+
console.log('Sending response ' + responseStatus);
75+
var responseBody = JSON.stringify({
76+
Status: responseStatus,
77+
Reason: 'See the details in CloudWatch Log Stream: ' + context.logStreamName,
78+
PhysicalResourceId: context.logStreamName,
79+
StackId: event.StackId,
80+
RequestId: event.RequestId,
81+
LogicalResourceId: event.LogicalResourceId,
82+
Data: responseData
83+
});
84+
85+
console.log('RESPONSE BODY:\n', responseBody);
86+
87+
var https = require('https');
88+
var url = require('url');
89+
90+
var parsedUrl = url.parse(event.ResponseURL);
91+
var options = {
92+
hostname: parsedUrl.hostname,
93+
port: 443,
94+
path: parsedUrl.path,
95+
method: 'PUT',
96+
headers: {
97+
'content-type': '',
98+
'content-length': responseBody.length
99+
}
100+
};
101+
102+
console.log('SENDING RESPONSE...\n');
103+
104+
var request = https.request(options, function (response) {
105+
console.log('STATUS: ' + response.statusCode);
106+
console.log('HEADERS: ' + JSON.stringify(response.headers));
107+
// Tell AWS Lambda that the function execution is done
108+
context.done()
109+
});
110+
111+
request.on('error', function (error) {
112+
console.log('sendResponse Error:' + error);
113+
// Tell AWS Lambda that the function execution is done
114+
context.done()
115+
});
116+
117+
// write data to request body
118+
request.write(responseBody);
119+
request.end()
120+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"name": "fargate-service-with-efs",
3+
"version": "1.0.0",
4+
"description": "Running a load balanced service on ECS with EFS",
5+
"private": true,
6+
"scripts": {
7+
"build": "tsc",
8+
"watch": "tsc -w",
9+
"cdk": "cdk"
10+
},
11+
"author": {
12+
"name": "Amazon Web Services",
13+
"url": "https://aws.amazon.com",
14+
"organization": true
15+
},
16+
"license": "Apache-2.0",
17+
"devDependencies": {
18+
"@types/node": "^8.10.38",
19+
"typescript": "^3.9.5"
20+
},
21+
"dependencies": {
22+
"@aws-cdk/aws-ec2": "*",
23+
"@aws-cdk/aws-ecs": "*",
24+
"@aws-cdk/aws-ecs-patterns": "*",
25+
"@aws-cdk/aws-efs": "*",
26+
"@aws-cdk/core": "*",
27+
"@aws-cdk/custom-resources": "*"
28+
}
29+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"compilerOptions": {
3+
"target":"ES2018",
4+
"module": "commonjs",
5+
"lib": ["es2016", "es2017.object", "es2017.string"],
6+
"strict": true,
7+
"noImplicitAny": true,
8+
"strictNullChecks": true,
9+
"noImplicitThis": true,
10+
"alwaysStrict": true,
11+
"noUnusedLocals": true,
12+
"noUnusedParameters": true,
13+
"noImplicitReturns": true,
14+
"noFallthroughCasesInSwitch": false,
15+
"inlineSourceMap": true,
16+
"inlineSources": true,
17+
"experimentalDecorators": true,
18+
"strictPropertyInitialization":false
19+
}
20+
}
21+

0 commit comments

Comments
 (0)