Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

#!/bin/sh
#
# $NetBSD: ec2_init,v 1.5 2022/10/15 18:32:30 jmcneill Exp $
#
# PROVIDE: ec2_init
# REQUIRE: NETWORKING
# BEFORE:  LOGIN

$_rc_subr_loaded . /etc/rc.subr

name="ec2_init"
rcvar=${name}
start_cmd="ec2_init"
stop_cmd=":"

CLOUD_TYPE=EC2	# default

case "$(/sbin/sysctl -n machdep.dmi.chassis-asset-tag)" in
OracleCloud*)
	CLOUD_TYPE=OCI
	;;
esac

case ${CLOUD_TYPE} in
EC2)
	EC2_USER="ec2-user"
	METADATA_URL="http://169.254.169.254/latest/meta-data/"
	SSH_KEY_URL="public-keys/0/openssh-key"
	;;
OCI)
	EC2_USER="opc"
	METADATA_URL="http://169.254.169.254/opc/v1/instance/"
	SSH_KEY_URL="metadata/ssh_authorized_keys"
	;;
esac

HOSTNAME_URL="hostname"

SSH_KEY_FILE="/home/${EC2_USER}/.ssh/authorized_keys"

OS_METADATA_URL="http://169.254.169.254/openstack/latest/meta_data.json"

ec2_newuser()
{
	echo "Creating ${CLOUD_TYPE} user account ${EC2_USER}"
	useradd -g users -G wheel,operator -m "${EC2_USER}"
}

extract_random_seed()
{
	sed -n -e '/random_seed/s/.*"random_seed": *"\([A-Za-z0-9+/=]*\)".*/\1/p'
}

ec2_init()
{
	(
	umask 022

	# set hostname; it may be 5-10 seconds for the metadata service
	# to become reachable.
	try=0
	while [ $((try++)) -lt 20 ]
	do
		HOSTNAME=$(ftp -o - -q 2 "${METADATA_URL}${HOSTNAME_URL}")
		if [ -n "$HOSTNAME" ]; then
			echo "Setting ${CLOUD_TYPE} hostname: ${HOSTNAME}"
			echo "$HOSTNAME" > /etc/myname
			hostname "$HOSTNAME"
			break
		fi
		echo "${CLOUD_TYPE} hostname not available yet (try $try)"
		sleep 1
	done

	# create cloud user
	id "${EC2_USER}" >/dev/null 2>&1 || ec2_newuser

	# fetch the public key from the metadata service
	EC2_SSH_KEY=$(ftp -o - -q 2 "${METADATA_URL}${SSH_KEY_URL}")

	if [ -n "$EC2_SSH_KEY" ]; then
		# A key pair is associated with this instance, add it
		# to EC2_USER's 'authorized_keys' file
		mkdir -p $(dirname "$SSH_KEY_FILE")
		chown "${EC2_USER}:users" $(dirname "$SSH_KEY_FILE")
		touch "$SSH_KEY_FILE"
		chown "${EC2_USER}:users" "$SSH_KEY_FILE"
		cd $(dirname "$SSH_KEY_FILE")

		grep -q "$EC2_SSH_KEY" "$SSH_KEY_FILE"
		if [ $? -ne 0 ]; then
			echo "Setting ${CLOUD_TYPE} SSH public key for user ${EC2_USER}: ${EC2_SSH_KEY##* }"
			echo "$EC2_SSH_KEY" >> "$SSH_KEY_FILE"
		fi
	fi

	# May contain a "random_seed".
	OS_METADATA="$(ftp -o - -q 2 ${OS_METADATA_URL})"
	if echo "$OS_METADATA" | grep -q random_seed; then
		echo "$OS_METADATA" | extract_random_seed |
		    base64 -di >> /dev/urandom
	fi
	)
}

load_rc_config $name
run_rc_command "$1"