Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/release/tools/mkami.sh
34677 views
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
10
export PATH=$PATH:/usr/local/bin
11
12
NAME=$1
13
if [ -z "$NAME" ]; then
14
echo "usage: mkami <AMI name> [<AMI description>]"
15
exit 1
16
fi
17
DESC=$2
18
if ! [ -z "$DESC" ]; then
19
DESCOPT="--description '$DESC'"
20
fi
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
24
TMPFILE=`mktemp`
25
fetch -qo $TMPFILE http://169.254.169.254/latest/dynamic/instance-identity/document
26
INST=`awk -F \" '/"instanceId"/ { print $4 }' $TMPFILE`
27
REGION=`awk -F \" '/"region"/ { print $4 }' $TMPFILE`
28
rm $TMPFILE
29
CMD="aws --region $REGION ec2 create-image --instance-id $INST --output text --no-reboot --name '$NAME' $DESCOPT"
30
31
# Unmount the new system image
32
if 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."
40
elif 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."
49
fi
50
51
if 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
60
fi
61
62
echo -n "Creating AMI..."
63
AMINAME=`eval "$CMD"`
64
echo " done."
65
echo "AMI created in $REGION: $AMINAME"
66
67