Skip to content

Instantly share code, notes, and snippets.

@karser
Last active January 20, 2023 16:07
Show Gist options
  • Save karser/3a9ea094b1de3ab1e7411666069419ea to your computer and use it in GitHub Desktop.
Save karser/3a9ea094b1de3ab1e7411666069419ea to your computer and use it in GitHub Desktop.
Automatic mounting of additional NBD volumes using systemd on Ubuntu
#!/bin/bash
if [ "$#" -ne 2 ] ; then
echo 'Usage: mount-nbd.sh <device> <mount_point>'
exit 1
fi
device=$1
fs_type=$(blkid -o value -s TYPE $device)
if [[ -z $fs_type ]] ; then
echo "Formatting ${device}"
mkfs -q -t ext4 $device
fi
fs_uuid=$(blkid -o value -s UUID $device)
if [[ -z $fs_uuid ]] ; then
echo "Unable to find UUID"
exit 1
fi
echo "Device ${device} UUID: ${fs_uuid}"
mnt_point=$2
if [[ -d $mnt_point ]] ; then
if [ "$(ls -A $mnt_point)" ] ; then
echo "Mount point is not empty!"
exit 1
fi
echo "Warning: Mount point $mnt_point exists"
else
mkdir -p $mnt_point
fi
if grep -q -e $device -e $mnt_point /etc/fstab ; then
echo "/etc/fstab already contains mountpoint or device"
exit 1
fi
service_name="$(sed s@^/@@g <<<$mnt_point)"
service_name="$(sed s@/@-@g <<<$service_name)"
service_name="${service_name}.mount"
service_path="/etc/systemd/system/${service_name}"
if [[ -f $service_path ]]; then
echo "Service exists: ${service_path}"
exit 1
fi
echo "Creating service: ${service_path}"
cat > $service_path <<EOL
[Unit]
Description=Mount NDB Volume at boot
After=network-online.target
[Mount]
What=UUID="$fs_uuid"
Where=$mnt_point
Type=ext4
Options=defaults
[Install]
WantedBy=multi-user.target
EOL
systemctl daemon-reload
echo "Starting service"
systemctl start $service_name
systemctl enable $service_name
@karser
Copy link
Author

karser commented Oct 31, 2017

Usage example:

root@server:~ ./mount-nbd.sh /dev/nbd1 /mnt/data
Formatting /dev/nbd1
Device /dev/nbd1 UUID: d42b7140-7f36-4674-a171-7e782f2dfa96
Creating service: /etc/systemd/system/mnt-data.mount
Starting service

root@server:~ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/nbd0        46G  1.3G   43G   3% /
/dev/nbd1       138G   60M  131G   1% /mnt/data

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