DEV Community

Cover image for Infrastructure as Code (IaC) with Terraform (AWS EC2 Example)
Željko Šević
Željko Šević

Posted on Edited on Originally published at sevic.dev

Infrastructure as Code (IaC) with Terraform (AWS EC2 Example)

Infrastructure as Code (IaC) is a DevOps approach where infrastructure is defined and managed using code instead of manual setup. This makes environments reproducible, version-controlled, and easy to scale.

In this guide, you'll provision an AWS EC2 instance using Terraform.

Requirements

Before starting, install:

  • Terraform
  • AWS CLI

AWS Credentials Setup

  1. Go to IAM → Security credentials in AWS
  2. Create access keys
  3. Configure locally:
aws configure
Enter fullscreen mode Exit fullscreen mode

This stores credentials in:

  • ~/.aws/credentials
  • ~/.aws/config

Project Structure

A simple Terraform setup:

.
├── main.tf
├── variables.tf
├── terraform.tfvars
├── outputs.tf
Enter fullscreen mode Exit fullscreen mode

Provider Configuration

Define your cloud provider in main.tf:

provider "aws" {
  profile = "default"
  region  = "eu-north-1"
}
Enter fullscreen mode Exit fullscreen mode

Variables

Define reusable variables in variables.tf:

variable "instance_name" {
  description = "Name tag for EC2 instance"
  type        = string
  default     = "MyNewInstance"
}

variable "ec2_instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"
}
Enter fullscreen mode Exit fullscreen mode

Set values in terraform.tfvars:

instance_name      = "MyEC2Name"
ec2_instance_type  = "t3.micro"
Enter fullscreen mode Exit fullscreen mode

EC2 Instance Configuration

Add the resource in main.tf:

resource "aws_instance" "app_server" {
  ami           = "ami-077d1b9f9a1902bbc"
  instance_type = var.ec2_instance_type

  tags = {
    Name = var.instance_name
  }
}
Enter fullscreen mode Exit fullscreen mode

You can find AMI IDs in EC2 → Images → AMI Catalog.

Outputs

Expose useful data in outputs.tf:

output "instance_id" {
  description = "EC2 instance ID"
  value       = aws_instance.app_server.id
}

output "instance_public_ip" {
  description = "Public IP address"
  value       = aws_instance.app_server.public_ip
}
Enter fullscreen mode Exit fullscreen mode

Terraform Workflow

Initialize the project:

  • terraform init

Preview changes:

  • terraform plan

Apply changes:

  • terraform apply

Destroy infrastructure:

  • terraform destroy

Important Notes

  • State file

Terraform stores infrastructure state in terraform.tfstate.

Do not commit this file to Git.

  • Remote state (recommended)

For teams, store state in S3 with locking.

  • Idempotency

Running apply multiple times won’t recreate resources unnecessarily.

  • Version control

Treat Terraform code like application code.

Need help with your project?

Get personalized advice on your architecture, code, or career in a 45-minute 1-on-1 consultation.

Book a consultation

Top comments (0)