In this lesson, you will learn how to write idempotent Bash scripts that ensure your RAID array is configured consistently every time they run, without causing errors if the array already exists.
Why Idempotency Matters
When automating storage setup, a script should be "idempotent"—meaning you can run it once, ten times, or a hundred times, and it will always result in the same desired state without failing or creating duplicate configurations. If your script blindly runs mdadm --create, it will throw errors or corrupt existing data if the array is already up.
Building the Script
To achieve this, we use conditional checks to verify the existence of the array before taking action. We check if the device file exists in /dev/md0 or if mdadm recognizes the array.
Here is a simple structure to ensure your RAID setup is stable:
#!/bin/bash
ARRAY_DEV="/dev/md0"
DEVICES="/dev/sdb /dev/sdc"
LEVEL=1
# Check if the array is already active
if [ -b "$ARRAY_DEV" ]; then
echo "Array $ARRAY_DEV already exists. Skipping creation."
else
echo "Creating RAID level $LEVEL array..."
mdadm --create --verbose "$ARRAY_DEV" --level=$LEVEL --raid-devices=2 $DEVICES
# Save the configuration to mdadm.conf for persistence
mdadm --detail --scan | grep "$ARRAY_DEV" >> /etc/mdadm/mdadm.conf
update-initramfs -u
fi
Key Considerations
- Safety Checks: The
-bflag checks if a block device exists. By wrapping the--createcommand in anifblock, we prevent the script from attempting to overwrite an active array. - Standardization: By defining variables at the top of your script (like
DEVICESandLEVEL), you can reuse the same script template across multiple servers, ensuring every machine has identical storage layouts. - Persistence: Since we learned about persistent assembly, the script automatically appends the array details to
mdadm.confonly if the array was freshly created. This ensures the array survives reboots without cluttering your config file on every subsequent run.
By incorporating these checks, you transform a manual, error-prone process into a robust, repeatable infrastructure-as-code workflow.
Key Takeaway: Build idempotency into your storage scripts by checking for the existence of block devices before execution, ensuring your deployment process is both reliable and safe.