Skip to main content

Command Palette

Search for a command to run...

Terraform Installation, Access Configuration, and EC2 Deployment: From Setup to Provisioning

Introduction: From Theory to Hands-On Automation

Updated
9 min read
Terraform Installation, Access Configuration, and EC2 Deployment: From Setup to Provisioning
D

I'm a DevOps enthusiast and software engineer with 3+ years of hands-on experience building scalable CI/CD pipelines, automating infrastructure, and streamlining deployment workflows. I specialize in tools like Jenkins, Maven, Docker, and Tomcat, and I love turning complex systems into elegant, maintainable solutions. On Hashnode, I share insights, tutorials, and real-world lessons from the trenches—whether it's debugging flaky builds, optimizing deployment strategies, or exploring the latest in cloud-native tech. My goal is to help developers and ops teams collaborate better, ship faster, and learn continuously.4

In the previous article — Understanding Terraform & Infrastructure as Code: From Manual Chaos to Declarative Control — we explored the why of Terraform: its architecture, lifecycle, and how it revolutionized infrastructure management.

Now, it’s time to move from concept to command line — setting up Terraform, giving it the necessary permissions to talk to your cloud provider, and using it to launch your first AWS EC2 instance.


Prerequisites

Before diving in, ensure you have:

  • A Linux or macOS or Windows machine (Windows WSL works too)

  • Sudo/root access on the system

  • An AWS account with administrative privileges

  • Basic understanding of CLI and IAM concepts


Terraform Installation Guide

Before using Terraform, you must install it on your local machine or server. Terraform is distributed as a single binary, making it lightweight, fast, and easy to install across platforms.

You can install Terraform either:

  • Using an automated installation script (recommended for Linux systems), or

  • By performing a manual installation depending on your operating system

Terraform officially supports Linux, Windows, and macOS, ensuring a consistent experience across all major platforms.


You can set up Terraform in one step using the verified installation script below:

curl -fsSL https://raw.githubusercontent.com/divakarchakali-aka-DC/DevOps-Tools-Setup-Scripts/main/terraform-setup.sh | bash

What This Script Does

  • Detects your operating system
    (Amazon Linux, Ubuntu/Debian, Fedora, RHEL, CentOS)

  • Adds the official HashiCorp package repository

  • Installs the latest stable version of Terraform

  • Verifies the installation automatically

This script is transparent and safe — you can review it before running:

🔗 Terraform Installation Script on GitHub


Verify Installation

After installation, confirm Terraform is available:

terraform -version

Expected output:

Terraform v1.x.x
on linux_amd64

If you see the version, Terraform is successfully installed.


Option 2: Manual Installation on Linux

If you prefer manual setup, follow the instructions for your Linux distribution.

Debian / Ubuntu

wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" \
| sudo tee /etc/apt/sources.list.d/hashicorp.list

sudo apt update && sudo apt install terraform

Amazon Linux

sudo yum install -y yum-utils shadow-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum install terraform

RHEL / CentOS

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform

Installing Terraform on Windows

Although Terraform is most commonly used on Linux servers, Windows users can install and run Terraform locally for learning and development purposes.

Step 1: Download Terraform

Step 2: Extract the Binary

  • Extract the ZIP file

  • Move terraform.exe to a directory, for example:

C:\terraform

Step 3: Add Terraform to PATH

  1. Open System Properties

  2. Go to Environment Variables

  3. Edit the PATH variable

  4. Add:

C:\terraform

Step 4: Verify Installation

Open Command Prompt or PowerShell and run:

terraform -version

If Terraform prints the version, installation is complete.


Installing Terraform on macOS

Terraform can be installed easily on macOS using Homebrew, which is the recommended approach.

Install Using Homebrew

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Verify Installation

terraform -version

Terraform is now ready to use on macOS.

💡 While macOS is not typically used in production environments, it is widely used by DevOps engineers for local development and testing.


Granting Terraform Access to AWS

Installing Terraform is only half the setup — it needs credentials and permissions to interact with AWS APIs.

Let’s configure that step-by-step.

Step 1: Create an IAM User or Role for Terraform

Login to the AWS Management Console → navigate to IAMUsersAdd User.

  • Username: terraform-user

  • Permissions:

    • Either attach AdministratorAccess for testing

    • Or, for production, create a least-privilege policy (Amazonec2FullAccess - To work with only EC2 instances)

  • Access Creation:

    • Once user is created, open user account → security credentials → Access keys → Create access key

    • Access Type: Programmatic access (for CLI/API)

      • Note down the Access Key and Secret Access Key and keep those safe

Example least-privilege policy for EC2:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:*",
        "iam:PassRole",
        "cloudwatch:*",
        "logs:*",
        "s3:*"
      ],
      "Resource": "*"
    }
  ]
}

Download the Access Key ID and Secret Access Key — you’ll need these for authentication.


Step 2: Configure AWS CLI Credentials

Terraform relies on the same credentials used by the AWS CLI.

You can either install it manually from AWS CLI official downloads or use the automated installation script below.

You can set up Terraform in one step with this verified script:

curl -fsSL https://raw.githubusercontent.com/divakarchakali-aka-DC/DevOps-Tools-Setup-Scripts/main/awscli-setup.sh | bash

What this script does:

  • Detects your operating system (Amazon Linux, Ubuntu/Debian, Fedora, RHEL, CentOS, Oracle Linux)

  • Installs required dependencies (curl, unzip)

  • Downloads the official AWS CLI v2 directly from Amazon

  • Installs it system-wide with proper PATH configuration

  • Verifies the installation automatically

This script is safe and transparent — you can review it here before running:
🔗 AWS CLI Installation Script on GitHub

Once installed, confirm the version:

aws --version

Configure your credentials:

aws configure

Provide the values:

AWS Access Key ID [None]: AKIAXXXXXXXX
AWS Secret Access Key [None]: AbCdEfGhIjKlMnOpQrStUvWxYz12345
Default region name [None]: us-east-1 # Sets default region and not mandatory to mention
Default output format [None]: json # Sets default output format and not mandatory to mention

This stores credentials at ~/.aws/credentials, accessible by both AWS CLI and Terraform.


Step 3: Verify Access

Confirm that your credentials work:

aws sts get-caller-identity

If successful, you’ll see your IAM user or role details.

Now Terraform has authenticated access to AWS APIs.


Setting Up Your Terraform Project

Create a working directory for your Terraform files:

mkdir ~/terraform-ec2-demo && cd ~/terraform-ec2-demo

Inside this folder, create a file called main.tf.


main.tf — Configuration File

# Specify the AWS provider and region
provider "aws" {
  region = "us-east-1"  # This defines which AWS region to deploy resources to
}

# Create a security group for SSH access
# Security groups act as virtual firewalls for your EC2 instances
resource "aws_security_group" "allow_ssh" {
  name        = "allow_ssh"                    # Name of the security group
  description = "Allow SSH inbound traffic"    # Description for documentation

  # Inbound rules (who can access the instance)
  ingress {
    from_port   = 22          # SSH port
    to_port     = 22          # SSH port  
    protocol    = "tcp"       # TCP protocol for SSH
    cidr_blocks = ["0.0.0.0/0"]  # Allow SSH from ANY IP address (⚠️ Warning: Not recommended for production)
  }

  # Outbound rules (what the instance can access)
  egress {
    from_port   = 0           # All ports
    to_port     = 0           # All ports
    protocol    = "-1"        # All protocols
    cidr_blocks = ["0.0.0.0/0"]  # Allow outbound traffic to ANYWHERE
  }
}

# Create an EC2 instance (virtual server)
resource "aws_instance" "web" {
  # Amazon Machine Image - defines the operating system
  ami           = "ami-0c55b159cbfafe1f0"  # Amazon Linux 2 AMI (⚠️ Replace with current AMI for your region)

  # Instance type - defines the hardware specs
  instance_type = "t3.micro"  # 2 vCPUs, 1GB RAM (free tier eligible)

  # SSH key pair for secure login
  key_name      = "my-keypair"  # ⚠️ Replace with your existing key pair name in AWS

  # Attach the security group we created above
  vpc_security_group_ids = [aws_security_group.allow_ssh.id]

  # Tags for better resource management and identification
  tags = {
    Name = "Terraform-EC2-Demo"  # Display name in AWS console
  }
}

