Posted by & filed under AWS/Linux/Unix/Devops stuff.

Creating snapshots with ZFS is easy, but scheduling these as cron jobs requires a simple script to automate these commands. Here is a simple sample script you can use and customize to your liking:


Creating snapshots with ZFS is easy, but scheduling these as cron jobs requires a simple script to automate these commands. Here is a simple sample script you can use and customize to your liking, simply customize “days” to the number of days you would like to keep snapshots for before rolling them over, and substitute “pool” and “pool/subpool” for the names of your pool(s)/subpool(s) you would like snapshots created for. As you can see, this script supports taking snapshots of “subpools” (for a lack of a better term, I’m sure this is incorrect), although you can obviously leave these out of the for loop if you do not have any.

If you are wondering why I don’t simply use the -r flag in the snapshot creation rather than include the additional recursion/for loop, the problem with this is that older snapshots in subpools are not turned over, hence an additional loop is needed to work through each individual pool and its child pools (kiddie pools?! :)

#!/usr/bin/bash                                                                                                      

DAYS=180

for POOL in pool pool/subpool; do
    cd /$POOL
    for i in *; do
        snapcheck=`zfs list | awk {'print $1'} | egrep "$POOL/$i@$DAYS$"`
        if [ "$snapcheck" != "" ]; then
            # old snapshot found, destroy it                                                                         
            zfs destroy $POOL/$i@$DAYS
        fi

        let STARTDAY=$DAYS-1
        for ((s=$STARTDAY; s >= 1; s--)); do
            snapcheck=`zfs list | awk {'print $1'} | egrep "$POOL/$i@$s$"`
            if [ "$snapcheck" != "" ]; then
                # snapshot exists, rollover                                                                          
                let NEXTSNAP=$s+1                                                          
                zfs rename $POOL/$i@$s @$NEXTSNAP
            fi
        done;                                                                             
        zfs snapshot $POOL/$i@1
    done;
done;
  • joe

    Just updated the include the -r flag in the final zfs snapshot command. This is optional, but we found it useful to also take snapshots of children file system that we may want to hypothetically rollback separately.

  • joe

    Updated the script again to better handle recursion through what I refer to as “subpools”, please disregard the above comment :)

  • joe

    I’m a little too lazy right at the moment to look up the proper term used for child pools. If any of you wish to enlighten me, please share and I’ll update this post accordingly…