DEV Community

Pedram Hamidehkhan
Pedram Hamidehkhan

Posted on

Create Static Website on AWS using Terraform

In this post, you learn how to use Terraform to create a static website on AWS. This example is suitable for scenarios where you have a frontend team working on a static web application. (not ideal for dynamic websites like mvc applications in ASP.NET) Moreover, you would generally use such pattern in larger applications, not for small blogs or single page applications.

First thing's first, let's initialize a Terraform project project. To do that create a file called configuration.tf (the name doesn't really matter, only the suffix) and add the following:

provider "aws" {
  region = "eu-central-1"
}
Enter fullscreen mode Exit fullscreen mode

Then run the following command to initialize the project:

Terraform init
Enter fullscreen mode Exit fullscreen mode

Using the configuration.tf file, terraform will know that provider you need and pulls the dependencies for you.

Then, in the main.tf file (create it if it doesn't exist) create a s3 bucket using the following command:

    resource "aws_s3_bucket" "bucket" {
      bucket = "youruniquebucketname"
      acl    = "public-read"

      provisioner "local-exec" {
          command = "aws s3 sync static/ s3://${aws_s3_bucket.bucket.bucket} --acl public-read --delete"

      }

      website {
        index_document = "index.html"
      }

    }
Enter fullscreen mode Exit fullscreen mode

In the first line, you create the bucket resource, second line is the name, the next is the access control list (must be public). The provisioner resource will copy a basic aws command, syncing the contents of the static folder (which is where you put your static content) to the bucket. You could also use the copy command, but I find sync more convenient, as it also can delete files in the target bucket.
At last, you can also make sure that index_document is pointing to your index.html file.

Then go ahead and paste your static content in the static folder.
Now we can deploy to AWS.
Use "terraform plan" to see what will be deployed. Then, using "terraform apply" you can deploy to your aws account.

The youtube video: https://www.youtube.com/watch?v=UU3drURkTtw

Top comments (0)