Skip to main content

Rust 1.92.0 (CentOS Stream 9) AMI Administrator Guide

1. Quick Start Information​

Connection Methods:

  • Access the instance via SSH using the ec2-user user. Use sudo to run commands requiring root privileges. To switch to the root user, use sudo su - root.

Install Information:

  • OS: CentOS Stream 9
  • Rust version: 1.92.0
  • Cargo version: 1.92.0
  • Rust Compiler: /usr/bin/rustc
  • Cargo Package Manager: /usr/bin/cargo

Quick Verification Commands:

  • Check Rust version: rustc --version
  • Check Cargo version: cargo --version
  • Check cargo-audit: cargo audit --version
  • Check ripgrep: rg --version

Development Tools Included:

  • Rust Compiler: rustc (1.92.0)
  • Cargo Package Manager: cargo (1.92.0)
  • cargo-audit: Security vulnerability scanner (0.22.1)
  • ripgrep: Fast grep alternative (14.1.1)
  • OpenSSL Development Libraries: For HTTPS and crypto support

Firewall Configuration:

  • Please allow SSH port 22.
  • For security, it is recommended to limit SSH access to trusted IPs only.

2. Overview​

Welcome to this Rust 1.92.0 AMI. This image is based on CentOS Stream 9 and provides a complete, production-ready development environment for building fast, reliable, and memory-safe systems software.

This guide explains how to use this AMI and details its internal configuration.

What is Rust?

Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. It accomplishes these goals through its unique ownership system, zero-cost abstractions, and powerful type system. Rust is used for operating systems, game engines, web servers, embedded systems, and blockchain applications.

Core Features of This AMI:

  • Rust 1.92.0: Latest stable release from Red Hat official repository
  • Cargo 1.92.0: Built-in package manager and build system
  • cargo-audit: Security vulnerability scanner for dependencies
  • ripgrep: Blazingly fast search tool (written in Rust)
  • OpenSSL Support: Development libraries for HTTPS and cryptographic operations
  • Development Tools: Complete gcc, make toolchain for linking

Target Use Cases:

  • Building command-line tools and system utilities
  • Developing web servers and microservices (using Actix, Rocket, Axum)
  • Creating embedded systems and IoT applications
  • Building WebAssembly modules
  • Systems programming (OS components, drivers)
  • High-performance data processing

3. First Launch & Verification​

Step 1: Connect to Your Instance​

  1. Launch your instance in your cloud provider's console (e.g., AWS EC2)
  2. Ensure SSH port 22 is allowed in your security group
  3. Connect via SSH:
    ssh -i your-key.pem ec2-user@YOUR_PUBLIC_IP

Step 2: Verify Rust Installation​

Check the Rust compiler version:

rustc --version

Expected Output:

rustc 1.92.0 (ded5c06cf 2025-12-08) (Red Hat 1.92.0-1.el9)

Check Cargo package manager:

cargo --version

Expected Output:

cargo 1.92.0 (344c4567c 2025-10-21) (Red Hat 1.92.0-1.el9)

Step 3: Verify Development Tools​

Check cargo-audit:

cargo audit --version

Expected Output:

cargo-audit-audit 0.22.1

Check ripgrep:

rg --version

Expected Output:

ripgrep 14.1.1

features:+pcre2
simd(compile):+SSE2,+SSSE3,-AVX2
simd(runtime):+SSE2,+SSSE3,+AVX2

PCRE2 10.43 is available (JIT is available)

Step 4: Create and Run a Test Program​

Create a simple "Hello World" program:

mkdir -p ~/hello-rust
cd ~/hello-rust

Create main.rs:

cat > main.rs << 'EOF'
fn main() {
println!("Hello from Rust 1.92.0!");
}
EOF

Compile directly with rustc:

rustc main.rs
./main

Expected Output:

Hello from Rust 1.92.0!

Or use Cargo (recommended):

cd ~
cargo new hello-rust
cd hello-rust
cargo run

Expected Output:

   Compiling hello-rust v0.1.0 (/home/ec2-user/hello-rust)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.50s
Running `target/debug/hello-rust`
Hello, world!

Clean up:

cd ~
rm -rf ~/hello-rust

4. Architecture & Detailed Configuration​

4.1. Component Locations​

ComponentInstallation PathPurpose
Rust Compiler/usr/bin/rustcRust compiler executable
Cargo/usr/bin/cargoPackage manager and build tool
cargo-audit/usr/local/bin/cargo-auditSecurity vulnerability scanner
ripgrep/usr/bin/rgFast search tool
Cargo Home~/.cargo/User packages and registry cache
Cargo Config~/.cargo/config.tomlUser-specific cargo configuration

4.2. Installation Method​

This AMI uses the Red Hat official repository packages:

  • Source: CentOS Stream 9 AppStream repository
  • Why System Packages: Stable, tested, integrated with system updates
  • Alternative: Official rustup installer (not used here for simplicity)

Package Manager vs. rustup:

MethodSystem Packages (Used)rustup (Not Used)
Installationdnf install rust cargocurl ... | sh
Updatesdnf updaterustup update
Toolchain ManagementSingle versionMultiple versions
Best ForProduction serversDevelopment machines

4.3. Cargo Project Structure​

When you create a new project with cargo new, you get this structure:

my_project/
├── Cargo.toml # Project manifest (dependencies, metadata)
├── Cargo.lock # Dependency lock file (generated)
├── src/
│ └── main.rs # Main source file
└── target/ # Build output directory (generated)
├── debug/ # Debug builds (default)
└── release/ # Release builds (--release flag)

Cargo.toml Example:

[package]
name = "my_project"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

4.4. Development Dependencies​

The following system packages are required for Rust development:

Development Tools Group:
- gcc # C compiler (linker for Rust)
- g++ # C++ compiler
- make # Build automation
- autoconf # Configure script generator
- automake # Makefile generator

Additional Libraries:
- openssl-devel # HTTPS and crypto support

Why Development Tools:

Without gcc, Rust compilation will fail with:

error: linker 'cc' not found

Rust compiles to machine code but uses the system linker (cc/gcc) for the final linking step.


5. How-To-Create: Building This AMI from Scratch​

This section explains exactly how this AMI was created, allowing you to:

  • Understand the configuration
  • Reproduce the setup on other systems
  • Customize the installation

Step 1: System Preparation​

Update the system:

sudo dnf update -y

Why Update:

Ensures all base packages are at their latest security patches before installing development tools.

Step 2: Install Development Tools​

Install the Development Tools group:

sudo dnf groupinstall -y "Development Tools"

What Gets Installed:

This group includes approximately 50 packages:

  • gcc: GNU C Compiler
  • g++: GNU C++ Compiler
  • make: Build automation tool
  • autoconf/automake: Build configuration tools
  • patch: Apply source patches
  • rpm-build: RPM package building tools

Critical Importance:

Without this, Rust will fail to compile even the simplest program because it cannot find the system linker.

Step 3: Install Rust and Cargo​

Install Rust compiler and Cargo from Red Hat repository:

sudo dnf install -y rust cargo

What Gets Installed:

  • rust package: Includes rustc compiler, standard library
  • cargo package: Package manager, build tool, test runner

Package Details:

Package: rust-1.92.0-1.el9.x86_64
Size: ~50 MB
Dependencies: gcc, glibc-devel, libgcc

Verify installation:

rustc --version
cargo --version

Expected Output:

rustc 1.92.0 (ded5c06cf 2025-12-08) (Red Hat 1.92.0-1.el9)
cargo 1.92.0 (344c4567c 2025-10-21) (Red Hat 1.92.0-1.el9)

Step 4: Install OpenSSL Development Libraries​

Install OpenSSL headers and libraries:

sudo dnf install -y openssl-devel

Why OpenSSL:

Many Rust crates (packages) require OpenSSL for:

  • HTTPS connections (reqwest, hyper)
  • TLS encryption (tokio-tls, rustls)
  • Cryptographic operations (ring, openssl-sys)

Without openssl-devel, building these crates will fail with:

error: failed to run custom build command for `openssl-sys`

What Gets Installed:

  • /usr/include/openssl/: Header files
  • /usr/lib64/libssl.so: Shared libraries
  • /usr/lib64/libcrypto.so: Crypto libraries

Step 5: Install cargo-audit​

Install cargo-audit globally:

sudo cargo install cargo-audit --root /usr/local

Command Breakdown:

  • sudo: Run as root to write to /usr/local/bin/
  • cargo install: Download, compile, and install a Rust binary
  • cargo-audit: Package name from crates.io
  • --root /usr/local: Install to /usr/local/bin/ (not ~/.cargo/bin/)

What is cargo-audit:

cargo-audit is a security tool that:

  • Scans Cargo.lock for vulnerable dependencies
  • Checks against the RustSec Advisory Database
  • Reports CVEs and security advisories
  • Helps maintain secure supply chains

