DEV Community

Cover image for Web Application on AWS with Terraform: A Step-by-Step Guide
Kalpesh Bhalekar
Kalpesh Bhalekar

Posted on

Web Application on AWS with Terraform: A Step-by-Step Guide

Ready to take your first steps into Infrastructure as Code (IaC)?

Today, we're going to walk through setting up your very first deployment with Terraform on AWS.

IaC Automation

What's the Plan?

We will deploy a basic web application using an EC2 instance on AWS. Don't worry if some of these terms are new to you - we'll cover everything step by step. Here's what you'll learn:

  1. How to set up Terraform and AWS
  2. Writing your first Terraform configuration
  3. Deploying and managing infrastructure with Terraform
  4. Best practices and next steps

Sounds exciting? Let's dive in!

Prerequisites and Setup

Before we start building, we need to make sure we have all our tools ready. It's like preparing for a cooking show - we want all our ingredients and utensils laid out before we begin.

1. Setting Up an AWS Account
If you haven't already, you'll need an AWS account. Head over to AWS and sign up. AWS offers a free tier that's perfect for experimenting without incurring costs.

2. Installing Terraform
Terraform is available for multiple operating systems. Here's how to install it:

For macOS:

bash
Copy code
brew install terraform
Enter fullscreen mode Exit fullscreen mode

For Windows:
Download the Terraform binary, unzip it, and add it to your system PATH.

For Linux:

bash
Copy code
sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install terraform
Enter fullscreen mode Exit fullscreen mode

3. Installing and Configuring AWS CLI

The AWS Command Line Interface (CLI) is essential for interacting with AWS services.

Installation:

bash
Copy code
# For macOS
brew install awscli
Enter fullscreen mode Exit fullscreen mode

For Windows and Linux, follow the instructions.

Configuration:

bash
Copy code
aws configure
Enter fullscreen mode Exit fullscreen mode

You'll be prompted to enter your AWS Access Key ID, Secret Access Key, region, and output format. Make sure you have your AWS credentials ready.

4. Checkpoint: Verify Installations

Let's ensure everything is set up correctly.

Check Terraform:

bash
Copy code
terraform -v
Enter fullscreen mode Exit fullscreen mode

You should see the installed Terraform version.

Check AWS CLI:

bash
Copy code
aws --version
Enter fullscreen mode Exit fullscreen mode

This should display the AWS CLI version.

💡 Checkpoint: After configuration, run aws sts get-caller-identity. If you see your AWS account details, you're all set!

  1. Creating a Working Directory Last bit of prep - let's create a directory for our Terraform project:
mkdir my-first-terraform-project
cd my-first-terraform-project
Enter fullscreen mode Exit fullscreen mode

💡 Checkpoint: Are you in your new project directory? You've just laid the groundwork for infrastructure automation.

Now that we've got all our tools set up, it's time to dive into Terraform configurations.

Writing Your Terraform Configuration

Understanding Terraform Files

Before we start coding, let's quickly go over the main Terraform file types we'll be using:

  1. main.tf: This is where the bulk of our resource definitions will go.
  2. variables.tf: We'll define any input variables here.
  3. outputs.tf: This file will specify any outputs we want to see after applying our configuration.

Initializing the Terraform Project
First things first, let's initialize our Terraform project:

terraform init
Enter fullscreen mode Exit fullscreen mode

This command sets up Terraform in your working directory and downloads any necessary provider plugins (in our case, the AWS provider).

💡Checkpoint: If you see a message saying "Terraform has been successfully initialized!"? Great job!

Terraform Success

Creating the Main Configuration

Now, let's create our main.tf file and start defining our infrastructure. We'll create a VPC, a subnet, a security group, and an EC2 instance.

Open main.tf in your favorite text editor and add the following:


provider "aws" {
  region = "us-west-2"  # Or your preferred region
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "main-vpc"
  }
}

resource "aws_subnet" "main" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "main-subnet"
  }
}

resource "aws_security_group" "allow_web" {
  name        = "allow_web_traffic"
  description = "Allow inbound web traffic"
  vpc_id      = aws_vpc.main.id

  ingress {
    description = "HTTP from VPC"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "allow_web"
  }
}

resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"  # Amazon Linux 2 AMI (HVM), SSD Volume Type
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.main.id

  vpc_security_group_ids = [aws_security_group.allow_web.id]

  tags = {
    Name = "WebServer"
  }
}


Enter fullscreen mode Exit fullscreen mode

Let's break this down:

  1. We start by specifying the AWS provider and the region.
  2. We create a VPC with a CIDR block of 10.0.0.0/16.
  3. Within the VPC, we create a subnet with a CIDR block of 10.0.1.0/24.
  4. We set up a security group that allows inbound HTTP traffic.
  5. Finally, we create an EC2 instance using the Amazon Linux 2 AMI, placing it in our subnet and associating it with our security group.

💡 Checkpoint: Double-check yourmain.tffile. Does it look similar to the above? Remember, indentation is important in Terraform configurations!

Adding Variables and Outputs

Now, let's create a variables.tf file to make our configuration more flexible:

variable "region" {
  description = "AWS region"
  default     = "us-west-2"
}

