AWS EC2 with Terraform: Step-by-Step Beginner Guide

Published: 2025-08-28
8 min read
Share:

AWS EC2 with Terraform is one of the most practical ways to learn Infrastructure as Code (IaC). Instead of manually creating virtual machines through the AWS console, you can define your infrastructure in code and deploy it consistently whenever needed.

For most Terraform users, launching an EC2 instance is the first real-world project. It introduces core Terraform concepts such as providers, resources, outputs, dependencies, and automation.

In this guide, you'll learn how to deploy an AWS EC2 instance with Terraform, configure secure SSH access, automate server setup, and manage your infrastructure using repeatable code.

If you're new to Terraform, consider reading our guide on getting started with Terraform on AWS before continuing.

Why Use AWS EC2 with Terraform?

Amazon EC2 (Elastic Compute Cloud) provides scalable virtual servers in AWS. Terraform allows you to provision and manage those servers through code.

Using EC2 with Terraform provides several advantages:

  • Version infrastructure alongside application code.
  • Reduce manual AWS console work.
  • Create consistent environments across development, testing, and production.
  • Automate deployments and updates.
  • Reuse infrastructure configurations across teams.
  • Track infrastructure changes through Git.

The same Terraform workflow can manage a single EC2 instance or an entire cloud environment.

What You'll Build

By the end of this tutorial, you'll deploy:

  • An AWS EC2 instance
  • An AWS key pair for SSH access
  • A security group for network access
  • A bootstrap script using user data
  • An output variable that displays the public IP address

Prerequisites

Before starting, ensure you have:

  • An AWS account
  • Terraform installed locally
  • AWS CLI configured with credentials
  • Basic knowledge of AWS and Terraform

If Terraform is not installed, follow our guide on installing Terraform.

You should also understand how Terraform AWS providers work because Terraform communicates with AWS through provider plugins.

Configure the AWS Provider

Before creating resources, Terraform must know which cloud provider to use.

Create a provider.tf file:

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

The AWS provider is maintained through the official Terraform Registry.

Terraform will use AWS credentials from your configured AWS CLI profile, environment variables, or supported authentication methods.

How to Deploy AWS EC2 with Terraform

Let's start with the core resource—the EC2 instance itself.

Create a file named main.tf.

resource "aws_instance" "web_server" {
  ami           = "ami-xxxxxxxxxxxxxxxxx"
  instance_type = "t2.micro"

  tags = {
    Name        = "web-server"
    Description = "NGINX web server on Ubuntu"
  }
}

This configuration creates a lightweight EC2 instance.

Replace the AMI ID with a valid AMI available in your chosen AWS region. You can find available AMIs in the AWS Console or through the Amazon EC2 Documentation.

Cost Note

Many tutorials use t2.micro because it has historically been eligible for AWS Free Tier programs. Always verify current AWS pricing and Free Tier eligibility before deploying resources.

Automatically Install Software Using User Data

Creating a server is only part of the process. Most workloads require software installation and configuration during launch.

Terraform supports this using the user_data argument.

resource "aws_instance" "web_server" {
  ami           = "ami-xxxxxxxxxxxxxxxxx"
  instance_type = "t2.micro"

  user_data = <<-EOF
              #!/bin/bash
              apt update
              apt install nginx -y
              EOF

  tags = {
    Name = "web-server"
  }
}

When the instance starts, AWS executes the script automatically.

In this example:

  • The package repository is updated.
  • NGINX is installed automatically.
  • The server is ready for web traffic immediately after launch.

You can add additional commands to install applications, create users, configure services, or deploy application code.

Create an SSH Key Pair for Secure Access

To connect to the EC2 instance through SSH, create an AWS key pair.

resource "aws_key_pair" "web_key" {
  key_name   = "web-key"
  public_key = file("~/.ssh/web.pub")
}

Next, associate the key pair with the EC2 instance.

resource "aws_instance" "web_server" {
  ami           = "ami-xxxxxxxxxxxxxxxxx"
  instance_type = "t2.micro"

  key_name = aws_key_pair.web_key.key_name
}

Terraform will upload the public key to AWS and associate it with the instance.

After deployment, you can authenticate using the corresponding private key stored on your machine.

Allow SSH Access with an AWS Security Group

Without a security group rule, SSH connections will fail even if the instance is running.

