Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script that will download the F22 cloud image and run fstrim and the compress it again.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
# purpose: This script will download a fedora image run fstrim and then cp
# all images to /tmp/xzimg. It uses Docker to hopefully guarantee
# the behavior is consistent across different machines.
# author: Dusty Mabe (
set -eux
mkdir -p /tmp/xzimg/
docker run -i --rm --privileged -v /tmp/xzimg:/tmp/xzimg fedora:22 bash << 'EOF'
set -eux
# Vars for the image
XZIMG=$(basename $XZIMGURL) # Just the file name
IMG=${XZIMG:0:-3} # Pull .xz off of the end
# Create workdir and cd to it
mkdir -p $TMPMNT && cd $WORKDIR
# Get any additional rpms that we need
dnf install -y wget xz
# Get the xz image
cp -a $XZIMG /tmp/xzimg/orig.raw.xz
unxz $XZIMG
cp -a $IMG /tmp/xzimg/orig.raw
# Find the starting byte and the total bytes in the 1st partition
# NOTE: normally would be able to use partx/kpartx directly to loopmount
# the disk image and add the partitions, but inside of docker I found
# that wasn't working quite right so I resorted to this manual approach.
PAIRS=$(partx --pairs $IMG)
eval `echo "$PAIRS" | head -n 1 | sed 's/ /\n/g'`
STARTBYTES=$((512*START)) # 512 bytes * the number of the start sector
TOTALBYTES=$((512*SECTORS)) # 512 bytes * the number of sectors in the partition
# Discover the next available loopback device
LOOPDEV=$(losetup -f)
# Make the loopback device if it doesn't exist already
if [ ! -e $LOOPDEV ]; then
LOMAJOR=${LOOPDEV#/dev/loop} # Get just the number
mknod -m660 $LOOPDEV b 7 $LOMAJOR
# Loopmount the first partition of the device
losetup -v --offset $STARTBYTES --sizelimit $TOTALBYTES $LOOPDEV $IMG
# Mount it on $TMPMNT
# Fstrim to recover space
fstrim -v ${TMPMNT}
# one more time for good luck
fstrim -v ${TMPMNT}
# umount and tear down loop device
umount $TMPMNT
losetup -d $LOOPDEV
[ ! -z $LOMAJOR ] && rm -f $LOOPDEV #Only remove if we created it
# recompress the image
xz --stdout $IMG > $XZIMG
# finally, cp $IMG into /tmp/azureimg/ on the host
cp -a $IMG /tmp/xzimg/trimmed.raw
cp -a $XZIMG /tmp/xzimg/trimmed.raw.xz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment