Skip to content

Instantly share code, notes, and snippets.

@braincow
Created June 17, 2020 16:33
Show Gist options
  • Save braincow/69b01cf7efbd8e8cae88cde3b6ea0b60 to your computer and use it in GitHub Desktop.
Save braincow/69b01cf7efbd8e8cae88cde3b6ea0b60 to your computer and use it in GitHub Desktop.
Bash script that when executed as root converts cloud-init version of the Fedora cloud disk image into GCE instance image
#!/bin/bash
# exit on all failures
set -e
FEDORA_VERSION=${1:-32}
BUCKET_NAME=${2:-fedora-$FEDORA_VERSION-custom}
# first detect the filename for the latest RAW image
IMAGE=/tmp/fedora-$FEDORA_VERSION-disk.img
if [ ! -f "$IMAGE" ]; then
RAW_NAME=$(curl http://mirrors.kernel.org/fedora/releases/$FEDORA_VERSION/Cloud/x86_64/images/ |grep raw.xz |sed -e 's/<[^>]*>//g'|cut -d" " -f1)
# download the RAW image and immediatelly decompress it into a disk.raw image
curl http://mirrors.kernel.org/fedora/releases/$FEDORA_VERSION/Cloud/x86_64/images/$RAW_NAME | xz --decompress --stdout > $IMAGE
fi
TEMPDIR=$(mktemp -d)
IMAGE_WORKCOPY="$TEMPDIR/disk.raw"
cp -v $IMAGE $IMAGE_WORKCOPY
# prepare the mountpoint for the image
ROOT=/mnt/fedora-$FEDORA_VERSION-disk
if [ -d "$ROOT" ]; then
echo "err: Previous mount folder detected at: $ROOT. Unmount and remove it manually to be safe."
exit 1
fi
mkdir -vp $ROOT
losetup -fP $IMAGE_WORKCOPY
DEVICE=$( losetup -l |grep $IMAGE_WORKCOPY |awk '{print($1)}' )
mount ${DEVICE}p1 $ROOT
mount --bind /etc/resolv.conf $ROOT/etc/resolv.conf
mount --bind /sys $ROOT/sys
mount --bind /proc $ROOT/proc
mount --bind /dev $ROOT/dev
# execute following script until EOT in chroot in the mounted image
chroot $ROOT /bin/bash << "EOT"
dnf -y remove cloud-init
dnf -y install google-compute-engine-tools
dnf clean all
systemctl enable google-accounts-daemon google-clock-skew-daemon \
google-instance-setup google-network-daemon \
google-shutdown-scripts google-startup-scripts
EOT
# cleanup the image mountpoint
umount $ROOT/etc/resolv.conf
umount $ROOT/sys
umount $ROOT/proc
umount $ROOT/dev
umount $ROOT
losetup -d $DEVICE
rmdir -v $ROOT
# package the image
TIMESTAMP=$(date +%s)
TARBALL="fedora-$FEDORA_VERSION-gce_image-$TIMESTAMP.tar.gz"
OLDPWD=$(pwd)
cd $TEMPDIR
tar zcvf $TARBALL disk.raw
gsutil cp $TARBALL gs://$BUCKET_NAME/
gcloud compute images create --source-uri gs://$BUCKET_NAME/$TARBALL fedora-$FEDORA_VERSION-$TIMESTAMP
cd $OLDPWD
rm $TARBALL
rm -rf $TEMPDIR
# eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment