Home

Launch EC2 instance, hosting static site using cloud-init

Credentials

I didn't want to permanently save my aws credentials on ~/.bashrc or some similar place. Thus, i created this script which has to be sourced, that asks for the secret and exports the credentials. This way, only on the exported shell does the credentials remain. It only asks for what's missing, and sets the default region without asking. The script:

#!/bin/bash
ask(){
	read -p "$@" x
	printf '%s\n' "$x"
}

if [[ -z $AWS_ACCESS_KEY_ID ]]; then
	export AWS_ACCESS_KEY_ID=$(ask "AWS_ACCESS_KEY_ID: ")
fi
if [[ -z $AWS_SECRET_ACCESS_KEY ]]; then
	export AWS_SECRET_ACCESS_KEY=$(ask "AWS_SECRET_ACCESS_KEY: ")
fi

if [[ -z $AWS_DEFAULT_REGION ]]; then
	export AWS_DEFAULT_REGION="ap-south-1"
fi

Launching EC2 with aws cli

To launch an EC2 instance programmatically, i used the aws cli. AWS cli has ec2 subcommand to manage the ec2 instances, that can create, delete, shutdown, or manage EC2 instances.
This script is used to create an ec2 instance. Because i'm using free tier, i can only have one EC2 instance. Thus, my script checks for running instance, and prompts to delete it before continuing.

cloud init

We can use cloud-init script to run some command when the instance first boots. This way we can customize our instance programatically. Note that it does not run on every boot, only the first one. We can run it on every boot using either a hook on the /etc/ directory, or by using a cronjob.

There are 2 formats that aws supports for cloud init. The first is the standard cloud init, created by canonical. The second one is just a shell script that'll be ran when the instance starts. I choosed to use the second one, since it's much simpler *and* much flexible! The cloud init script i created is: cloud-init.sh

Web server architecture

This is a static stite, no processing required. Thus the architecture is very simple:

Internet --->
             VPC -->
                   Subnet (security rules) -> EC2
                                                -> Nginx
                                                  -> files in fs