Skip to main content
โšก Calmops

Rust for DevOps Tooling

Rust for DevOps Tooling

TL;DR: This guide covers building DevOps tooling with Rust. You’ll learn CLI automation, infrastructure management, deployment utilities, and operational tools.


Introduction

Rust is excellent for DevOps tools due to:

  • Single binary deployment - No runtime dependencies
  • Fast execution - High performance
  • Memory safety - Reliable for automation
  • Cross-compilation - Target any platform

CLI Automation

Using Clap

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "deploy")]
#[command(about = "Deployment automation tool")]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Deploy to production
    Deploy {
        /// Environment to deploy to
        #[arg(short, long)]
        env: String,
        
        /// Skip tests
        #[arg(long)]
        skip_tests: bool,
    },
    
    /// Rollback deployment
    Rollback {
        /// Version to rollback to
        #[arg(short, long)]
        version: String,
    },
    
    /// Check deployment status
    Status,
}

pub fn run() {
    let cli = Cli::parse();
    
    match cli.command {
        Commands::Deploy { env, skip_tests } => {
            deploy(env, skip_tests);
        }
        Commands::Rollback { version } => {
            rollback(version);
        }
        Commands::Status => {
            check_status();
        }
    }
}

SSH Automation

use std::process::Command;

pub fn ssh_exec(host: &str, user: &str, cmd: &str) -> Result<String, Error> {
    let output = Command::new("ssh")
        .args(["-o", "StrictHostKeyChecking=no", 
               &format!("{}@{}", user, host), 
               cmd])
        .output()?;
    
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        Err(Error::SshFailed(String::from_utf8_lossy(&output.stderr).to_string()))
    }
}

Docker Integration

use std::process::Command;

pub struct DockerClient;

impl DockerClient {
    pub fn build_image(name: &str, tag: &str, context: &str) -> Result<(), Error> {
        let output = Command::new("docker")
            .args(["build", "-t", &format!("{}:{}", name, tag), context])
            .output()?;
        
        if output.status.success() {
            Ok(())
        } else {
            Err(Error::BuildFailed)
        }
    }
    
    pub fn run_container(name: &str, image: &str, port: u16) -> Result<(), Error> {
        Command::new("docker")
            .args(["run", "-d", "--name", name, "-p", &port.to_string(), image])
            .output()?;
        
        Ok(())
    }
}

Kubernetes Integration

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct K8sPod {
    pub metadata: PodMetadata,
    pub status: Option<PodStatus>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PodMetadata {
    pub name: String,
    pub namespace: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PodStatus {
    pub phase: String,
    pub pod_ip: Option<String>,
}

pub async fn get_pods() -> Result<Vec<K8sPod>, Error> {
    let output = Command::new("kubectl")
        .args(["get", "pods", "-o", "json"])
        .output()?;
    
    let pods: K8sPodList = serde_json::from_slice(&output.stdout)?;
    Ok(pods.items)
}

Log Aggregation

use std::fs::File;
use std::io::{BufRead, BufReader};

pub fn tail_logs(path: &str) {
    let file = File::open(path).unwrap();
    let reader = BufReader::new(file);
    
    for line in reader.lines() {
        if let Ok(line) = line {
            println!("{}", line);
        }
    }
}

Conclusion

Rust DevOps tooling provides:

  1. CLI automation - Powerful command-line tools
  2. SSH automation - Remote execution
  3. Docker/K8s - Container orchestration
  4. Single binary - Easy deployment

Comments