Last active
March 7, 2024 15:29
-
-
Save skirsten/e5aa8f739afbfc6b1e230bc96509620f to your computer and use it in GitHub Desktop.
Small script to automatically format and mount virtio disks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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