-
Notifications
You must be signed in to change notification settings - Fork 3
/
ec2_fetchkey
58 lines (48 loc) · 1.54 KB
/
ec2_fetchkey
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/bin/sh
# KEYWORD: firstboot
# PROVIDE: ec2_fetchkey
# REQUIRE: NETWORKING
# BEFORE: LOGIN
# Define ec2_fetchkey_enable=YES in /etc/rc.conf to enable SSH key fetching
# when the system first boots.
: ${ec2_fetchkey_enable=NO}
# Set ec2_fetchkey_user to change the user for which SSH keys are provided.
: ${ec2_fetchkey_user=ec2-user}
. /etc/rc.subr
name="ec2_fetchkey"
rcvar=ec2_fetchkey_enable
start_cmd="ec2_fetchkey_run"
stop_cmd=":"
SSHKEYPATH="latest/meta-data/public-keys/0/openssh-key"
IMDSV2GET="/usr/local/bin/aws-ec2-imdsv2-get"
ec2_fetchkey_run()
{
# If the user does not exist, create it.
if ! grep -q "^${ec2_fetchkey_user}:" /etc/passwd; then
echo "Creating user ${ec2_fetchkey_user}"
pw useradd ${ec2_fetchkey_user} -m -G wheel
fi
# Figure out where the SSH public key needs to go.
eval SSHKEYFILE="~${ec2_fetchkey_user}/.ssh/authorized_keys"
# Grab the provided SSH public key and add it to the
# right authorized_keys file to allow it to be used to
# log in as the specified user.
echo "Fetching SSH public key for ${ec2_fetchkey_user}"
mkdir -p `dirname ${SSHKEYFILE}`
chmod 700 `dirname ${SSHKEYFILE}`
chown ${ec2_fetchkey_user} `dirname ${SSHKEYFILE}`
${IMDSV2GET} ${SSHKEYPATH} > ${SSHKEYFILE}.ec2
if [ $? = 0 ]; then
touch ${SSHKEYFILE}
sort -u ${SSHKEYFILE} ${SSHKEYFILE}.ec2 \
> ${SSHKEYFILE}.tmp
mv ${SSHKEYFILE}.tmp ${SSHKEYFILE}
chown ${ec2_fetchkey_user} ${SSHKEYFILE}
rm ${SSHKEYFILE}.ec2
else
echo "Fetching SSH public key failed!"
rm ${SSHKEYFILE}.ec2
fi
}
load_rc_config $name
run_rc_command "$1"