Compilation Time:

  • t3.micro (1 vCPU): ~5 minutes
  • t3.small (2 vCPU): ~3 minutes
  • t3.medium (4 vCPU): ~2 minutes

Verify installation:

cargo audit --version

Expected Output:

cargo-audit-audit 0.22.1

Step 6: Install ripgrep​

Install EPEL repository:

sudo dnf install -y epel-release

What is EPEL:

EPEL (Extra Packages for Enterprise Linux) provides additional packages not included in the base CentOS repository. ripgrep is available in EPEL.

Refresh package cache:

sudo dnf makecache

Install ripgrep:

sudo dnf install -y ripgrep

What is ripgrep:

ripgrep (command: rg) is a line-oriented search tool written in Rust that:

  • Searches recursively through directories
  • Respects .gitignore files automatically
  • Is 2-10x faster than grep
  • Supports regex patterns and literal strings

Why Include It:

  • Demonstrates Rust's performance capabilities
  • Extremely useful for searching code in large projects
  • Standard tool in modern development workflows

Verify installation:

rg --version

Expected Output:

ripgrep 14.1.1

features:+pcre2
simd(compile):+SSE2,+SSSE3,-AVX2
simd(runtime):+SSE2,+SSSE3,+AVX2

PCRE2 10.43 is available (JIT is available)

Features Explained:

  • +pcre2: Perl-compatible regex support
  • +SSSE3: SIMD optimizations for faster searching
  • JIT available: Just-In-Time regex compilation

Step 7: Cleanup (Critical for AMI Size)​

Remove root's cargo cache:

sudo rm -rf /root/.cargo/registry
sudo rm -rf /root/.cargo/git

Why This Matters:

When installing cargo-audit with sudo cargo install, Cargo downloads and caches:

  • crate source code (~50 MB)
  • Git repositories (~30 MB)
  • Compiled intermediate files (~100 MB)

Total Space Saved: ~180 MB

The compiled binary is already in /usr/local/bin/, so these caches serve no purpose in the final AMI.


6. Using the Development Environment​

6.1. Creating a New Project with Cargo​

Create a binary (executable) project:

cargo new my_app
cd my_app

Create a library project:

cargo new my_lib --lib
cd my_lib

Project Structure:

my_app/
├── Cargo.toml
└── src/
└── main.rs # For binary projects

my_lib/
├── Cargo.toml
└── src/
└── lib.rs # For library projects

6.2. Adding Dependencies​

Edit Cargo.toml to add dependencies:

[dependencies]
serde = "1.0"
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

Or use cargo add (Cargo 1.62+):

cargo add serde
cargo add serde_json
cargo add tokio --features full

Download dependencies:

cargo build

This:

  1. Downloads crates from crates.io
  2. Compiles dependencies
  3. Creates Cargo.lock with exact versions

6.3. Building and Running​

Run in development mode (with debug symbols):

cargo run

Build without running:

cargo build

Binary location: target/debug/my_app

Build optimized release version:

cargo build --release

Binary location: target/release/my_app

Performance Difference:

  • Debug build: Fast compilation, slow execution, ~2-10x slower
  • Release build: Slow compilation, fast execution, full optimizations

Run release version:

cargo run --release

6.4. Testing​

Create a test in src/main.rs:

#[cfg(test)]
mod tests {
#[test]
fn test_addition() {
assert_eq!(2 + 2, 4);
}
}

Run tests:

cargo test

Run specific test:

cargo test test_addition

Run tests with output:

cargo test -- --nocapture

6.5. Using cargo-audit​

Check for security vulnerabilities:

cargo audit

Sample Output:

    Fetching advisory database from `https://github.com/RustSec/advisory-db.git`
Loaded 500 security advisories (from /home/ec2-user/.cargo/advisory-db)
Scanning Cargo.lock for vulnerabilities (10 crate dependencies)
Crate: time
Version: 0.1.45
Warning: potential segfault in `time`
Title: Potential segfault in `time` crate
Date: 2020-11-18
ID: RUSTSEC-2020-0071
URL: https://rustsec.org/advisories/RUSTSEC-2020-0071

Fix vulnerabilities by updating dependencies:

cargo update
cargo audit

Generate audit report:

cargo audit --json > audit-report.json

Search for a pattern in current directory:

rg "fn main"

Search with case-insensitive:

rg -i "TODO"

Search specific file types:

rg "async" --type rust

Search and show context:

