Deploying Website on AWS EC2 using Terraform

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2021-09-28
Deploying a Website on AWS EC2 Using Terraform: A Comprehensive Guide
This article explains how to deploy a simple website to Amazon Web Services' Elastic Compute Cloud (EC2) using Terraform, a powerful infrastructure-as-code tool. We'll explore the concepts behind Terraform, walk through the process step-by-step, and clarify the purpose of each component.
Understanding Terraform
Terraform is a software tool designed to manage and automate the creation, modification, and versioning of infrastructure. Think of it as a blueprint for your cloud resources. Instead of manually configuring servers, networks, and storage through a web interface, you define your infrastructure using a declarative configuration language. Terraform then takes this configuration and translates it into actions on your chosen cloud provider, in this case, AWS. This approach offers several advantages: improved consistency, reduced errors, and enhanced version control for your infrastructure. Terraform supports many different cloud providers and even on-premise solutions, making it versatile for managing a wide range of environments. Its configuration language is designed specifically for describing infrastructure, making it easier to model complex setups. It utilizes a system of "resources," which are individual components of your infrastructure (like a virtual server or a network), and "modules," which group resources together for easier management of larger configurations.
Setting Up the Environment
To follow along, you'll need an AWS account and the AWS Command Line Interface (CLI) configured with appropriate permissions. A user with sufficient privileges (like "full access" for simplicity during this tutorial, though this isn't ideal for production environments) is necessary. The access and secret keys associated with this user will be crucial for authenticating Terraform with your AWS account. You'll also need a suitable Integrated Development Environment (IDE) like Visual Studio Code; the HashiCorp Terraform extension is helpful for syntax highlighting and code completion.
The Terraform Configuration Files
The core of your Terraform deployment lies within several configuration files. Let's examine each one:
variables.tf: This file defines variables that will be used throughout your configuration. These variables act as placeholders for values that might change, such as your AWS region, the access key and secret key for your AWS user, details for your EC2 instance (like instance type), and other customizable settings. This keeps your code flexible and reusable. It allows changing settings without modifying the core logic in other files.provider.tf: This file specifies the cloud provider you're working with. In this case, it's AWS. This file contains the credentials (access key and secret key) needed for Terraform to connect to and manage your AWS account. It establishes the communication channel between your local Terraform configuration and your AWS environment. The configuration within this file ensures Terraform can correctly authenticate and execute actions within your AWS account.securitygroup.tf: This file defines the security group, a virtual firewall that controls inbound and outbound network traffic for your EC2 instance. The security group rules specify which ports and protocols are allowed to reach your server. This is crucial for security, preventing unauthorized access to your website. Multiple security groups can be associated with a single instance, enabling fine-grained control over access.createwebsite.sh: This is not a Terraform configuration file itself; instead, it's a shell script. This script, executed on the EC2 instance after its creation, contains the instructions for setting up your website. In this tutorial, it sets up a basic "Hello, world!" website. The script handles the installation of any necessary web server software and the deployment of your website's files. This keeps the actual website setup separate from the core infrastructure configuration.ec2withuserdata.tf: This file defines the EC2 instance resource. It uses the variables defined invariables.tfto configure the instance's specifications, such as its instance type, the security group to associate it with, and importantly, it references thecreatewebsite.shscript as user data. This ensures the script is executed automatically when the instance starts up. The user data feature of EC2 allows custom scripts to be run during instance initialization.outputs.tf: This file specifies what information Terraform should output after the infrastructure is created. This is helpful for obtaining important details like the instance ID, its public DNS address (the address you'll use to access your website), and the security group ID. This provides a convenient way to access key information about the deployed resources without having to search the AWS console manually.
The Deployment Process
After setting up the files above, you navigate to the project directory in your terminal and execute a series of Terraform commands:
terraform init: This initializes the Terraform project and downloads the necessary AWS provider plugin.terraform plan: This creates an execution plan, showing you what changes Terraform will make to your AWS infrastructure. This is a crucial step for reviewing and verifying the intended changes before making them.terraform apply: This executes the plan, creating the EC2 instance, security group, and other resources defined in your configuration files.
Accessing Your Website
Once the terraform apply command completes successfully, you can access your website using the public DNS address shown in the output. It's important to note that the initial setup might take a few minutes because the instance needs to download and execute the createwebsite.sh script to set up your website.
Conclusion
This comprehensive guide demonstrates how Terraform simplifies the process of deploying a website to AWS EC2. By using infrastructure-as-code principles, you gain control, repeatability, and maintainability in managing your cloud environment. This example showcases a fundamental use case, but Terraform's power extends far beyond simple website deployments, allowing you to manage incredibly complex infrastructure configurations efficiently and safely. Remember to always follow security best practices, and avoid using overly permissive IAM policies in production environments. This example used "full access" for simplicity of demonstration only; more restrictive policies should be used in real-world deployments.