Monday, October 17, 2022

Auto mount an SD card upon insert on Ubuntu Server

I have a headless Raspberry Pi board running Ubuntu 20.04.x server with a USB SD card reader. I wanted the system to automatically mount an SD card to a fixed mount point, e.g. /media/ubuntu/sdcard/ upon card insertion. By default, Ubuntu Server doesn't mount the SD card so I had to do some setup and configuration, as illustrate in the steps below. I had to install some prerequisite software package (udevil) and create a systemd service.

Install udevil package and create mount directory

  1. Open up a Terminal and type in the following command to install udevil.

    $ sudo apt install udevil

  2. Then, create a SD card directory mount point, e.g. /media/ubuntu/sdcard/ with the following command:

    $ mkdir -p /media/ubuntu/sdcard

 

Add a mount rule to the fstab file

  1. Using a text editor, e.g. vi, open up the system file /etc/fstab.

    $ sudo vi /etc/fstab

  2. Append the following line:

    /dev/sda1 /media/ubuntu/sdcard auto rw,user,exec,umask=000  0  2

    An example fstab file is shown below:
LABEL=writable  /        ext4   defaults        0 1
LABEL=system-boot       /boot/firmware  vfat    defaults        0       1
/dev/sda1       /media/ubuntu/sdcard auto rw,user,exec,umask=000        0       2

Create the devmon Systemd service

  1. In the Terminal, change directory to /etc/systemd/system/.

    $ cd /etc/systemd/system

  2. Using a text editor, e.g. vi, create a file e.g. devmon.service. Enter the following and save the file.

    [Unit]
    Description=Systemd service for running devmon
    [Service]
    Type=simple
    User=ubuntu
    Group=ubuntu
    ExecStart=/usr/bin/devmon
    [Install]
    WantedBy=multi-user.target
    


  3. In the Terminal, type in the following to generate the service:

    $ sudo systemctl daemon-reload
    $ sudo systemctl enable devmon

  4. Then either reboot the board or run the following command to start the service:

    $ sudo systemctl start devmon

 Monitor the service

  1. In a Terminal, type in the following to monitor the newly create devmon service when an SD card is inserted or unmounted.

    $ journalctl -u devmon -f

 Note: The SD card should be unmounted properly using the following command(s):

$ udevil umount /media/ubuntu/sdcard

- or -

$ sudo umount /media/ubuntu/sdcard

No comments: