Step-by-Step Guide. Provisioning Multi-Tier Infrastructure on AWS Using Terraform (Mac OS)


In the world of DevOps, managing infrastructure efficiently is crucial. Infrastructure as Code (IaC) tools like Terraform streamline this process by allowing the provisioning of complex architectures on cloud platforms like AWS. In this tutorial, we’ll walk through using Terraform to create a multi-tier infrastructure for hosting a sample web app on AWS, all from your Mac OS.

Prerequisites

Before diving in, ensure you have the following:

  • An AWS account
  • Terraform installed on your Mac OS
  • Basic knowledge of AWS services and Terraform

Step 1: Set Up AWS Credentials

Before you start using Terraform to provision resources on AWS, you need to set up your AWS credentials on your Mac OS. Follow these steps:

Create Access Key and Secret Key

  1. Log in to the AWS Management Console.

  2. Navigate to IAM (Identity and Access Management).
  3. Access Users and Add a New User.
    • From the left-hand side panel, click on “Users.”
    • Click on the “Add user” button.
  4. Set User Details.
    • Enter a username (e.g., terraform-user) for the new IAM user.
    • Click Next.
  5. Define User Permissions.
    • Select “Attach policies directly” and Attach policies to grant necessary permissions. For this tutorial, you can attach the AmazonEC2FullAccess and AmazonVPCFullAccess policies to the user for managing EC2 and VPC resources.
  6. Review and Create the User.
    • Review the user details and permissions.
    • Click “Create user.”
  7. Get Access Key ID and Secret Access Key.
    • After the user is created, you’ll be prompted to download the user’s credentials (Access Key ID and Secret Access Key) as a CSV file. Ensure you save this file securely.
    • If you were not prompted to download credentials, click on the username you created (eg: terraform-user) > Security Credentials > “Create Access Key” > Select “Command Line Interface (CLI)” > Click Next > Create Access Key > Download .csv file > Done

Configure AWS CLI with Access Key and Secret Key

Once you have the Access Key ID and Secret Access Key:

  1. Install AWS CLI if not already installed.
    brew install awscli
    
  2. Configure AWS CLI with your credentials.
    aws configure
    
    • Enter your Access Key ID and Secret Access Key when prompted.
    • Set the default region and output format as needed.

    By following these steps, you’ll create an IAM user, generate access keys, and configure the AWS CLI on your Mac OS to enable Terraform to authenticate and interact with your AWS account.

Step 2: Install Terraform on Mac OS

Download and install Terraform on your Mac OS using Homebrew.

# Install Terraform via Homebrew
brew install terraform

Step 3: Create Terraform Configuration Files

Organize your Terraform files for deploying the multi-tier infrastructure. Here’s a basic file structure:

project-folder/
│
├── main.tf         # Main Terraform configuration
├── variables.tf    # Variables file
└── backend.tf      # Backend configuration (optional)

Step 4: Define Infrastructure Components

Create a VPC (Virtual Private Cloud)

To create a VPC using Terraform, define the VPC resource in your main.tf:

# main.tf
# Create VPC

resource "aws_vpc" "my_vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "my-vpc"
  }
}

# Create an Internet Gateway
resource "aws_internet_gateway" "my_igw" {
  vpc_id = aws_vpc.my_vpc.id

  tags = {
    Name = "my-internet-gateway"
  }
}

Define Subnets

Next, create subnets within the VPC. Append below lines to the above code:

NOTE: Modify the availability zones us-west-1a and us-west-1b with the desired values.

# main.tf

resource "aws_subnet" "public_subnet" {
  vpc_id     = aws_vpc.my_vpc.id
  cidr_block = "10.0.1.0/24"
  availability_zone = "us-west-1a"
  map_public_ip_on_launch = true
  tags = {
    Name = "public-subnet"
  }
}

resource "aws_subnet" "private_subnet" {
  vpc_id     = aws_vpc.my_vpc.id
  cidr_block = "10.0.2.0/24"
  availability_zone = "us-west-1b"
  tags = {
    Name = "private-subnet"
  }
}

