anacunha / rust-on-aws

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rust on AWS

Prerequisites

You will need to create an AWS accounts and setup your access keys. Follow the instructions here.

AWS Rust SDK

Upload file to Amazon S3 bucket

  1. Create new project
cargo new aws_rust_sdk
  1. Add dependencies (tokio, aws-config, aws-sdk-s3)
cargo add tokio@1 --features full
cargo add aws-config
cargo add aws-sdk-s3

Your dependencies on Cargo.toml will look like this:

[dependencies]
aws-config = "0.48.0"
aws-sdk-s3 = "0.18.0"
tokio = { version = "1", features = ["full"] }
  1. We will use tokio as our asynchronous runtime:
#[tokio::main]
async fn main() {
  // Our code will go here
}
  1. Create an SdkConfig by loading the default configuration from the environment:
let config = aws_config::load_from_env().await;
  1. Create and aws_sdk_s3::Client:
let client = aws_sdk_s3::Client::new(&config);
  1. Create a ByteStream from the file that will be uploaded:
let body = aws_sdk_s3::types::ByteStream::from_path(std::path::Path::new("test.txt")).await;
  1. Create a PutObject request:
let response = client
    .put_object()
    .bucket("bucket-name")
    .key("key")
    .body(body.unwrap())
    .send()
    .await?;
  1. Get the object version:
let version = response.version_id().unwrap();
println!("Uploaded file version {}", version);

Our entire main.rs file will look like this:

use aws_sdk_s3::{types::ByteStream, Client, Error};
use std::path::Path;

#[tokio::main]
async fn main() -> Result<(), Error> {
    let config = aws_config::load_from_env().await;
    let client = Client::new(&config);

    let body = ByteStream::from_path(Path::new("test.txt")).await;

    let response = client
        .put_object()
        .bucket("tech-day-ifood")
        .key("demo")
        .body(body.unwrap())
        .send()
        .await?;

    let version = response.version_id().unwrap();
    println!("Uploaded file version {}", version);

    Ok(())
}

AWS Lambda Rust Runtime

  1. Install cargo-lambda
brew tap cargo-lambda/cargo-lambda
brew install cargo-lambda
  1. Create a function
cargo lambda new FUNCTION_NAME
  1. Build
cargo lambda build --release
cargo lambda build --release --arm64
  1. Deploy
cargo lambda deploy \
  --iam-role arn:aws:iam::XXXXXXXXXXXXX:role/your_lambda_execution_role
  1. Test
cargo lambda invoke --remote \
  --data-ascii '{"command": "hi"}' \
  --output-format json \
  FUNCTION_NAME

Links

Blogs

Videos

About