With a profile set up, we can take advantage of the AWS Rust SDK to use those profiles in our application.
First add the aws_config
crate to the local upload-pokemon-data
package. We’ll also need tokio
, so we’ll add that now too.
cargo add -p upload-pokemon-data aws_config tokio
Make sure to enable the full
feature for tokio
in the upload-pokemon-data
Cargo.toml
. This enables a large set of the tokio optional features, including the macros which we’ll use soon.
[dependencies]
aws-config = "0.9.0"
tokio = { version = "1.17.0", features = ["full"] }
The aws-config
crate includes a from_env
function that we can use to load credentials from the environment. This works for our local development environment on our computer as well as places like lambda functions.
#[tokio::main]
async fn main() -> eyre::Result<()> {
color_eyre::install()?;
let config = aws_config::from_env().load().await;
dbg!(config.region());
...
Ok(())
}
The .load()
function is async, so we have to await
it, but we also have to make our main
function async to be able to await
it, as we can’t use await
unless we’re inside of an async function.
Tokio helps us our here with the tokio::main
macro, which rewrites our async main function into a regular main function that bootstraps the tokio async runtime.
The SdkConfig
type, which is what config
is, is a fairly large struct. The fields are mostly private and not meant to be accessed directly, so we can use dbg!(config.region());
to see if our profile is being used.
It is likely that if you cargo run
your application now, you will get a region of None
, which means that we didn’t set one.
Finished dev [unoptimized + debuginfo] target(s) in 1.24s
Running `target/debug/upload-pokemon-data`
[crates/upload-pokemon-data/src/main.rs:10] config.region() = None
To use our profile, we can use the environment variable AWS_PROFILE
to select the profile we want to use.
AWS_PROFILE=rust-adventure-playground cargo run
My profile name is rust-adventure-playground
so that’s what I used here. The region should now log out as the region set in your profile’s config. In my case this is us-east-1
.
AWS has many datacenters in many locations, and the region is which datacenter we intend to deploy our data/function/etc to.
[crates/upload-pokemon-data/src/main.rs:10] config.region() = Some(
Region(
"us-east-1",
),
)