Formatting, mounting and adding entry in /etc/fstab is necessary almost all the time. Here is a solution I came up with and might help others. This can also, for sure, be improved. I added echo commands to explain what each block does.
About disk name you could add device_name on your terraform code when you attach your disks to the instance(s) like mentioned here: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_attached_disk
device_name - (Optional) Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google- tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance.*
#!/bin/bash
DISKS_PATH=/dev/disk/by-id
DISKS=(disk1 disk2)
check_disks () {
for disk in "${DISKS[@]}"; do
MOUNT_DIR="/$disk"
echo "$MOUNT_DIR"
if sudo blkid $DISKS_PATH/google-${disk}; then
echo "$disk is already formatted, nothing to do"
echo "checking if $disk is present in fstab"
UUID=$(sudo blkid -s UUID -o value $DISKS_PATH/google-${disk})
grep -q "UUID=${UUID} $MOUNT_DIR" /etc/fstab
if [[ $? -eq 0 ]]; then
echo "$disk already present in fstab, continuing with checking mount"
echo "Now checking if $disk is already mounted"
grep -qs "$MOUNT_DIR" /proc/mounts
if [[ $? -eq 0 ]]; then
echo "$disk is already mounted, so doing nothing with mount"
else
echo "$disk is not mounted, so mounting it"
sudo mkdir -p $MOUNT_DIR
sudo mount -o discard,defaults $DISKS_PATH/google-${disk} $MOUNT_DIR
fi
elif [[ $? -ne 0 ]]; then
echo "$disk not present in fstab, so adding it"
echo UUID="$UUID" $MOUNT_DIR ext4 discard,defaults,nofail 0 2 | sudo tee -a /etc/fstab
echo "Now checking if $disk is already mounted"
grep -qs "$MOUNT_DIR" /proc/mounts
if [[ $? -eq 0 ]]; then
echo "$disk is already mounted, so doing nothing with mount"
else
echo "$disk is not mounted, so mounting it"
sudo mkdir -p $MOUNT_DIR
sudo mount -o discard,defaults $DISKS_PATH/google-${disk} $MOUNT_DIR
fi
fi
else
echo "Formatting ${disk}"
sudo mkfs.ext4 $DISKS_PATH/google-${disk};
echo "Creating directory for ${disk} on $MOUNT_DIR"
sudo mkdir -p $MOUNT_DIR
echo "adding $disk in fstab"
UUID=$(sudo blkid -s UUID -o value $DISKS_PATH/google-${disk})
echo UUID="$UUID" $MOUNT_DIR ext4 discard,defaults,nofail 0 2 | sudo tee -a /etc/fstab
echo "Mounting $disk"
sudo mount -o discard,defaults $DISKS_PATH/google-${disk} $MOUNT_DIR
fi
done
}
check_disks