Create a security group:

resource "aws_security_group" "ssh_access" {
  name        = "ssh-access"
  description = "Allow SSH access"

  ingress {
    from_port   = 22
    to_port     = 22
    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"]
  }
}

Attach the security group to the EC2 instance:

resource "aws_instance" "web_server" {
  ami                    = "ami-xxxxxxxxxxxxxxxxx"
  instance_type          = "t2.micro"
  key_name               = aws_key_pair.web_key.key_name
  vpc_security_group_ids = [aws_security_group.ssh_access.id]
}

Production Tip

Opening port 22 to 0.0.0.0/0 is acceptable for isolated testing environments but should be avoided in production.

A better approach is to:

  • Restrict access to trusted IP addresses.
  • Use a VPN.
  • Use AWS Systems Manager Session Manager.
  • Limit administrative access through bastion hosts.

One of the most common beginner mistakes is creating a security group but forgetting to attach it to the EC2 instance. Terraform will deploy successfully, but SSH access won't work.

Display the EC2 Public IP After Deployment

After deployment, you'll need the public IP address to connect to the server.

Use a Terraform output variable:

output "web_server_ip" {
  value = aws_instance.web_server.public_ip
}

If you're unfamiliar with outputs, read our guide on Terraform output variables.

Terraform will display the public IP after deployment completes.

Example SSH command:

ssh -i ~/.ssh/web.pem ubuntu@<public-ip>

Replace <public-ip> with the value returned by Terraform.

Deploy the Infrastructure with Terraform

Initialize the working directory:

terraform init

This command downloads the required providers and prepares the project.

Review the execution plan:

terraform plan

Terraform shows the resources it intends to create before making any changes.

Deploy the infrastructure:

terraform apply

Terraform will:

  • Create the key pair.
  • Create the security group.
  • Launch the EC2 instance.
  • Execute the user data script.
  • Display the public IP output.

If you modify the configuration later, running terraform apply again updates only the resources that changed.

Verify the Deployment

After deployment:

  1. Open the AWS Console.
  2. Navigate to EC2.
  3. Confirm the instance is running.
  4. Verify the security group configuration.
  5. Connect through SSH.
  6. Confirm NGINX is installed.

You can also verify infrastructure state using Terraform commands covered in our guide on Terraform state commands.

Best Practices for AWS EC2 with Terraform

As your infrastructure grows, following best practices becomes increasingly important.

  • Store Terraform code in Git repositories.
  • Use remote state storage with S3.
  • Enable state locking.
  • Separate environments using workspaces.
  • Reuse code through modules.
  • Apply least-privilege IAM permissions.
  • Avoid hardcoding sensitive values.

For larger deployments, these guides will help:

Frequently Asked Questions

Do I need a public key to connect to an EC2 instance?

Yes. When using SSH-based authentication, AWS requires a key pair. Terraform can upload the public key using the aws_key_pair resource.

Can I change the AMI after deployment?

Yes. Update the ami attribute and run terraform plan followed by terraform apply.

Depending on the change, Terraform may replace the instance.

Is opening port 22 to all IP addresses safe?

No. Production environments should restrict access to trusted IP ranges or use more secure alternatives such as VPNs or AWS Systems Manager Session Manager.

Can I install multiple packages using user data?

Yes. The user data script can contain multiple commands that run during instance initialization.

How do I destroy the EC2 instance?

Run:

terraform destroy

Terraform will remove all resources managed by the configuration.

What AWS permissions are required?

At minimum, the IAM identity used by Terraform needs permissions to create and manage EC2 instances, security groups, key pairs, and related networking resources.

Can I use Amazon Linux instead of Ubuntu?

Yes. Simply replace the Ubuntu AMI with a supported Amazon Linux AMI from your AWS region.

Final Thoughts

Deploying AWS EC2 with Terraform is one of the fastest ways to learn Infrastructure as Code in a practical setting.

Once you've launched your first instance, you'll see how much easier infrastructure management becomes when everything is defined in code. Instead of repeating manual AWS console steps, you can version, review, and reproduce environments consistently across teams and projects.

The same concepts used here—providers, resources, outputs, security groups, and automation—form the foundation for managing larger AWS environments with Terraform.

Free Engineering ToolsNEW

8 free, 100% client-side tools for developers — no signup, no data uploads.

Explore all tools