EC2 + CloudFront Intergration with Terrafrom

Saurav Rana
4 min readAug 4, 2020

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.

Our task is to create a complete webserver environment in aws using terraform.So we setup basic requirements and create a tf file and start writing the code.

Now we create our private key using puttygen and save both public and private key in our windows.And now we create key_pair resource in AWS.

Now we create our security group which will only allow port 80 (http) and 22 (ssh).

We also need a additional security group for NFS.

Time to create our VM (EC2) and use these above created KEY and SECURITY GROUP in the ec2.Also we install needed packages for web server using provisioner.

We will create a EFS now.

Now to create mount target and attach security group to it.

We can attach this EFS to our EC2 isntance now.For this we use remote-provisioner and also copy our code from github.

Now time to create cloudfront distribution for Content Delivery Network.But first we need to create OAI (Origin Access Identity) for that.

We also need to store our content in s3 so need to create a bucket for cloudfront and update the bucket policy for the same.We make our s3 completely private and can’t be accessed from public world.

Time to upload our content to our s3 and we make our object completely private which can only be accessed by cloudfront OAI.

And created a local variable name for s3 origin id.

Now all the prerequisites have been done and now we can create cloudfront network.

One last step is to replace the image url with cloudfront url.Last code will modify the url and replace it with cloudfront url.

This completes our terraform code and all that is left is to run the code using “terraform apply”

We can verify all this form aws too.

Now at last time to see our webserver running.

It works fine.You can check the IP and ID of ec2 from above sreenshots and can confirm that it is same from terraform code terminal output.

That wraps up our whole setup to configure and launch webserver on aws+EFS using terraform

--

--