These are the steps that I took to spin up an EC2 instance within the us-west-2 region, utilizing the Amazon Linux 2 AMI and t2.micro instance type.
First, you have to make sure that you have the AWS CLI installed and configured on your local machine.
Second, find the Amazon Linux 2 AMI IDs that are located in the us-west-2 region:
aws ec2 describe-images --region us-west-2 \
--filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" \
--owners amazon \
--query 'Images[].[ImageId,Name,CreationDate]' \
--output table
This outputs a list of the AMI IDs – just copy the ‘ami-xxx’ value from one of them. We’re going to select the instance type soon.
Next, create a key-pair. This will be so that we can ssh into the instance, and we have to make it now (before spinning up the ec2 instance) so that the public key can be attached to the instance when initiated. Here’s one way to do that:
aws ec2 create-key-pair --key-name MyKeyPair2 --query 'KeyMaterial' --output text > MyKeyPair2.pem
Note, the private part of that key pair will be saved in the directory where you run that command. Keep that in mind for when you want to SSH into the instance.
Third, create a security group that will be attached to the EC2 instance. Security groups are firewalls that are instance focused (as opposed to subnets, which are the domain of the NACLs). We need to create a SG and then create a route that will allow SSH ingress via port 22 (by default, all ingress routes are denied). Here’s one way to do that:
aws ec2 create-security-group2 --group-name MySecurityGroup --description "My security group2"
And then we need to set that ingress route. This is just for testing puirposes- the source is set wide-open to 0.0.0.0/0 which is not best practice for the real-world, you’d want to lock that down for sure.
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup2 --protocol tcp --port 22 --cidr 0.0.0.0/0
Now to put all those disparate pieces of data together:
aws ec2 run-instances \
--region us-west-2 \
--image-id ami-00572d57e771a4823 \
--instance-type t2.micro \
--key-name MyKeyPair2 \
--security-groups MySecurityGroup2
And just like that, the EC2 instance is initiated, there is a key-pair attached, and we can SSH into it. oh yah!
