Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Write A Text String To An AWS S3 File In Rust

Code

```cargo
[dependencies]
aws-config = "1.1.9"
aws-sdk-s3 = "1.21.0"
tokio = { version = "1", features = ["full"] }
```

use aws_sdk_s3 as s3;

#[::tokio::main]
async fn main() {

  let provider = aws_config::profile::ProfileFileCredentialsProvider::builder()
    .profile_name("Blog_Example_Profile")
    .build();

  let config = aws_config::defaults(aws_config::BehaviorVersion::v2023_11_09())
    .credentials_provider(provider)
    .load()
    .await;

  let body = "The quick brown fox".to_string();
  let bucket = "aws-test-sandbox".to_string();
  let key = "rust-sdk-test/example.txt".to_string();

  match upload_text_to_s3(&config, &body, &bucket, &key).await {
    Ok(_) => println!("Content uploaded"),
    Err(e) => println!("Error: {}", e)
  };
}

async fn upload_text_to_s3(
    config: &aws_config::SdkConfig, 
    body: &str, 
    bucket: &str, 
    key: &str
  ) -> Result<(), s3::Error> {
    let client = s3::Client::new(&config);
    let bytes = s3::primitives::ByteStream::new(s3::primitives::SdkBody::from(body));
    let _ = client.put_object().bucket(bucket).key(key).body(bytes).send().await?;
    Ok(())
}
  • This sends a string of text to a file in AWS S3

  • The config details are loaded from a named profile in the `~/.aws/config`` and `~/.aws/credentails`` files.

  • The `~/.aws/credentails`` file has an entry for `[Blog_Example_Profile]`` with my AWS credentails.

  • The `~/.aws/config`` file has a corresponding profile that sets the region like this:

    [Blog_Example_Profile] region = us-east-1

  • Some of the AWS SDK Examples show using `.region()`` in the config chain like: `aws_config::defaults(...).credentials_provider(provider).region("us-east-1").load().await;``

    Or, using aws_config::meta::region::RegionProviderChain. My setup doesn't need that, but yours might if you don't set the region in the `~/.aws/config`` file or something else is different in the set up.

References