Skip to content

Instantly share code, notes, and snippets.

Last active August 30, 2023 23:57
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Use the following script to mount a persistent storage during startup. This is helpful when you provision the compute instance as well as the persistent disk using some automation tool like Terraform. StackOverFlow question -
set -uxo pipefail
# DISK_NAME = Name of the disk in terraform
# DEVICE_NAME = When $DISK_NAME is mounted in the compute instance at `/dev/`
# Check if entry exists in fstab
grep -q "$MOUNT_DIR" /etc/fstab
if [[ $? -eq 0 ]]; then # Entry exists
set -e # The grep above returns non-zero for no matches & we don't want to exit then.
# Find persistent disk's drive value, prefixed by `google-` #
DEVICE_NAME="/dev/$(basename $(readlink /dev/disk/by-id/google-${DISK_NAME}))"
sudo mkfs.ext4 -m 0 -F -E lazy_itable_init=0,lazy_journal_init=0,discard $DEVICE_NAME
sudo mkdir -p $MOUNT_DIR
sudo mount -o discard,defaults $DEVICE_NAME $MOUNT_DIR
# Add fstab entry
echo UUID=$(sudo blkid -s UUID -o value $DEVICE_NAME) $MOUNT_DIR ext4 discard,defaults,nofail 0 2 | sudo tee -a /etc/fstab
Copy link

tclift commented Oct 12, 2021

Given that DISK_NAME is under your control, wouldn't you want to use the device path in fstab rather than the UUID? I.e., if the disk is replaced, you'd want the new one with the same name, not the old one by UUID?

Copy link

@tclift depends on the use case. The thinking here was that if you decide to change the DISK_NAME, the UUID would still be the same so it would mount correctly.

Copy link

tclift commented Oct 14, 2021

Makes sense. Thanks, I found this useful.

Copy link

Will your script wipe all data if we destroy the instance and recreate it ?

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