Launching an EC2 instance

Manually launch an AMI

Now that we have an VM image we can launch it with the AWS CLI. To launch the image we need:

  • the AMI ID that we created
  • the region
  • the instance type
  • the security group
  • an instance name
  • a user data script

The user data script is critical because it tells the operating system what to do after it was launched. In our case we want to run our example application which is already contained in the image. In our case it is very simple - it runs the app:

#! /bin/bash
/home/ubuntu/sample &

The AWS CLI already accepts as arguments all the required options:

IMAGE_ID=$(aws ec2 describe-images --filters Name=name,Values=my-own-ami | jq -r .Images[0].ImageId)
aws ec2 run-instances --image-id $IMAGE_ID --count 1 --no-cli-pager --instance-type t2.micro --security-group-ids sg-077847d2f63340b3f --user-data file://scripts/startup.sh --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=from-packer}]'

The first command find the AMI ID of any image by name (my-own-ami in the example). The second command launches a machine using that AMI ID.

If you visit the AWS Console you will now see your instance running:

Running instance

While you can run manually these commands in your terminal we will also automate this process using Codefresh.