Skip to content
masdzub.com
~/articles/terraform — one from the notebook

Terraform Provision EC2 Instances and Security Groups

Provision EC2 instances and security groups using Terraform with VPC and variable definitions.

masdzub@website:~$ cat ~/articles/iac-provisioning-write-terraform-code-to-provision-ec2-instances-and-security-groups.aspx.md
# 1 file · 3 min read · topic: terraform · status: published

Project Setup

Create a directory for the project and initialize the Terraform state file locally.

Terminal window
mkdir terraform-ec2-sg && cd terraform-ec2-sg
terraform init

Backend Configuration

Define the backend to store the state in the current directory. This avoids S3 requirements for simple setups.

backend.tf

terraform {
backend "local" {
path = "terraform.tfstate"
}
}

Variables

Define flexible inputs for the instance type and AMI ID. Use data sources to fetch the default AMI automatically.

variables.tf

variable "instance_type" {
type = string
default = "t3.micro"
description = "EC2 instance type to provision"
}
variable "aws_region" {
type = string
default = "us-east-1"
description = "AWS region for resources"
}

data.tf

data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
}

Infrastructure Definition

Configure the security group and EC2 instance. The security group allows HTTP traffic from anywhere to expose a web server.

main.tf

provider "aws" {
region = var.aws_region
}
resource "aws_security_group" "web_server_sg" {
name = "terraform-web-server-sg"
description = "Allow HTTP inbound traffic"
vpc_id = data.aws_vpc.default.id
tags = {
Name = "terraform-web-server-sg"
}
}
resource "aws_vpc_security_group_ingress_rule" "allow_http_ipv4" {
security_group_id = aws_security_group.web_server_sg.id
cidr_ipv4 = "0.0.0.0/0"
from_port = 80
ip_protocol = "tcp"
to_port = 80
}
resource "aws_vpc_security_group_egress_rule" "allow_all_traffic_ipv4" {
security_group_id = aws_security_group.web_server_sg.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1" # semantically equivalent to all ports
}
resource "aws_instance" "web_server" {
ami = data.aws_ami.amazon_linux.id
instance_type = var.instance_type
subnet_id = data.aws_subnet.default.id
vpc_security_group_ids = [aws_security_group.web_server_sg.id]
tags = {
Name = "terraform-web-server"
}
}

data.tf (Add defaults for VPC/Subnet if not present)

data "aws_vpc" "default" {
default = true
}
data "aws_subnet" "default" {
vpc_id = data.aws_vpc.default.id
default_for_az = true
}

Outputs

Capture the public IP address for easy access.

outputs.tf

output "instance_public_ip" {
value = aws_instance.web_server.public_ip
description = "Public IP address of the EC2 instance"
}

Provision Infrastructure

Apply the configuration to create resources.

Terminal window
terraform apply -auto-approve

Troubleshooting

  • Error: Error: Error creating Security Group: OperationNotPermitted

    • Cause: Your AWS user account likely lacks the iam:CreateVpcs or ec2:CreateSecurityGroup permissions.
    • Fix: Attach the policy AdministratorAccess or a specific inline policy granting ec2:* permissions to your IAM user.
  • Error: Error: no matching subnet for availability zone

    • Cause: The default_for_az = true subnet does not exist or is in a different region.
    • Fix: Verify the aws_region variable matches the region where the default VPC exists, or explicitly define a subnet ID in variables.
  • Error: Error: failed to import: not found

    • Cause: Terraform state does not contain the resource ID, but the resource already exists in AWS.
    • Fix: Run terraform import aws_instance.web_server <instance_id> or use terraform plan -destroy if the resource is no longer needed.
skipped: vpc creation, manual subnet selection, complex state locking. Add VPC module when multi-region or isolated networking is required.
found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.