Create Security Groups

Define security groups to control inbound and outbound traffic. Append below lines to your code:

# main.tf

resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Security group for web tier"
  vpc_id      = aws_vpc.my_vpc.id

  # Define ingress and egress rules as needed
  # Example:
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# Define security groups for other tiers (app, database) similarly

Launch EC2 Instances (Web Tier)

Create EC2 instances for each tier. Append below lines to your code:

NOTE: Modify the ami “ami-0287a05f0ef0e9d9a” with your desired ami.

# main.tf

resource "aws_instance" "web_server" {
  ami           = "ami-0287a05f0ef0e9d9a"  # Specify your desired AMI
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.public_subnet.id
  security_groups = [aws_security_group.web_sg.id]

  # Add user data to install Nginx and serve a sample page
  user_data = <<-EOF
              #!/bin/bash
              yum update -y
              yum install nginx -y
              echo "<h1>Welcome to my web server!</h1>" > /usr/share/nginx/html/index.html
              service nginx start
              EOF
}

Set Up Load Balancers

Define load balancers to distribute incoming traffic. Append below lines to your code:

# main.tf

resource "aws_lb" "my_lb" {
  name               = "my-load-balancer"
  internal           = false
  load_balancer_type = "application"
  subnets            = [aws_subnet.public_subnet.id]

  enable_deletion_protection = false

  # Add listeners, target groups, and other configurations as needed
}

Explanation

VPC: Defines the Virtual Private Cloud network with a specified CIDR block.

Subnets: Creates public and private subnets within the VPC across different availability zones.

Security Groups: Defines rules to control inbound and outbound traffic for different tiers (e.g., web, app, database).

EC2 Instances: Launches an EC2 instance for the web tier, installs Nginx, and serves a sample webpage.

Load Balancers: Sets up a load balancer to distribute traffic among EC2 instances.

By following these steps and running Terraform, you’ll create a multi-tier infrastructure on AWS, complete with VPC, subnets, security groups, EC2 instances, and a load balancer, ready to serve a sample web page using Nginx.

Step 5: Define Variables (Optional)

Utilize the variables.tf file to declare variables for the infrastructure components to ensure flexibility and reusability.

Step 6: Initialize Terraform and Plan Deployment

Initialize the Terraform configuration and check the plan before applying changes.

# Initialize Terraform in your project directory
terraform init

# Check the execution plan
terraform plan

Step 7: Apply Changes

Apply the Terraform changes to create the infrastructure on AWS.

# Apply changes to provision infrastructure
terraform apply

Step 8: Test the Infrastructure

After successful deployment, test the infrastructure:

  • Access deployed resources (e.g., web app)
  • Perform basic functionality tests

Conclusion

Congratulations! You’ve successfully provisioned a multi-tier infrastructure on AWS using Terraform on your Mac OS. This tutorial provides a foundation for DevOps enthusiasts seeking hands-on experience with infrastructure as code.

Expand upon this setup, experiment with different AWS services, or enhance your Terraform skills to further optimize your infrastructure deployment process.

Happy coding and automating with Terraform!

About the Author

Hello! I’m Basil Varghese, a seasoned DevOps professional with 16+ years in the industry. As a speaker at conferences like Hashitalks: India, I share insights into cutting-edge DevOps practices. With over 8 years of training experience, I am passionate about empowering the next generation of IT professionals.

In my previous role at Akamai, I served as an ex-liaison, fostering collaboration. I founded Doorward Technologies, which became a winner in the Hitachi Appathon, showcasing our commitment to innovation.

Let’s navigate the dynamic world of DevOps together! Connect with me on LinkedIn for the latest trends and insights.


DevOps Door is here to support your DevOps learning journey. Join our DevOps training programs to gain hands-on experience and expert guidance. Let’s unlock the potential of seamless software development together!