
A minimal Rust crate to detect whether your application is running in a container, a virtual machine, or on bare metal (no container/VM).
Add to your Cargo.toml:
[dependencies]
env_inspector = "0.1.0"
Then fetch the crate:
cargo build
Call the detect_scope function to get an EnvScope enum:
use env_inspector::{detect_scope, EnvScope};
fn main() {
match detect_scope() {
EnvScope::Kubernetes => {
println!("Running inside Kubernetes");
}
EnvScope::Container(engine) => {
println!("Running inside container: {}", engine);
}
EnvScope::Vm(vendor) => {
println!("Running inside VM: {}", vendor);
}
EnvScope::BareMetal => {
println!("Running on bare metal");
}
}
}
Execute the built‑in unit tests:
cargo test
Optionally, include a small binary in src/bin/inspect.rs:
use env_inspector::detect_scope;
fn main() {
println!("{:#?}", detect_scope());
}
Build and run it:
cargo run --bin inspect
The test code (src/bin/inspect.rs) should print: BareMetal.
Build the image and run a container:
cargo build --release
docker build -t env-inspector .
docker run --rm env-inspector
You should see this message:
Container(
"docker",
)
If you run it with podman it can detect it:
podman pull docker-daemon:env-inspector:latest
podman run --rm docker-daemon:env-inspector:latest
Container(
"podman",
)
Build and push the Docker image:
# Build locally
docker build -t your-registry/env-inspector:latest .
# Push to your registry (Docker Hub, ECR, GCR, etc.)
docker push your-registry/env-inspector:latest
Create a Pod manifest (k8s/pod.yaml):
apiVersion: v1
kind: Pod
metadata:
name: env-inspector-test
spec:
containers:
- name: inspector
image: your-registry/env-inspector:latest
command: ["inspect"]
restartPolicy: Never
Deploy to your cluster:
kubectl apply -f k8s/pod.yaml
Check the logs:
kubectl logs pod/env-inspector-test
You should see output indicating kubernetes, confirming that the code correctly detected the environment inside the cluster.
You need some hypervisor like VirtualBox. If you have vagrant then it is easy to run it with the supplied Vagrantfile:
vagrant up
default: Vm(
default: "hypervisor",
default: )
vagrant destroy -f