rg "error" -A 3 -B 3

Common Use Cases:

# Find all TODOs in Rust files
rg "TODO|FIXME" --type rust

# Find function definitions
rg "^fn \w+"

# Find all imports
rg "^use "

# Search excluding target directory
rg "pattern" --glob '!target/'

6.7. Formatting and Linting​

Format code with rustfmt:

cargo fmt

Check formatting without changing files:

cargo fmt -- --check

Lint code with clippy:

cargo clippy

Clippy will suggest improvements:

  • Performance optimizations
  • Idiomatic Rust patterns
  • Potential bugs
  • Code simplifications

Fix clippy warnings:

cargo clippy --fix

7. Important File Locations​

PathPurposeNotes
/usr/bin/rustcRust compilerSystem-wide installation
/usr/bin/cargoPackage managerSystem-wide installation
/usr/local/bin/cargo-auditSecurity scannerGlobally installed tool
/usr/bin/rgripgrep search toolFrom EPEL repository
~/.cargo/Cargo home directoryUser-specific packages and cache
~/.cargo/bin/User-installed binariesFrom cargo install
~/.cargo/registry/Downloaded crate cacheAuto-managed by Cargo
~/.cargo/git/Git dependency cacheAuto-managed by Cargo
~/.cargo/config.tomlCargo configurationOptional user config
target/Build outputIn each project directory

8. Troubleshooting​

Problem: error: linker 'cc' not found​

Cause: Development Tools not installed, gcc missing.

Solution:

# Install Development Tools
sudo dnf groupinstall -y "Development Tools"

# Verify gcc is available
which gcc

# Retry build
cargo build

Problem: failed to run custom build command for 'openssl-sys'​

Cause: OpenSSL development headers missing.

Solution:

# Install OpenSSL development libraries
sudo dnf install -y openssl-devel

# Clean build and retry
cargo clean
cargo build

Problem: cargo build is extremely slow​

Cause: Debug builds compile dependencies every time, or network is slow.

Solutions:

# Use offline mode if dependencies already downloaded
cargo build --offline

# Use release mode for faster execution (slower compilation)
cargo build --release

# Enable incremental compilation (default in dev mode)
# Add to Cargo.toml:
[profile.dev]
incremental = true

# Use more cores
cargo build -j 4

Problem: error: no default toolchain configured​

Cause: Using rustup-installed Rust, but toolchain not set (not applicable to this AMI).

Note: This AMI uses system packages, not rustup. This error shouldn't occur. If it does:

Solution:

# Verify rustc is from system packages
which rustc
# Should show: /usr/bin/rustc

# Check version
rustc --version
# Should show: (Red Hat 1.92.0-1.el9)

Problem: cargo audit reports vulnerabilities​

Cause: Dependencies have known security issues.

Solution:

# Update dependencies to latest compatible versions
cargo update

# Check again
cargo audit

# If still vulnerable, check if newer version available
cargo outdated

# Update Cargo.toml with newer versions
# Then:
cargo update
cargo build
cargo test

Problem: Out of disk space during build​

Cause: target/ directory grows large, cargo cache accumulates.

Solution:

# Clean current project
cargo clean

# Clean all cargo caches (use carefully)
rm -rf ~/.cargo/registry
rm -rf ~/.cargo/git

# Clean only old build artifacts
cargo cache --autoclean

Problem: cargo install fails with permission denied​

Cause: Trying to install to /usr/local/bin/ without sudo.

Solution:

# Install globally (requires sudo)
sudo cargo install package_name --root /usr/local

# Or install to user directory (no sudo needed)
cargo install package_name
# Binary goes to ~/.cargo/bin/

# Make sure ~/.cargo/bin is in PATH
echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

9. Advanced Topics​

9.1. Async Programming with Tokio​

Install Tokio runtime:

cargo add tokio --features full

Create an async HTTP server:

use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Server listening on port 8080");

loop {
let (mut socket, _) = listener.accept().await?;

tokio::spawn(async move {
let mut buffer = [0; 1024];
socket.read(&mut buffer).await.unwrap();
socket.write_all(b"HTTP/1.1 200 OK\r\n\r\nHello!").await.unwrap();
});
}
}

9.2. Building Web APIs with Actix​

Install Actix Web:

cargo add actix-web

Create a REST API:

use actix_web::{web, App, HttpServer, Responder};

async fn hello() -> impl Responder {
"Hello, World!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(hello))
})
.bind("127.0.0.1:8080")?
.run()
.await
}

