Creating AWS EC2 instances with the AWS CLI

Mon 13th Nov 2017 / Tags: #AWS

Note: I did this to learn how the AWS CLI and API work, but for real-world use I recommend using Terraform instead.

Provision a Linux server (Ubuntu Xenial - 16.04 LTS)

Upload an existing SSH public key:

aws ec2 import-key-pair --key-name dave@davejamesmiller.com --public-key-material "$(ssh-add -L)"

Go to Console > Services > EC2 > Launch Instance to find an Amazon Machine Image (AMI) and get the ID.

You can also run something like this - but there's a lot of output and it's hard to read:

aws ec2 describe-images --owners self amazon --query \
    'Images[*].{ImageId:ImageId,Description:Description,Architecture:Architecture,ImageOwnerAlias:ImageOwnerAlias,ImageType:ImageType,RootDeviceType:RootDeviceType,VirtualizationType:VirtualizationType}'

Then launch it:

aws ec2 run-instances --image-id ami-add175d4 --instance-type t2.micro --key-name dave@davejamesmiller.com

Wait a minute and run this to check it's running and get the public IP / hostname:

aws ec2 describe-instances --instance-id i-01e0ed76c40ab0e9f

Allow access from your current IP (see output above for the default security group ID):

aws ec2 authorize-security-group-ingress --group-id sg-2add8d53 --protocol tcp --port 22 --cidr "$(curl -s checkip.amazonaws.com)/32"

Connect to it:

ssh ubuntu@ec2-34-240-160-133.eu-west-1.compute.amazonaws.com

Terminate it:

aws ec2 terminate-instances --instance-ids i-01e0ed76c40ab0e9f

Provision a Windows (2016) Server

Create a key pair (there's no reason to use my SSH key for this):

aws ec2 create-key-pair --key-name dave-windows --output text --query KeyMaterial > ~/dave-windows.pem

Launch it:

aws ec2 run-instances --image-id ami-b7e93bce --instance-type t2.micro --key-name dave-windows

Wait a minute and run this to check it's running and get the public IP / hostname:

aws ec2 describe-instances --instance-id i-0a2bfc7ce95569ca6

Allow access from your current IP (see output above for the default security group ID):

aws ec2 authorize-security-group-ingress --group-id sg-2add8d53 --protocol tcp --port 3389 --cidr "$(curl -s checkip.amazonaws.com)/32"

Get the password:

aws ec2 get-password-data --instance-id i-0a2bfc7ce95569ca6 --priv-launch-key dave-windows.pem

Connect to it via Remote Desktop (username is Administrator).

Terminate it:

aws ec2 terminate-instances --instance-ids i-0a2bfc7ce95569ca6