ruk·si

AWS Script
Simple EC2

Updated at 2016-02-23 08:30

In reality, you should use an auto scaling group and a CloudFormation template to do this in production but this script shows the basics.

Starts a single t2.micro instance and tells how to open a SSH access to it. When you press enter after the bootup, it will terminate the instance and the security group.

#!/bin/bash -e

# change to the AWS key pair you want to use
SSH_KEY=aws-skeleton-key

# find AMI ID in the region
AMI_ID=$(aws ec2 describe-images \
    --filters "Name=description, Values=Amazon Linux AMI 2015.03.? x86_64 HVM GP2" \
    --query "Images[0].ImageId" \
    --output text)

# find default VPC in the region
VPC_ID=$(aws ec2 describe-vpcs \
    --filter "Name=isDefault, Values=true" \
    --query "Vpcs[0].VpcId" \
    --output text)

# just pick the first found subnet
SUBNET_ID=$(aws ec2 describe-subnets \
    --filters "Name=vpc-id, Values=$VPC_ID" \
    --query "Subnets[0].SubnetId" \
    --output text)

# create a new security gorup
SG_ID=$(aws ec2 create-security-group \
    --group-name delete-me-sg \
    --description "This can be deleted" \
    --vpc-id $VPC_ID \
    --output text)

# allow SSH access to the security group
aws ec2 authorize-security-group-ingress --group-id $SG_ID \
    --protocol tcp --port 22 --cidr 0.0.0.0/0

INSTANCE_ID=$(aws ec2 run-instances \
    --image-id $AMI_ID \
    --key-name $SSH_KEY \
    --instance-type t2.micro \
    --security-group-ids $SG_ID \
    --subnet-id $SUBNET_ID \
    --query "Instances[0].InstanceId" \
    --output text)

echo "waiting for $INSTANCE_ID ..."
aws ec2 wait instance-running --instance-ids $INSTANCE_ID

PUBLIC_NAME=$(aws ec2 describe-instances \
    --instance-ids $INSTANCE_ID \
    --query "Reservations[0].Instances[0].PublicDnsName" \
    --output text)

echo "$INSTANCE_ID is accepting SSH connections under $PUBLIC_NAME"
echo "ssh -i ~/.ssh/$SSH_KEY.pem ec2-user@$PUBLIC_NAME"
read -p "Press [Enter] key to terminate $INSTANCE_ID ..."

# Now you can copy & paste the ssh command found in terminal to connect
# to the instance. Note that it will take a minute or two to fully boot up.

aws ec2 terminate-instances --instance-ids $INSTANCE_ID
echo "terminating $INSTANCE_ID ..."
aws ec2 wait instance-terminated --instance-ids $INSTANCE_ID
aws ec2 delete-security-group --group-id $SG_ID
echo "done."