9.3. Cross-Compilation​

Install cross-compilation targets:

rustup target add x86_64-unknown-linux-musl
rustup target add aarch64-unknown-linux-gnu

Note: This AMI uses system Rust, not rustup. For cross-compilation, install rustup:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
rustup target add x86_64-unknown-linux-musl

Build for different target:

cargo build --target x86_64-unknown-linux-musl

9.4. Optimizing Binary Size​

Create .cargo/config.toml:

[profile.release]
opt-level = "z" # Optimize for size
lto = true # Enable Link Time Optimization
codegen-units = 1 # Better optimization
strip = true # Remove debug symbols

Build optimized binary:

cargo build --release

Further reduce with UPX:

sudo dnf install -y upx
upx --best --lzma target/release/my_app

9.5. WebAssembly Compilation​

Install wasm-pack:

cargo install wasm-pack

Create Wasm project:

cargo new --lib my_wasm
cd my_wasm

Add to Cargo.toml:

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"

Build for WebAssembly:

wasm-pack build --target web

9.6. Benchmarking​

Create benches/my_benchmark.rs:

use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn fibonacci(n: u64) -> u64 {
match n {
0 => 1,
1 => 1,
n => fibonacci(n-1) + fibonacci(n-2),
}
}

fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

Add to Cargo.toml:

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "my_benchmark"
harness = false

Run benchmarks:

cargo bench

10. Security Considerations​

10.1. Dependency Security Best Practices​

Use cargo-audit regularly:

# Add to CI/CD pipeline
cargo audit

# Fail build on vulnerabilities
cargo audit --deny warnings

Pin dependencies carefully:

# Bad: Allows major updates (breaking changes)
serde = "*"

# Good: Allows minor updates (compatible)
serde = "1.0"

# Strict: Exact version only
serde = "=1.0.195"

Review dependency tree:

# Show all dependencies
cargo tree

# Find why a crate is included
cargo tree -i suspicious_crate

10.2. Secure Coding Practices​

Avoid unsafe code unless necessary:

// Safe Rust (preferred)
let vec = vec![1, 2, 3];
let first = vec[0];

// Unsafe (use only when needed)
unsafe {
let ptr = vec.as_ptr();
let first = *ptr;
}

Validate user input:

use std::io;

fn safe_parse(input: &str) -> Result<i32, std::num::ParseIntError> {
input.trim().parse::<i32>()
}

Use constant-time comparisons for secrets:

cargo add subtle
use subtle::ConstantTimeEq;

fn compare_secrets(a: &[u8], b: &[u8]) -> bool {
a.ct_eq(b).into()
}

10.3. Firewall Best Practices​

Only expose necessary ports:

# SSH (restrict to your IP)
Source: YOUR_IP/32, Port: 22

# Web application (if public)
Source: 0.0.0.0/0, Port: 443 (HTTPS)

# Do NOT expose:
# - 8080 (Development server)
# - Random high ports

11. Final Notes​

What You've Got​

This AMI provides a complete, production-ready Rust development environment:

  • ✅ Rust 1.92.0 from Red Hat official repository
  • ✅ Cargo 1.92.0 package manager and build tool
  • ✅ cargo-audit 0.22.1 for security scanning
  • ✅ ripgrep 14.1.1 for fast code searching
  • ✅ OpenSSL development libraries for crypto support
  • ✅ Complete gcc toolchain for linking
  1. Learn Rust Basics:

  2. Build a Web Service:

  3. Explore the Ecosystem:

  4. Join the Community:

Performance Expectations​

Rust excels at:

  • Memory Safety: Zero-cost abstractions without garbage collection
  • Concurrency: Fearless concurrency with compile-time guarantees
  • Speed: Performance comparable to C/C++
  • Reliability: Catch bugs at compile time, not runtime
  • Small Binaries: 1-5 MB for typical CLI tools (with optimization)

Cost Optimization​

For development:

  • t3.micro (1 vCPU, 1GB RAM): Sufficient for learning
  • t3.small (2 vCPU, 2GB RAM): Better for compiling larger projects

For production:

  • t3.medium+ (2+ vCPU, 4GB+ RAM): Recommended for web services
  • c5.large+: For CPU-intensive workloads
  • Rust services: Very cost-effective due to low memory usage

Rust's efficiency makes it one of the most cost-effective languages for cloud deployment, often using 50-90% less memory than equivalent Java or Go applications.


Happy coding with Rust! 🦀