Last active
May 25, 2024 15:31
-
-
Save raj-saxena/3dcaa5c0ba0be88ed91ef3fb50d3ce85 to your computer and use it in GitHub Desktop.
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 - https://stackoverflow.com/questions/53162620/automate-gcp-persistent-disk-initialization
This file contains 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 | |
set -uxo pipefail | |
# DISK_NAME = Name of the disk in terraform | |
# DEVICE_NAME = When $DISK_NAME is mounted in the compute instance at `/dev/` | |
MOUNT_DIR=/mnt/disks/persistent_storage | |
# Check if entry exists in fstab | |
grep -q "$MOUNT_DIR" /etc/fstab | |
if [[ $? -eq 0 ]]; then # Entry exists | |
exit | |
else | |
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-` # https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance#device_name | |
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 | |
fi |
@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.
Makes sense. Thanks, I found this useful.
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
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?