Automatically mount encrypted drive (sparsebundle) on Login on macOS
The How
As always, the good stuff (TLDR) first:
Step 1: Open up Automator.app
Step 2: Press on “New Document”
Step 3: Select “Application”
Step 4: Find the “Run Shell Script” node in the Library (it’s on the left, if missing, go to View => Show Library on the top menu bar)
Step 5: Drag and drop the “Run Shell Script” to the right side
Step 6: Copy/paste the following script (asks for your password before attempting to mount the disk, which is needed if the drive is encrypted):
osascript -e "do shell script \"hdiutil attach <location/to/your/sparsebundle>\""
Step 7: Replace the <location/to/your/sparsebundle> above with the real absolute path to the .sparsebundle you want to mount
Step 8: Save as “YourAppName.app” in your Applications folder (mine is “TimeMachineAutoMounter.app”)
Step 9: Open System Preferences => General => Login Items
Step 10: Press the + sign at the bottom left of the Open at Login table
Step 11: Select “YourAppName.app”
The Why
I’ve recently configured Time Machine on macOS to create backups on a sparsebundle* that is stored on my OneDrive folder. The OneDrive application automatically saves that to the cloud, which makes my backups available on any device without the need for an external drive.
I noticed a small hiccup after setting all of it up as I show in this article: macOS Time Machine on your Cloud Storage system (OneDrive for me)
Every time I’d restart my Mac, I’d notice that TimeMachineBackups .sparsebundle wasn’t mounted. I’d have to open the folder I stored it on and double click it to mount it so that it’s available for the next backup. If I forgot to do this, I’d eventually get a notification that Time Machine failed to create a backup. If you miss this notification, you might end up with a false sense of security, all the while lacking fresh backups of your system.
By following The How section of this article, I managed to create a convenient little script that runs automatically every time I log in. It asks for my password so that it can read and mount the encrypted drive. Once that’s out of the way, I can rest assured that my backups will proceed without me noticing anything in the background.
Final note: check if you have working/usable backups every now and then. You don’t want to find out that your backups don’t work when you need them most.
*sparsebundle — a Read/Write format where the disk image only occupies as much space as the data it contains, up to the limit defined when it was created. (from TheXLab)