variable "instance_type" {
  description = "EC2 instance type"
  default     = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

And an outputs.tf file to get some useful information after we apply our configuration:

output "instance_public_ip" {
  description = "Public IP address of the EC2 instance"
  value       = aws_instance.web_server.public_ip
}

Enter fullscreen mode Exit fullscreen mode

Don't forget to update your main.tf to use these variables:

provider "aws" {
  region = var.region
}

# ... (other resources remain the same)

resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.instance_type
  # ... (rest of the resource definition remains the same)
}
Enter fullscreen mode Exit fullscreen mode

💡Checkpoint: Do you have main.tf, variables.tf, and outputs.tf files in your directory? Great!

Deploying Your Infrastructure

Exciting times! We're ready to bring our infrastructure to life. Here's how:

  1. First, let's see what Terraform is planning to do:
terraform plan
Enter fullscreen mode Exit fullscreen mode

This command shows you a preview of the changes Terraform will make.

  1. If everything looks good, let's apply our configuration:
terraform apply
Enter fullscreen mode Exit fullscreen mode

Terraform will show you the planned changes again and ask for confirmation. Type 'yes' to proceed.

  1. Wait for Terraform to work its magic. When it's done, you should see something like:
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

Outputs:

instance_public_ip = "52.XX.XX.XX"
Enter fullscreen mode Exit fullscreen mode

💡Checkpoint: Did you see a similar output? Congratulations! You've just deployed your first infrastructure using Terraform!

What's Next?

We'll explore how to access our newly created web server, make changes to our infrastructure, and clean everything up when we're done.

Remember, if you run into any issues, don't panic. Infrastructure as Code is a journey, and every error is a learning opportunity. Keep experimenting, and you'll be a Terraform pro in no time!

To summarise , we've set up our tools, written our configuration, and deployed our infrastructure. Now, let's see it in action, make some changes, and learn how to clean up after ourselves.

Accessing Your Web Server

Remember that public IP address we got as output? It's time to put it to use!

  1. Open your web browser and try to access http://<your-instance-public-ip>.

    ...Wait, nothing's happening? That's because we haven't actually set up a web server on our EC2 instance yet!

  2. Let's SSH into our instance and set up a simple web server:

ssh ec2-user@<your-instance-public-ip>
sudo yum update -y
sudo yum install -y httpd
sudo systemctl start httpd
sudo systemctl enable httpd
echo "<h1>Hello from Terraform!</h1>" | sudo tee /var/www/html/index.html

Enter fullscreen mode Exit fullscreen mode
  1. Now try accessing your public IP again in the browser.

💡Checkpoint: Do you see "Hello from Terraform!" in your browser? Awesome job!

Making Changes to Your Infrastructure

One of the beauties of Infrastructure as Code is how easy it is to make changes. Let's try changing our instance type:

  1. Open variables.tf and change the default instance type:
variable "instance_type" {
  description = "EC2 instance type"
  default     = "t2.small"  # Changed from t2.micro
}

Enter fullscreen mode Exit fullscreen mode

Now, let's apply these changes:

terraform plan
terraform apply

Enter fullscreen mode Exit fullscreen mode
  1. Terraform will show you that it needs to destroy the existing instance and create a new one. Type 'yes' to proceed.

Checkpoint: After applying, check the AWS Console. Is your instance now a t2.small? Congratulations, you've just modified your infrastructure with just a few lines of code!

Cleaning Up

When you're done experimenting, it's important to clean up to avoid unnecessary AWS charges. Terraform makes this easy:

  1. Run the following command:
terraform destroy

Enter fullscreen mode Exit fullscreen mode
  1. Terraform will show you what it plans to destroy. Type 'yes' to confirm.

Checkpoint: Check your AWS Console. Are all the resources we created gone? Great job on keeping your AWS account tidy!

Congratulations! You've successfully deployed, modified, and destroyed infrastructure using Terraform.

So you've taken your first steps with Terraform on AWS ! While this tutorial gets you started with Infrastructure as Code, managing Terraform at scale across teams and environments can become challenging. That's where Scoutflo steps in to supercharge your Terraform workflow and eliminate common headaches. Think of Scoutflo as your mission control center for infrastructure - it handles all the complex aspects of managing Terraform so you can focus on building great infrastructure.

Managing Terraform with Scoutflo

Scoutflo

Terraform is a powerful tool, but achieving a fully secure, end-to-end GitOps workflow often requires a platform to manage and execute Terraform workflows efficiently. Scoutflo elevates Terraform management by providing an advanced platform, which unlocks capabilities like:

  • Infrastructure Management: Create and manage dev, staging, and production environments with just a few clicks.
  • Cost Control: Get cost estimates before applying changes and set budgets to avoid surprise bills.
  • Team Collaboration: Built-in approval flows, audit logs, and role-based access control make team coordination seamless.
  • GitOps Ready: Connect your repository and automatically plan infrastructure changes on pull requests.
  • Security First: Secure credential management and integration with your identity provider keep everything locked down.
  • Visual Infrastructure: See your entire infrastructure state at a glance through an intuitive dashboard.

To learn more about Scoutflo, create a free account or book a demo with our team.

Top comments (0)