Skip to content

Instantly share code, notes, and snippets.

@cam8001

cam8001/userdata.sh

Created Sep 30, 2020
Embed
What would you like to do?
AWS EC2 userdata for Unifi Controller on Ubuntu 16.04. Assumes Correto is installed and Ubiqiuiti repo is added
#!/bin/bash
echo "Updating Unifi..."
systemctl stop unifi
apt update
# Disable interactive prompts for the unifi installer
echo "unifi unifi/has_backup boolean true" | debconf-set-selections
DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade unifi
# Update the Unifi config for a system using Amazon Corretto instead of OpenJDK
curl https://gist.githubusercontent.com/cam8001/585bc721b25c80e185b83269fdb62e4a/raw/de847624ee14b89814c8c759e2559d7871d6c4ce/correto_unifi.sh > /usr/lib/unifi/bin/unifi.init
# Set timezone to NZ
ln -fs /usr/share/zoneinfo/Pacific/Auckland /etc/localtime
# Make sure ssm is running
systemctl start snap.amazon-ssm-agent.amazon-ssm-agent.service
systemctl enable snap.amazon-ssm-agent.amazon-ssm-agent.service
systemctl start unifi
systemctl enable unifi
# Associate a given elastic IP with an instance on boot.
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
AWS_DEFAULT_REGION=ap-southeast-2
# Associate this EIP on launch.
ALLOC_ID=eipalloc-00d3362d1453c25f5
echo "Updating packages..."
# Force grub to update in a silent mode
DEBIAN_FRONTEND=noninteractive apt-get -y -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" -qq --force-yes upgrade
# Update packages.
apt upgrade -y
# Install the awscli
if ! [ -x "$(command -v aws)" ]; then
echo "Installing awscli..."
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
yes | unzip awscliv2.zip
yes | ./aws/install
fi
# Install jq
if ! [ -x "$(command -v jq)" ]; then
echo "Installing jq..."
snap install jq
fi
# Get instance creds.
# @see https://github.com/pierreg256/eip/blob/master/auto-ip.sh
# @see https://gist.github.com/fgassert/8923461
# @see https://gist.github.com/odessky/e7b8b31e3b710cf3e29e85339d4ec5e6
ROLE=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/)
CR=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE/)
export AWS_ACCESS_KEY_ID=$(echo $CR | jq -r '.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $CR | jq -r '.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $CR | jq -r '.Token')
# Now we can associate the address.
echo "Running: aws --region=$AWS_DEFAULT_REGION ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID --allow-reassociation"
aws --region=$AWS_DEFAULT_REGION ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID --allow-reassociation
IPv4=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
echo "This instance now has public IPv4 $IPv4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment