Terraform with AWS

Vanshika SharmaVanshika Sharma
9 min read

Prerequisites for Using Terraform with AWS

  1. AWS Account → Sign up at AWS Console.

  2. IAM User with Permissions → Create an IAM user with AdministratorAccess or required permissions.

  3. AWS CLI Installed → Install from AWS CLI Official Site and configure using:

     aws configure
    
  4. Terraform Installed → Download from Terraform’s official site.

  5. Basic Knowledge of AWS Services → EC2, S3, IAM, VPC, etc.

  6. Understanding Infrastructure as Code (IaC) → Terraform works declaratively.

  7. Text Editor (VS Code Recommended) → Install VS Code with the Terraform extension for better syntax support.

  8. Networking Basics (Optional) → Useful for configuring VPC, subnets, and security groups.

AWS CLI installed

Step 1: Download AWS CLI

  • Windows: Download and install from AWS CLI Windows Installer.

  • macOS: Install using Homebrew:

      brew install awscli
    
  • Linux: Install using the package manager:

      curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
      unzip awscliv2.zip
      sudo ./aws/install
    

Step 2: Verify Installation

Run:

aws --version

Example output:

aws-cli/2.x.x Python/3.x.x Linux/Windows/macOS

Step 3: Configure AWS CLI

Use:

aws configure

Enter:

  • AWS Access Key ID

  • AWS Secret Access Key

  • Default region (e.g., us-east-1)

  • Output format (json, table, or text)

AWS IAM user

Step 1: Sign in to AWS Console

  1. Go to AWS IAM Console.

  2. Click Users Add Users.

Step 2: Configure User Details

  1. Enter User Name (e.g., terraform-user).

  2. Select Access Key - Programmatic Access (needed for Terraform & AWS CLI).

Step 3: Set Permissions

  1. Choose Attach policies directly.

  2. Select AdministratorAccess (or create a custom policy with required permissions).

Step 4: Create and Download Credentials

  1. Click Create User.

  2. Download the Access Key ID and Secret Access Key (store them securely).

Step 5: Configure AWS CLI for Terraform

Run:

aws configure

Enter:

  • AWS Access Key ID

  • AWS Secret Access Key

  • Default region (e.g., us-east-1)

  • Output format (json, table, or text)

Task-01

  • Provision an AWS EC2 instance using Terraform

Hint:

resource "aws_instance" "aws_ec2_test" {
        count = 4
        ami = "ami-08c40ec9ead489470"
        instance_type = "t2.micro"
        tags = {
     Name = "TerraformTestServerInstance"
  }
}

Prerequisites

  • AWS CLI installed and configured (aws configure).

  • Terraform installed (Download Terraform).

  • IAM user with necessary permissions (EC2, VPC, etc.).


Step 1: Create a Terraform Configuration File (main.tf)

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "aws_ec2_test" {
  count         = 4
  ami           = "ami-08c40ec9ead489470"
  instance_type = "t2.micro"

  tags = {
    Name = "TerraformTestServerInstance-${count.index + 1}"
  }
}

Step 2: Initialize Terraform

Run:

terraform init

This downloads the AWS provider plugin.


Step 3: Plan and Apply Terraform Configuration

  1. Preview changes:

     terraform plan
    
  2. Apply the configuration:

     terraform apply -auto-approve
    

    This provisions 4 EC2 instances.


Step 4: Verify in the AWS Console

Go to EC2 Dashboard and check if the instances are running.


Step 5: Destroy the Instances (Optional)

If you want to delete the instances, run:

terraform destroy -auto-approve

Working with Terraform Resources

Understanding Terraform Resources

A resource in Terraform represents a specific cloud infrastructure component, such as an EC2 instance, S3 bucket, VPC, or database. Resources are defined in .tf files and managed declaratively by Terraform.


1. Structure of a Terraform Resource

resource "aws_instance" "example" {
  ami           = "ami-08c40ec9ead489470"
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleInstance"
  }
}

Breakdown:

  • resource → Declares a resource block.

  • "aws_instance" → Specifies the AWS EC2 instance resource type.

  • "example" → A unique name for referencing this resource.

  • ami → Amazon Machine Image (AMI) ID for the instance.

  • instance_type → Defines the EC2 instance type.

  • tags → Assigns metadata to the resource.


2. Common Terraform Resource Attributes

Terraform resources have several attributes that define their configuration. Some common ones include:

AttributeDescription
amiThe AMI ID is used to launch an instance.
instance_typeDefines the type of EC2 instance (e.g., t2.micro).
countSpecifies the number of instances to create.
tagsKey-value pairs to label resources.
cidr_blockDefines IP range (used in networking resources).

3. Using Multiple Resources

Terraform can manage multiple resources in a single configuration.
Example:

resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-terraform-bucket"
  acl    = "private"
}

resource "aws_instance" "web" {
  ami           = "ami-08c40ec9ead489470"
  instance_type = "t2.micro"

  tags = {
    Name = "WebServer"
  }
}

Here, both an EC2 instance and an S3 bucket are created.


4. Resource Dependencies

Terraform automatically manages dependencies, but you can explicitly define them using depends_on.
Example:

resource "aws_instance" "app_server" {
  ami           = "ami-08c40ec9ead489470"
  instance_type = "t2.micro"

  depends_on = [aws_s3_bucket.my_bucket]
}

This ensures the EC2 instance is created after the S3 bucket.


5. Modifying Resources

To update a resource, change its configuration and run:

terraform apply

Terraform will determine the changes needed and apply them.


6. Destroying Resources

To remove resources, run:

terraform destroy

This deletes all managed infrastructure.


Task 2: Create a security group

You need to create a security group to allow traffic to the EC2 instance. Follow these steps:

In your main.tf file, add the following code to create a security group:

resource "aws_security_group" "web_server" {
  name_prefix = "web-server-sg"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
  • Terraform init to initialize the Terraform project.

  • Run terraform apply to create the security group.

Step 1: Update main.tf with Security Group Configuration

Add the following code to your main.tf file:

provider "aws" {
  region = "us-east-1"
}

resource "aws_security_group" "web_server" {
  name_prefix = "web-server-sg"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]  # Allows HTTP traffic from anywhere
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]  # Allows all outbound traffic
  }

  tags = {
    Name = "WebServerSecurityGroup"
  }
}

Step 2: Initialize Terraform

Run the following command to download the required provider plugins:

terraform init

Step 3: Apply the Terraform Configuration

Run:

terraform apply -auto-approve

This will create the security group and display the generated resource details.


Step 4: Verify Security Group in AWS Console

  1. Go to AWS Console EC2 Dashboard Security Groups.

  2. Look for a security group with the name web-server-sg.

  3. Ensure it has an inbound rule for HTTP (Port 80) and an outbound rule for all traffic.


Optional: Attach Security Group to an EC2 Instance

If you have an EC2 instance, update it to use this security group:

resource "aws_instance" "web_server" {
  ami             = "ami-08c40ec9ead489470"
  instance_type   = "t2.micro"
  security_groups = [aws_security_group.web_server.name]

  tags = {
    Name = "TerraformWebServer"
  }
}

Step 5: Destroy the Security Group (Optional)

If you need to remove the security group, run:

terraform destroy -auto-approve

This completes Task 2! Now, your EC2 instances can receive HTTP traffic on port 80.

Task 3: Create an EC2 instance

  • Now, you can create an EC2 instance with Terraform. Follow these steps:

  • In your main.tf file, add the following code to create an EC2 instance:

resource "aws_instance" "web_server" {
  ami           = "ami-0557a15b87f6559cf"
  instance_type = "t2.micro"
  key_name      = "my-key-pair"
  security_groups = [
    aws_security_group.web_server.name
  ]

  user_data = <<-EOF
              #!/bin/bash
              echo "<html><body><h1>Welcome to my website!</h1></body></html>" > index.html
              nohup python -m SimpleHTTPServer 80 &
              EOF
}

Note: Replace the ami and key_name values with your own. You can find a list of available AMIs in the AWS documentation.

Run terraform apply to create the EC2 instance.

Step 1: Update main.tf to Include EC2 Instance Configuration

Modify your main.tf file to include the EC2 instance:

provider "aws" {
  region = "us-east-1"
}

# Security Group for EC2 Instance
resource "aws_security_group" "web_server" {
  name_prefix = "web-server-sg"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]  # Allows HTTP traffic from anywhere
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]  # Allows all outbound traffic
  }

  tags = {
    Name = "WebServerSecurityGroup"
  }
}

# EC2 Instance
resource "aws_instance" "web_server" {
  ami           = "ami-0557a15b87f6559cf"  # Replace with your AMI ID
  instance_type = "t2.micro"
  key_name      = "my-key-pair"  # Replace with your key pair name

  security_groups = [
    aws_security_group.web_server.name
  ]

  user_data = <<-EOF
              #!/bin/bash
              echo "<html><body><h1>Welcome to my website!</h1></body></html>" > index.html
              nohup python -m SimpleHTTPServer 80 &
              EOF

  tags = {
    Name = "TerraformWebServer"
  }
}

Step 2: Initialize Terraform

Run:

terraform init

Step 3: Apply the Terraform Configuration

Execute:

terraform apply -auto-approve

Terraform will create:
1. A security group allowing HTTP traffic
2. An EC2 instance with a simple Python HTTP server


Step 4: Verify in the AWS Console

  1. Go to EC2 Dashboard Instances.

  2. Check if the TerraformWebServer instance is running.

  3. Copy the Public IP and open it in a browser:

     http://<your-ec2-public-ip>
    

    You should see "Welcome to my website!" displayed.


Step 5: Destroy the EC2 Instance (Optional)

If you want to delete the resources, run:

terraform destroy -auto-approve

This completes Task 3! Your EC2 instance is now hosting a basic web page using Terraform.

Task 4: Access your website

  • Now that your EC2 instance is up and running, you can access the website you just hosted on it.

Now that your EC2 instance is running with a basic web server, follow these steps to access your website:


Step 1: Get the Public IP of Your EC2 Instance

Run the following Terraform command to fetch the public IP:

terraform output

OR, use this command if output variables are not defined:

aws ec2 describe-instances \
  --query "Reservations[*].Instances[*].PublicIpAddress" \
  --output text

Alternatively, you can find it in the AWS Console:

  1. Go to EC2 Dashboard Instances.

  2. Locate your TerraformWebServer instance.

  3. Copy the Public IPv4 Address.


Step 2: Open the Website in Your Browser

Paste the Public IPv4 Address into your browser’s address bar:

http://<your-ec2-public-ip>

Example:

http://3.93.45.123

If everything is set up correctly, you should see:
"Welcome to my website!"


Step 3: Troubleshooting (If the Website Is Not Loading)

If the page does not load:
Check EC2 Instance Status → Make sure the instance is running.
Verify Security Group Rules → Ensure inbound rule allows HTTP (port 80).
Check the User Data Script Execution

  • SSH into your instance:

      ssh -i my-key-pair.pem ec2-user@<your-ec2-public-ip>
    
  • Verify that the web server is running:

      ps aux | grep python
    
  • Restart it if necessary:

      nohup python -m SimpleHTTPServer 80 &
    

Step 4: (Optional) Destroy the Resources

If you want to delete everything:

terraform destroy -auto-approve

This completes Task 4! Your EC2 instance is now hosting a simple website, and you can access it from any browser.

1
Subscribe to my newsletter

Read articles from Vanshika Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vanshika Sharma
Vanshika Sharma

I am currently a B.Tech student pursuing Computer Science with a specialization in Data Science at I.T.S Engineering College. I am always excited to learn and explore new things to increase my knowledge. I have good knowledge of programming languages such as C, Python, Java, and web development.