Skip to content

Instantly share code, notes, and snippets.

@skirsten
Last active March 7, 2024 15:29
Show Gist options
  • Save skirsten/e5aa8f739afbfc6b1e230bc96509620f to your computer and use it in GitHub Desktop.
Save skirsten/e5aa8f739afbfc6b1e230bc96509620f to your computer and use it in GitHub Desktop.
Small script to automatically format and mount virtio disks
#!/usr/bin/env python3
import glob
import json
import os
import subprocess
prefix = "/dev/disk/by-id/virtio-"
for disk in glob.glob(f"{prefix}*"):
name = disk.removeprefix(prefix)
if name.startswith("boot"):
continue
print(f"Checking disk {disk}")
# check if the disk is already formatted
blockdevice = json.loads(subprocess.check_output(["lsblk", "-f", disk, "--json"]))[
"blockdevices"
][0]
if blockdevice["fstype"] is None:
print(f" Formatting disk")
subprocess.run(["mkfs.ext4", disk], check=True)
else:
print(f" Disk already formatted")
# check / update fstab
with open("/etc/fstab") as f:
fstab = f.read()
mountpoint = f"/mnt/disk-{name}"
if disk in fstab:
print(f" Disk already setup in fstab. Expected mounted at {mountpoint}")
else:
print(f" Mounting at {mountpoint}")
os.makedirs(mountpoint, exist_ok=True)
# make the mountpoint immutable to prevent accidentally writing files to the unmounted mountpoint
subprocess.run(["chattr", "+i", mountpoint], check=True)
with open("/etc/fstab", "a") as f:
f.write(f"{disk} {mountpoint} ext4 defaults,nofail 0 2\n")
# reload fstab
print("")
print("Reloading all mountpoints")
subprocess.run(["mount", "-a"], check=True)
@skirsten
Copy link
Author

skirsten commented Mar 7, 2024

Usage:

sudo wget -O /usr/local/bin/auto-format-mount https://gist.github.com/skirsten/e5aa8f739afbfc6b1e230bc96509620f/raw/auto-format-mount.py

sudo chmod +x /usr/local/bin/auto-format-mount

sudo auto-format-mount # run this after attaching a new volume or run it periodically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment