Skip to content

Instantly share code, notes, and snippets.

@Apsu
Last active October 1, 2024 21:06
Show Gist options
  • Save Apsu/504236c048c0e6dcf04170fc044df8c2 to your computer and use it in GitHub Desktop.
Save Apsu/504236c048c0e6dcf04170fc044df8c2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
### Packages, kernel, systemd ###
# Fix cloudflare postrm
if [[ -f /var/lib/dpkg/info/cloudflared.postrm ]]; then
cat <<-EOF > /var/lib/dpkg/info/cloudflared.postrm
#!/bin/bash
set -eu
rm -f /usr/local/bin/cloudflared
rm -f /usr/local/etc/cloudflared/.installedFromPackageManager || true
EOF
fi
# Stop cloudflared and jupyter units
systemctl disable --now cloudflared.service cloudflared-update.{service,timer} lambda-jupyter.service || true
# Get current cloud image manifest
wget https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.manifest -O /tmp/manifest
# Automated interactions
export DEBIAN_FRONTEND=noninteractive
# Extract differences in installed packages
comm -23 <(dpkg --get-selections | awk '{print $1}; F=":" {print $1}' | sort) <(awk '{print $1}; F=":" {print $1}' /tmp/manifest | sort) > /tmp/extra-packages
# Purge extras
xargs apt autoremove --purge -y < /tmp/extra-packages
# Purge old kernels
apt autoremove --purge -y linux-*-5* linux-*-6*
# Purge apparmor and snap
apt autoremove --purge -y apparmor snapd
# Remove 3rd party repos
rm -f /etc/apt/{cloud-init.gpg.d,sources.list.d}/*
# Remove custom services
rm -f /etc/systemd/system/cloudflared*
rm -f /etc/systemd/system/lambda-jupyter*
# Update repos
apt update
# Install latest HWE kernel
apt install --no-install-recommends -y linux-image-generic-hwe-22.04
# Upgrade rest of system
apt upgrade -y
# Disable apparmor in kernel
sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="apparmor=0"/' /etc/default/grub
update-grub
### Fixup networking ###
public_ip() {
# Strip CIDR
address=${1%/*}
# Check RFC1918 space
if [[ "$address" =~ ^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\.|^192\.168\. ]]; then
return 1 # Private
else
return 0 # Public
fi
}
NETWORK_FILE=/etc/systemd/network/20-wired.network
# Grab addresses from network definition
for address in $(grep ^Address= $NETWORK_FILE); do
# Strip Address= prefix
if public_ip ${address/Address=/}; then
# Delete from network file
sed -i "/Address=$address/d" $NETWORK_FILE
fi
done
### Miscellaneous ###
# Cleanup ubuntu user
rm -rf /home/ubuntu/.{local,cache,jupyter,ipython}
### Finished ###
# Reboot
reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment