Uploading Files to S3

In this lesson, you will learn how to upload files to S3 by modifying the template file.

You added a web-site directory to your project, with static web assets. Before you can deploy the new version of the application, you need to send those assets to S3 and replace the placeholder for the API URL in the index file.

At the time this was written, CloudFormation didn’t have any built-in support for sending web asset files to S3. However, there is a component in the AWS Serverless Application Repository that can handle simple uploads to S3, which is just what you need to deploy everything at the same time. DeployToS3, created by Aleksandar Simović, can upload files to S3 and optionally replace patterns in those files with CloudFormation references. That component will make it very easy to coordinate API Gateway updates and static website assets. Import the component into the application template by adding it to the Resources section. The code from the following listing will be added and indented so it aligns with existing resources (for example ConvertFileFunction).

Press + to interact
DeployToS3:
Type: AWS::Serverless::Application
Properties:
Location:
ApplicationId: arn:aws:serverlessrepo:us-east-1:375983427419:applications/deploy-to-s3
SemanticVersion: 1.0.0

CloudFormation and SAM can only package files from a local directory for Lambda functions. DeployToS3 abuses the Lambda packaging process slightly to trick CloudFormation into collecting files from a local directory with web assets and uploading them to S3.

In order for CloudFormation to package the web-site directory files, you need to make it think it’s collecting the source code for a Lambda function. For that, you just need to create another AWS::Serverless:Function resource and point it to the local directory. That function, of course, won’t be able to run, because it does not contain executable code or a Lambda handler. Also, the files will be, in that case, deployed to a Lambda container, not to S3. That’s where the DeployToS3 component comes in. It contains a Lambda layer with a Python function handler. When you attach the layer to the fake Lambda function, it will make the function executable. Once the ...