xref: /freebsd/release/tools/mkami.sh (revision 58426589030308cd632477d328b9536b1634c54d)
1#!/bin/sh -e
2#
3# Copyright (c) 2015 Colin Percival
4#
5# SPDX-License-Identifier: BSD-2-Clause
6#
7# mkami.sh: Create an AMI from the currently running EC2 instance.
8#
9
10export PATH=$PATH:/usr/local/bin
11
12NAME=$1
13if [ -z "$NAME" ]; then
14	echo "usage: mkami <AMI name> [<AMI description>]"
15	exit 1
16fi
17DESC=$2
18if ! [ -z "$DESC" ]; then
19	DESCOPT="--description '$DESC'"
20fi
21
22# Get the instance ID and region from the EC2 Instance Metadata Service:
23# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
24TMPFILE=`mktemp`
25fetch -qo $TMPFILE http://169.254.169.254/latest/dynamic/instance-identity/document
26INST=`awk -F \" '/"instanceId"/ { print $4 }' $TMPFILE`
27REGION=`awk -F \" '/"region"/ { print $4 }' $TMPFILE`
28rm $TMPFILE
29CMD="aws --region $REGION ec2 create-image --instance-id $INST --output text --no-reboot --name '$NAME' $DESCOPT"
30
31# Unmount the new system image
32if mount -p | grep -q '/mnt.*ufs'; then
33	echo -n "Unmounting new system image..."
34	sync
35	umount /mnt
36	sync
37	sleep 5
38	sync
39	echo " done."
40elif mount -p | grep -q '/mnt.*zfs'; then
41	echo -n "Unmounting new system image..."
42	sync
43	zfs umount -a
44	zfs umount zroot/ROOT/default
45	sync
46	sleep 5
47	sync
48	echo " done."
49fi
50
51if eval "$CMD" --dry-run 2>&1 |
52    grep -qE 'UnauthorizedOperation|Unable to locate credentials'; then
53	echo "This EC2 instance does not have permission to create AMIs."
54	echo "Launch an AMI-builder instance with an appropriate IAM Role,"
55	echo "create an AMI from this instance via the AWS Console, or run"
56	echo "the following command from a system with the necessary keys:"
57	echo
58	echo "$CMD"
59	exit
60fi
61
62echo -n "Creating AMI..."
63AMINAME=`eval "$CMD"`
64echo " done."
65echo "AMI created in $REGION: $AMINAME"
66