Export files to Microsoft Azure in Rust

⚠️ Important: Microsoft is developing the official Azure SDK for Rust crates and has no plans to update the current unofficial crates. A future official version may have different package names. Monitor https://aka.ms/azsdk/releases for official releases.
Rust's robust type system and memory safety guarantees make it an excellent choice for cloud storage operations. This guide demonstrates how to export files to Azure Blob Storage using the Azure SDK for Rust.
Prerequisites
- Rust 1.75+ (2021 edition)
- Cargo package manager
- Azure Storage account
- Environment variables:
AZURE_STORAGE_ACCOUNT=myaccount
AZURE_STORAGE_KEY=mykey
Project setup
Add these dependencies to your Cargo.toml
:
[dependencies]
tokio = { version = "1.32", features = ["rt-multi-thread", "macros"] }
azure_core = "0.21.0"
azure_storage = "0.21.0"
azure_storage_blobs = "0.21.0"
dotenv = "0.15"
Azure client initialization
The following example initializes the Azure Blob Storage client with credentials from your environment:
use azure_storage::core::prelude::*;
use azure_storage_blobs::prelude::*;
use dotenv::dotenv;
use std::env;
#[tokio::main]
async fn main() -> azure_core::Result<()> {
dotenv().ok();
let account = env::var("AZURE_STORAGE_ACCOUNT")
.expect("Missing AZURE_STORAGE_ACCOUNT environment variable");
let key = env::var("AZURE_STORAGE_KEY")
.expect("Missing AZURE_STORAGE_KEY environment variable");
let storage_credentials = StorageCredentials::Key(account.clone(), key);
let blob_service = BlobServiceClient::new(account, storage_credentials);
let container_name = "rust-exports";
let file_path = "data.txt";
upload_file(&blob_service, container_name, file_path).await?;
Ok(())
}
File upload implementation
This function uploads a file to a specified container. The Azure SDK for Rust handles chunking and parallel uploads automatically.
use azure_storage_blobs::blob::responses::PutBlockBlobResponse;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
async fn upload_file(
blob_service: &BlobServiceClient,
container_name: &str,
file_path: &str,
) -> azure_core::Result<()> {
let container_client = blob_service.container_client(container_name);
let blob_name = file_path.split('/').last().unwrap_or("unnamed");
let blob_client = container_client.blob_client(blob_name);
let mut file = File::open(file_path).await?;
let mut contents = Vec::new();
file.read_to_end(&mut contents).await?;
blob_client
.put_block_blob(contents)
.content_type("application/octet-stream")
.await?;
println!("Successfully uploaded '{}' to container '{}'", blob_name, container_name);
Ok(())
}
Error handling
Configure custom retry options to improve robustness for network timeouts and transient errors:
use azure_core::RetryOptions;
use std::time::Duration;
let retry_options = RetryOptions::default()
.with_max_retries(3)
.with_initial_retry_delay(Duration::from_secs(1));
let blob_client = /* your blob client instance */;
let blob_client = blob_client.with_retry_options(retry_options);
Best practices
- Authenticate securely by using environment variables or Azure CLI credentials.
- Leverage the builder pattern provided by the SDK for client configuration.
- Implement robust error handling with proper retry logic using
azure_core::Result
. - Use HTTPS for all connections and regularly rotate your storage keys.
- Monitor Azure Storage metrics and adjust performance settings as needed.
Production considerations
- Monitor uploaded files and storage properties:
use azure_storage_blobs::prelude::*;
let properties = blob_client.get_properties().await?;
println!("Content length: {}", properties.content_length);
println!("Content type: {}", properties.content_type);
- Manage your container efficiently by creating it if it does not exist:
use azure_storage_blobs::prelude::*;
use azure_storage::core::prelude::PublicAccess;
let container_client = blob_service.container_client("rust-exports");
container_client
.create()
.public_access(PublicAccess::None)
.await?;
- Consider implementing blob lifecycle policies and container naming conventions to streamline data management.
This implementation provides a foundation for integrating Azure Blob Storage with Rust applications. The Azure SDK for Rust simplifies cloud storage operations by handling many complexities under the hood.
For a production-ready solution with enhanced error handling and progress tracking, consider using Transloadit's Azure export Robot alongside your Rust workflows.