1

Context is as in this other question of mine. TL,DR: most of my home folder is on an external drive that I carry along with me and mount at my various workplaces and at home.

Mount is done as unionfs /HomeLocal=RW:/mnt/external_drive/HomeRoaming=RW /home thanks to the following line in fstab:

/HomeLocal=RW:/mnt/external_drive/HomeRoaming=RW /home fuse.unionfs auto,suid,exec,nonempty,max_files=32768,allow_other,x-systemd.requires=/mnt/external_drive

(/HomeLocal holds my local config files, and local users' homes.)

This works well but local users cannot use the computer when I'm not there, because unionfs fails when external_drive is not present. So I would like to write a SystemD mount unit to achieve this:

  • if external_drive is present, mount it, then unionfs as explained
  • if not, simply (bind) mount /HomeLocal on /home

I don't know if SystemD on its own has got what it takes to set up this kind of branching. If not, I guess I can resort to a script called by a mount unit, but then I need advice on how to write a correct unit file to achieve this.

1 Answer 1

0

You could do this with a systemd generator; have the generator create the appropriate mount unit depending on which devices are available. The following examples demonstrates the general idea:

  1. We check if our target device (/dev/disk/by-uuid/7057c04d-e1c8-4b95-8338-ff0c3e5b14f8) is available:

    • If it is, we'll use it.
    • If it's not, we'll use /dev/disk/by-uuid/cad0b488-1ac0-4725-806d-1df5aff03391 instead.
  2. Now that we know which device to use, we generate the appropriate mount unit.

  3. Finally, we activate the mount unit so that the device gets mounted.

I created the following script and named it /etc/systemd/system-generators/home-mount-generator:

#!/bin/bash

DISK1=/dev/disk/by-uuid/7057c04d-e1c8-4b95-8338-ff0c3e5b14f8
DISK2=/dev/disk/by-uuid/cad0b488-1ac0-4725-806d-1df5aff03391

normal_dir=$1
early_dir=${2:-$normal_dir}
late_dir=${3:-$normal_dir}

if [[ -b $DISK1 ]]; then
        DEVICE=$DISK1
else
        DEVICE=$DISK2
fi

cat > $normal_dir/home.mount <<EOF
# Created by $0

[Unit]
Description=Home directories

[Mount]
What=$DEVICE
Where=/home
Type=ext4

[Install]
WantedBy=local-fs.target
EOF

mkdir -p $normal_dir/local-fs.target.requires
ln -sf ../home.mount $normal_dir/local-fs.target.requires

Ensure the file is executable:

chmod 755 /etc/systemd/system-generators/home-mount-generator

Now reboot the system, and depending on which device is attached you would find one or the other mounted.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .