Friday, 13 October 2017

Host a static website on EC2 instance by deploying it from S3


In one of the previous post we saw how to host a static website on EC2 instance.
But we took a much simple approach. We installed httpd and manually crated index.html which was the rendered by httpd service to outside world. In this post we will try to automate things.
  1. We will try to download the index.html from S3 bucket instead of manually creating it. 
  2. We will also automate all this using bootstrap bash so that every time we spawn our EC2 instance we don't have to manually do all these steps. 

  Host a static website on EC2 instance by deploying it from S3

First we need to create an EC2 role that has access to S2 using IAM. So we don't use new user programmatic access credentials directly like we did in last post. So go to IAM service and go to Roles and create a new role. Select EC2 to grant permission and in next page select S3 full access.

Once created go to EC2 instance and fireup new instance. I am going to use Amazon Linux AMI for this. In configure instance page select role as the one we have created - s3fullaccess

Next go to Advanced Details section in same page. You should see a text box here. Here you can add bootstrap scripts. Here I will add steps to automate our process. Add the following in the bootstrap code -

yum update -y
yum install httpd -y
service httpd start
chkconfig httpd on
cd /var/www/html
aws s3 cp s3://athakur/index.html /var/www/html

Then keep others defaults and launch the instance (Make sure in security groups you give allow port 80). Of course I have put index.html in bucket athakur which has following simple html content -

        <title>Hello World!</title>
        <h1>Hello world!</h1>

Once EC2 is up you can directly hit the public DNS and see if it works.

NOTE : Make sure you assign a security group that gives access to port 80 to outside world when you are creating your EC2 instance.

Related Links

t> UA-39527780-1 back to top