NOTE:

  1. Replace "ami-0c55b159cbfafe1f0" with a current Amazon Linux AMI for your region

  2. Replace "my-keypair" with your existing EC2 key pair name

  3. Allow SSH from "0.0.0.0/0" is insecure - restrict to your IP in production

  4. Run terraform init first to initialize the working directory

  5. Run terraform plan to preview changes before applying

  6. Run terraform apply to create the resources

What This Terraform Configuration Creates:

1. AWS Provider Setup

  • Configures Terraform to use AWS

  • Sets the region to us-east-1 (North Virginia)

2. Security Group (Virtual Firewall)

  • Inbound Rule: Allows SSH access (port 22) from any IP

  • Outbound Rule: Allows all outbound traffic

  • ⚠️ Security Note: Allowing SSH from 0.0.0.0/0 is insecure for production

3. EC2 Instance (Virtual Server)

  • OS: Amazon Linux 2

  • Size: t3.micro (2 vCPUs, 1GB RAM - free tier eligible)

  • Network: Attached to the SSH security group

  • Access: Uses SSH key pair for secure login

Required Before Running:

  1. AWS CLI configured with valid credentials

  2. Existing key pair named "my-keypair" in AWS

  3. Valid AMI ID for your region (the example AMI may be outdated)


Terraform Workflow in Action

Once your main.tf is ready, run Terraform’s standard workflow.

Step 1: Initialize Terraform

terraform init

This downloads the AWS provider and prepares the working directory.

Step 2: Validate Configuration

terraform validate

Ensures your .tf files are syntactically correct.

Step 3: Preview the Execution Plan

terraform plan

Terraform compares the desired state (from main.tf) with the current state (empty for now) and shows what actions will be taken.

Example output:

Plan: 2 to add, 0 to change, 0 to destroy.

Step 4: Apply the Configuration

# Interactive mode (recommended for learning/safety)
terraform apply

# Non-interactive mode (for automation/scripts)
terraform apply --auto-approve

Confirm with yes when prompted.
Terraform will create the security group and EC2 instance automatically.

Once done, you’ll see:

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

aws_instance.web.public_ip = "3.89.123.45"

Your instance is now live in AWS — created entirely from code.


Step 5: Verify on AWS Console

Go to your AWS Console → EC2 → Instances.
You’ll see an instance named Terraform-EC2-Demo running in your specified region.


Step 6: Destroy Infrastructure (Optional)

To tear down the environment and avoid charges:

terraform destroy

Terraform will gracefully remove all created resources.


6. Understanding What Happened Behind the Scenes

Here’s a simplified view of how Terraform executed your request:

+-------------------------------------+
| Terraform Config (.tf)              |
+-----------------+-------------------+
                  |
                  v
+-------------------------------------+
| Terraform CLI                       |
| init → validate →plan → apply       |
+-----------------+-------------------+
                  |
                  v
+-------------------------------------+
| AWS Provider Plugin                 |
| (via APIs)                          |
+-----------------+-------------------+
                  |
                  v
+-------------------------------------+
| AWS Infrastructure (EC2)            |
+-------------------------------------+

Terraform read your .tf file, authenticated using the IAM credentials, generated a plan, and applied it through the AWS provider plugin using AWS APIs.


7. Best Practices for Secure and Scalable Use

  • Never hardcode credentials in .tf files. Use AWS CLI profiles or environment variables.

  • Store Terraform state remotely (e.g., S3 backend + DynamoDB for locking).

  • Use separate IAM roles for dev/staging/prod environments.

  • Enable least privilege policies for long-term automation.

  • Run terraform fmt and terraform validate before every plan/apply.


Conclusion: From Zero to Cloud in Minutes

With Terraform installed and authenticated, you’ve just automated the creation of a real AWS EC2 instance — no clicks, no console navigation, no manual drift.

This is the power of Infrastructure as Code in action — infrastructure that’s:

  • Repeatable

  • Version-controlled

  • Auditable

  • Scalable

In the next article, we’ll take this further by introducing Terraform state management, modules, and remote backend configuration — the building blocks of production-grade IaC.

You’ve just coded your first cloud resource — and the sky is no longer the limit.