Learning terraform ec2 provisioning is the fastest way to make infrastructure as code (IaC) click for a beginner. Instead of clicking through the AWS console to launch a virtual server, you describe the server you want in a declarative configuration file, and Terraform builds exactly that — every time, on every environment. This guide walks you through provisioning a real AWS EC2 instance with Terraform on Linux, from installation to cleanup, with variables, outputs, and state management best practices included. This article covers Terraform First Steps in detail.

By the end of this terraform ec2 tutorial you will have a repeatable workflow: terraform init, terraform plan, terraform apply, and terraform destroy. You will also learn how to look up the latest Amazon Linux 2023 AMI dynamically, keep secrets out of your code, and avoid the classic state-file mistakes that trip up newcomers.
Prerequisites – Terraform First Steps
- A Linux machine (Ubuntu 22.04/24.04, Debian 12, or AlmaLinux 8/9) with sudo access.
- An AWS account with programmatic access: an IAM user (or role credentials) that has
ec2:RunInstances,ec2:DescribeImages, and related EC2 permissions. For a first test, theAmazonEC2FullAccessmanaged policy is the simplest choice. - Your AWS access key ID and secret access key, plus the region you want to deploy in (e.g.
us-east-1). - Basic comfort with the Linux terminal and editing text files.
Step 1: Install Terraform on Linux – Terraform First Steps
Install Terraform from HashiCorp’s official package repository rather than your distro’s default repos, so you get a current, supported release. The commands below work on Debian/Ubuntu:
# Add the HashiCorp GPG key
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
# Add the official HashiCorp repository
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
# Install Terraform
sudo apt update
sudo apt install -y terraform
# Verify the installation
terraform version
On RHEL-family systems (AlmaLinux, Rocky Linux) use the official RPM repository instead:
sudo dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo dnf install -y terraform
terraform version
You should see output like Terraform v1.9.x. If the version command works, the terraform ec2 journey can begin.
Step 2: Configure AWS Credentials (Never Hardcode Keys)
The AWS provider for Terraform reads standard AWS SDK credentials. The cleanest approach for a workstation is environment variables — never paste keys into your .tf files:
export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_REGION="us-east-1"
Add these lines to your ~/.bashrc (or use a tool like direnv) so they persist across sessions. If you use the AWS CLI, running aws configure once is an equivalent alternative — the Terraform AWS provider reads the same shared credentials file at ~/.aws/credentials.
Step 3: Write the Provider and EC2 Configuration
Create a project directory and a main.tf file. This is the heart of your terraform ec2 configuration:
mkdir -p ~/terraform-ec2-first
cd ~/terraform-ec2-first
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
Note that no access keys appear here — the provider picks them up from the environment automatically. The required_providers block pins the AWS provider to a known-good major version, which protects you from breaking changes.
Step 4: Look Up the Latest Amazon Linux 2023 AMI
Hardcoding an AMI ID is fragile: IDs differ per region and go stale as Amazon publishes updates. Use a data source to query the newest Amazon Linux 2023 image at plan time:
data "aws_ami" "amazon_linux_2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
Now define the instance itself:
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux_2023.id
instance_type = var.instance_type
tags = {
Name = "terraform-ec2-first"
Environment = "dev"
ManagedBy = "terraform"
}
}
A t3.micro instance type (set via the instance_type variable we will define next) is eligible for the AWS Free Tier in most regions, making this terraform ec2 experiment effectively free.
Step 5: Add Variables and Outputs
Variables make your configuration reusable. Create variables.tf:
variable "aws_region" {
description = "AWS region to deploy the EC2 instance in"
type = string
default = "us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
validation {
condition = can(regex("^t[23]\\.", var.instance_type))
error_message = "Stick to t2/t3 burstable types for this tutorial."
}
}
Outputs expose useful values after a successful apply. Create outputs.tf:
output "instance_id" {
description = "ID of the created EC2 instance"
value = aws_instance.web.id
}
output "public_ip" {
description = "Public IP address of the instance"
value = aws_instance.web.public_ip
}
output "ami_used" {
description = "AMI ID that was actually deployed"
value = data.aws_ami.amazon_linux_2023.id
}
Step 6: Initialize, Plan, and Apply (Terraform EC2 Workflow)
Run the classic three-command terraform ec2 workflow:
# Download the AWS provider plugin into .terraform/
terraform init
# Check formatting and syntax
terraform fmt
terraform validate
# Preview exactly what will be created
terraform plan
Read the plan output carefully: it should show Plan: 1 to add, 0 to change, 0 to destroy with the aws_instance.web resource. If the plan looks right, apply it:
terraform apply
Type yes when prompted. Within a minute or two Terraform reports Apply complete! along with your outputs. Verify in the AWS console or with the CLI:
aws ec2 describe-instances --instance-ids $(terraform output -raw instance_id) \
--query 'Reservations[0].Instances[0].State.Name' --output text
Once you can SSH in, consider locking the instance down: instead of opening port 22 to the world, manage it over AWS Systems Manager Session Manager with no open ports, which keeps your security groups tight while giving you full shell access.
Step 7: Understand State and Protect It
After the first apply, Terraform wrote terraform.tfstate — the record of what it manages. Terraform compares your configuration against this state file on every run, which is why deleting a resource from .tf files and re-applying destroys it in AWS. Treat the state file with care:
- It can contain sensitive data (in plain text), so never commit it to a public repository.
- Add a
.gitignorewith at minimum:.terraform/ *.tfstate *.tfstate.backup *.tfvars !example.tfvars - For team or production use, move state to a remote backend such as an S3 bucket with DynamoDB locking — but local state is fine for this first terraform ec2 project.
Step 8: Destroy Your Terraform EC2 Instance
Idle EC2 instances cost money. When the experiment is over, tear everything down with one command:
terraform destroy
Confirm with yes. Terraform reads the state file, terminates the instance, and reports Destroy complete!. Because every resource was declared in code, nothing is left behind — one of the core promises of the terraform ec2 approach.
Troubleshooting Common Terraform EC2 Errors
“No valid credential sources found”
Your environment variables are not exported in the shell running Terraform. Re-export them, or run aws sts get-caller-identity to confirm the AWS CLI sees the same credentials.
“Error: configuring Terraform AWS Provider: no valid credential sources”
This is the same root cause with a longer message. Double-check for typos in AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, and confirm the region variable matches a real AWS region.
AMI data source returns no results
The al2023-ami-2023.*-x86_64 name filter must match your region. If you are deploying on ARM (Graviton), switch the filter to al2023-ami-2023.*-arm64 and use a t4g.micro instance type.
“InstanceLimitExceeded” or “VcpuLimitExceeded”
New AWS accounts have low vCPU quotas. Request a limit increase in the Service Quotas console, or start with a single t3.micro which fits inside the default quota.
Plan wants to replace the instance on every run
Something in your configuration forces replacement — often an AMI data source that resolves to a newer image each time. That is actually correct behavior: pin the AMI ID in a variable if you want stability across runs.
Conclusion
You have completed your first real terraform ec2 workflow: installing Terraform from the official repository, authenticating without hardcoded secrets, declaring an EC2 instance with a dynamically looked-up AMI, previewing changes with plan, applying them, exposing outputs, and destroying everything cleanly. The same four commands — init, plan, apply, destroy — scale from this single instance to entire VPCs, databases, and Kubernetes clusters. Your next steps: explore the official Terraform documentation to learn about modules, workspaces, and remote state backends, then try adding a security group and an Elastic IP to this project to deepen your IaC skills.