This page shows how to create an AWS EC2 instance with an extra EBS data volume using Terraform. It uses three resources: aws_instance, aws_ebs_volume and aws_volume_attachment. Below the original example you will find a complete, runnable version with a provider block, a current AMI lookup, encryption and gp3 storage, plus the steps to format and mount the disk and fixes for common errors.
How the example works
The example above declares three resources. Terraform works out the order from the references between them: it creates the instance and the volume first, because the attachment refers to both IDs, and creates the attachment last.
| Resource | Purpose | Key arguments |
|---|---|---|
aws_instance | Launches the EC2 virtual machine | ami, instance_type, availability_zone |
aws_ebs_volume | Creates a standalone block storage volume | availability_zone, size (GiB), type, encrypted |
aws_volume_attachment | Attaches the volume to the instance | device_name, volume_id, instance_id |
Note: An EBS volume can only be attached to an instance in the same Availability Zone. That is why both resources in the example use ap-south-1a. If the two values differ, the attachment fails.
The example works as a starting point, but it is not complete. It has no provider configuration, it uses a hardcoded AMI ID that only exists in one region and may no longer be available, and it leaves the volume unformatted. The sections below fix these gaps.
Prerequisites
- Terraform CLI installed (
terraform -version). - AWS credentials available to Terraform, for example through
aws configure, environment variables or an IAM role. The identity needs permissions for EC2 instances, volumes, volume attachments andec2:DescribeImages. - A default VPC in the target region, or a subnet ID you can pass to the instance.
- An existing EC2 key pair or AWS Systems Manager Session Manager access if you plan to log in and mount the volume.
Corrected and complete configuration
This version can be run as is. It adds the terraform and provider blocks, looks up the latest Amazon Linux 2023 AMI instead of hardcoding an ID, takes the volume's Availability Zone from the instance so the two always match, and sets the volume type to gp3 with encryption turned on.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 5.0"
}
}
}
variable "region" {
type = string
default = "ap-south-1"
}
variable "availability_zone" {
type = string
default = "ap-south-1a"
}
provider "aws" {
region = var.region
}
# Latest Amazon Linux 2023 AMI for the selected region
data "aws_ami" "al2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.al2023.id
instance_type = "t3.micro"
availability_zone = var.availability_zone
# key_name = "my-key-pair" # uncomment to allow SSH
tags = {
Name = "HelloWorld"
}
}
resource "aws_ebs_volume" "data" {
availability_zone = aws_instance.web.availability_zone
size = 40
type = "gp3"
encrypted = true
tags = {
Name = "HelloWorld-data"
}
}
resource "aws_volume_attachment" "data_att" {
device_name = "/dev/sdf"
volume_id = aws_ebs_volume.data.id
instance_id = aws_instance.web.id
}
output "instance_id" {
value = aws_instance.web.id
}
output "volume_id" {
value = aws_ebs_volume.data.id
}
output "public_ip" {
value = aws_instance.web.public_ip
}Code language: PHP (php)
data "aws_ami"finds the newest matching Amazon-owned image at plan time, so the configuration works in any region.availability_zone = aws_instance.web.availability_zoneremoves the duplicated AZ string and creates a dependency, so the volume is always created in the instance's AZ.type = "gp3"sets the volume type explicitly. gp3 gives a baseline of 3,000 IOPS and 125 MiB/s regardless of size, and you can raise both withiopsandthroughput.encrypted = trueencrypts the volume with the AWS managed EBS key unless you setkms_key_id.- The outputs print the IDs and public IP after
apply. You need them for the mounting steps.
Deploy and verify
- Save the configuration as
main.tfin an empty directory. - Run
terraform initto download the AWS provider. - Run
terraform fmtandterraform validateto catch syntax errors. - Run
terraform planand check that it shows 3 resources to add. - Run
terraform applyand typeyeswhen prompted. - Check the attachment with the AWS CLI.
terraform init
terraform fmt
terraform validate
terraform plan
terraform apply
# Expected at the end of apply:
# Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
aws ec2 describe-volumes \
--volume-ids $(terraform output -raw volume_id) \
--query 'Volumes[0].Attachments[0].[InstanceId,Device,State]' \
--output text
# i-0abc123... /dev/sdf attachedCode language: PHP (php)
Format and mount the volume inside the instance
Terraform attaches a raw block device. The operating system cannot store files on it until you create a filesystem and mount it. On Nitro-based instance types such as t3, the volume attached as /dev/sdf appears in Linux as an NVMe device, usually /dev/nvme1n1. Always check with lsblk before formatting.
# Identify the new 40 GiB disk (no MOUNTPOINT, no partitions)
lsblk
# Confirm it has no filesystem yet; output 'data' means empty
sudo file -s /dev/nvme1n1
# Create a filesystem (ONLY on a new, empty volume)
sudo mkfs -t xfs /dev/nvme1n1
# Mount it
sudo mkdir -p /data
sudo mount /dev/nvme1n1 /data
df -h /data
# Make the mount persistent across reboots using the UUID
UUID=$(sudo blkid -s UUID -o value /dev/nvme1n1)
echo "UUID=$UUID /data xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab
sudo mount -aCode language: PHP (php)
Note: Running mkfs on a volume that already holds data erases it. Use the UUID in /etc/fstab rather than the device name, because NVMe device names can change between boots. The nofail option lets the instance boot even if the volume is detached.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
InvalidAMIID.NotFound or InvalidAMIID.Malformed | The hardcoded AMI ID does not exist in the current region or has been deregistered | Use the aws_ami data source shown above, or look up a current AMI ID for your region |
InvalidVolume.ZoneMismatch | The volume and instance are in different Availability Zones | Set the volume's availability_zone from aws_instance.web.availability_zone |
Unsupported instance type in the requested Availability Zone | The instance type is not offered in that AZ | Choose another AZ or instance type |
Volume detach hangs or times out during terraform destroy | The volume is still mounted and in use inside the OS | Unmount it first, or set stop_instance_before_detaching = true on aws_volume_attachment |
InvalidParameterValue for the device name | The device name is already in use or not valid for the instance | Use an unused name in the range /dev/sdf to /dev/sdp |
UnauthorizedOperation | The IAM identity lacks EC2 permissions | Grant the required EC2 actions or use a role that has them |
Separate volume resource or inline ebs_block_device
Terraform can also define extra disks inline with an ebs_block_device block inside aws_instance. The separate-resource pattern used in this example is usually the better choice for data disks.
| Approach | Lifecycle | Typical use |
|---|---|---|
aws_ebs_volume + aws_volume_attachment | Volume exists independently and can be detached and reattached to a replacement instance | Persistent data disks |
ebs_block_device inside aws_instance | Created and normally destroyed with the instance; changes often force instance replacement | Scratch or disposable disks |
root_block_device inside aws_instance | Controls the boot volume size, type and encryption | Resizing or encrypting the root disk |
Note: Do not manage the same instance's extra volumes with both ebs_block_device and aws_volume_attachment. The two methods conflict and cause constant drift in terraform plan.
Best practices
- Always set
encrypted = trueor turn on EBS encryption by default for the account and region. - Prefer
gp3overgp2: performance does not depend on volume size, and it typically costs less per GiB. - Add
lifecycle { prevent_destroy = true }to data volumes that must survive a carelessterraform destroy. - Back up data volumes with EBS snapshots or AWS Backup. Terraform state does not protect your data.
- Use variables for region, AZ, size and instance type, and use
countorfor_eachto create several volumes. See Terraform Loops and Iteration. - Run
terraform fmt,validateand security scanners automatically with pre-commit for Terraform. - Run
terraform destroyafter lab exercises so that instances and volumes do not keep running up charges.
Frequently asked questions
Why does my EBS volume show as /dev/nvme1n1 instead of /dev/sdf?
On Nitro-based instance types, EBS volumes are exposed as NVMe devices, whatever device name you set in Terraform. Use lsblk to find the disk, and use the filesystem UUID in /etc/fstab.
Can I attach an EBS volume to an instance in a different Availability Zone?
No. A volume can only attach to an instance in the same Availability Zone. To move data to another AZ, take a snapshot and create a new volume from it in the target AZ.
Does terraform destroy delete the EBS volume?
Yes. Running terraform destroy on this configuration detaches and deletes the volume along with the instance. Add prevent_destroy in a lifecycle block, or take a snapshot first, if the data must be kept.
How do I increase the size of the EBS volume with Terraform?
Change size to a larger value and run terraform apply. EBS volumes can be resized in place, but you must then grow the filesystem inside the OS, for example with sudo xfs_growfs /data for XFS. EBS volumes cannot be shrunk.
Does Terraform format and mount the volume automatically?
No. Terraform only creates and attaches the block device. You format and mount it manually, as shown above, or with configuration management or a user data script that waits for the device to appear.
Related tutorials
- More Terraform tutorials
- Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks
- How to Configure pre-commit for Terraform: Complete DevOps Guide with 15 Practical Use Cases, Commands, Security Checks, and Best Practices
- More AWS tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals