-
-
Save sohooo/8d24417780ac053299b4d40c20a9c087 to your computer and use it in GitHub Desktop.
Automatic mounting of additional NBD volumes using systemd on Ubuntu
This file contains hidden or 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
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment