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
- Go to IAM → Security credentials in AWS
- Create access keys
- Configure locally:
aws configure
This stores credentials in:
~/.aws/credentials~/.aws/config
Project Structure
A simple Terraform setup:
.├── main.tf├── variables.tf├── terraform.tfvars├── outputs.tf
Provider Configuration
Define your cloud provider in main.tf:
provider "aws" {profile = "default"region = "eu-north-1"}
Variables
Define reusable variables in variables.tf:
variable "instance_name" {description = "Name tag for EC2 instance"type = stringdefault = "MyNewInstance"}variable "ec2_instance_type" {description = "EC2 instance type"type = stringdefault = "t3.micro"}
Set values in terraform.tfvars:
instance_name = "MyEC2Name"ec2_instance_type = "t3.micro"
EC2 Instance Configuration
Add the resource in main.tf:
resource "aws_instance" "app_server" {ami = "ami-077d1b9f9a1902bbc"instance_type = var.ec2_instance_typetags = {Name = var.instance_name}}
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}
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 via DynamoDB.
- Idempotency
Running apply multiple times won’t recreate resources unnecessarily.
- Version control
Treat Terraform code like application code.