One subtle thing that you do when working with AWS SAM is that you upload the Lambda deployment packages (artifacts) to a staging bucket where Lambda service retrieve these packages. After the artifacts were retrieved by AWS Lambda from S3, those packages often stay in the staging bucket and may build up over time especially for large projects with tons of Lambda functions. This often results to a slow and steady increase in S3 bills over time.

In this article, we will explore what are the common techniques available to reduce the cost generated by the build up of SAM deployment artifacts.

Option 1: Add a 1-day Expiry Rule for Dev Environment Artifacts

Deployment artifacts for development environments are basically non-valuable to an organization, it doesn’t allow developers to extract useful debugging information out of them except from cases where you really need to inspect the packages. To help your organization reduce cost, you can configure your development artifact storage for S3 bucket to implement an object lifecycle management rule that will expire any build that is older than one day. You can use the following Cloud Formation template to achieve this:

AWSTemplateFormatVersion: "2010-09-09"
	Description: >
	  CloudFormation template used for provisioning SAM artifact storage for environments 
	  that require rapid expiration of build artifacts.
	Parameters:
	  AppName:
	    Type: String
	    Description: "Name of application."
	    AllowedPattern: ".+"
	    Default: "ninja-buckets"

	  Environment:
	    Type: String
	    Description: "Environment code of deployment (dev, uat, prod)"
	    AllowedPattern: ".+"
	    AllowedValues:
	      - "dev"
	      - "uat"
	      - "prod"

	Resources:
	  SamArtifactStorage:
	    Type: AWS::S3::Bucket
	    Properties:
	      BucketName: !Join ["-", [!Ref AppName, !Ref Environment, "sam-artifacts"]]
	      LifecycleConfiguration:
	        Rules:
	          - Id: DeleteDevArtifactsAfterOneDay
	            Status: "Enabled"
	            ExpirationInDays: 1
	      BucketEncryption:
	        ServerSideEncryptionConfiguration:
	          - ServerSideEncryptionByDefault:
	              SSEAlgorithm: AES256
	      Tags:
	        - Key: "ENVIRONMENT"
	          Value: !Ref Environment
	        - Key: "APP"
	          Value: !Ref AppName

#cloudformation #aws-lambda #serverless #s3 #aws

How to Reduce Cost of SAM Artifact Storage using S3 Lifecyle Management & Cloud Formation
1.25 GEEK