-
Minimal SAM template image function definition
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: Minimal lambda containers example Parameters: Namespace: Type: String Default: '' Resources: ContainerFunction: Type: AWS::Serverless::Function Metadata: Dockerfile: Dockerfile DockerContext: ./lambda Properties: FunctionName: !Sub "ContainerFunction${Namespace}" PackageType: Image Timeout: 900 MemorySize: 10240
-
Dockerfile in the folder defined by
Metadata. ├── Makefile ├── README.md ├── lambda │ ├── Dockerfile │ ├── index.js │ └── package.json └── template.yaml- can be in a different directory also
-
Dockerfile
FROM public.ecr.aws/lambda/nodejs:12 RUN yum install ImageMagick-devel -y COPY ./* ./ RUN npm install CMD [ "./index.lambdaHandler"]
- the dockerfile will reference an aws lambda container
FROM public.ecr.aws/lambda/nodejs:12and extend it with own dependencies CMD [ "./index.lambdaHandler"]runs the executable on lambda invoke
- the dockerfile will reference an aws lambda container
-
Build and Deploy
make create_repository- run only oncemake deploy- builds and deploys
-
make create_repositoryaccount=$(aws sts get-caller-identity | jq --raw-output .Account) aws ecr create-repository --repository-name container-lambda --image-scanning-configuration scanOnPush=true- makes sure the ecr image repository exists in account
- the
--repository-nameparameter set to the ecr repo you want to create, in this casecontainer-lambda, you will use the repo url in the package and deploy SAM commands
-
make buildsam build- sam handles building the container with docker for you
-
make packagesam package --s3-bucket $$BUCKET --image-repository $$ACCOUNT.dkr.ecr.us-east-1.amazonaws.com/container-lambda- runs package the built files and stage in ecr and s3
-
make deploysam deploy \ --s3-bucket $$BUCKET \ --image-repository $$ACCOUNT.dkr.ecr.us-east-1.amazonaws.com/container-lambda \ --stack-name LambdaContainers-mike \ --capabilities CAPABILITY_NAMED_IAM \ --no-fail-on-empty-changeset --tags logical_name=LambdaContainers-mike
- runs sam deploy which launches the stack
- the
--image-repositoryis required for functions withPackageType: Image - the
--s3-bucketis required for large templates (not in this case but leaving it in for extending in the future) - the
--tagsparameter with thelogical_nametag tags the stack resources for cost explorer and is our convention
-
make testaws lambda invoke --function-name "ContainerFunction" --payload '{}' out.json && cat out.json && rm out.json- invokes lambda function and prints the response