Bootstrap Rust Template
How to create a new Rust project using AWS SAM
What you'll learn
- How to create a new Rust project using AWS SAM
Now that you've got your environment set up, it's time to actually build something. Starting from a clean template is much better than trying to guess what configuration files you're missing.
We're going to use the AWS SAM CLI to bootstrap our project. It handles the "scaffolding" the folders, the basic code, and the cloud configuration so we can jump straight into the logic.
SAM init
Open your terminal and run the initialization command. AWS SAM is interactive, so it will ask you a few questions.
sam initHere are the choices I usually make to get a solid Rust foundation:
- Which template source? Choose
1 - AWS Quick Start Templates. - Choose an application pattern? Choose
1 - Hello World Example. - Use the most modern runtime? Enter
N(we want to pick specifically). - Which runtime? Look for
rust (provided.al2023)or similar. Usually it's around option 22-23 depending on the version. - Would you like to enable X-Ray tracing on the function(s) in your application? Enter
N(we can enable it later if needed). - Would you like to enable monitoring using CloudWatch Application Insights? Enter
N(we can enable it later if needed). - Would you like to set Structured Logging in JSON format on your Lambda functions? Enter
y(it's just better for logs). - Project name Let's call it
rust-serverless-api.
You should see something like this:
-----------------------
Generating application:
-----------------------
Name: rust-serverless-api
Runtime: rust (provided.al2023)
Architectures: x86_64
Dependency Manager: cargo
Application Template: hello-world
Output Directory: .
Configuration file: rust-serverless-api/samconfig.toml
Next steps can be found in the README file at rust-serverless-api/README.md
Commands you can use next
=========================
[*] Create pipeline: cd rust-serverless-api && sam pipeline init --bootstrap
[*] Validate SAM template: cd rust-serverless-api && sam validate
[*] Test Function in the Cloud: cd rust-serverless-api && sam sync --stack-name {stack-name} --watchInfo
SAM will download a specific Rust template that uses Cargo Lambda under the hood
File Structure
Once the command finishes, you'll have a new folder called rust-serverless-api. And your file structure will look like this:
rust-serverless-api/
├── events/
│ └── event.json
├── rust_app/
│ ├── Cargo.toml
│ ├── src/
│ │ └── main.rs
├── README.md
├── samconfig.toml
└── template.yamlCongratulations, you now have a Rust project set up with AWS SAM. :)
Testing it out locally
Naaah, testing locally is kind of little complicated, so we're gonna skip it for now. because you are going to need Docker for that
Maybe in the future I'll write a post about it.
In the next post, we'll customize our file structure and necessary files to make things easier.