MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform Example – AWS EC2 Instance with EBS

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.

ResourcePurposeKey arguments
aws_instanceLaunches the EC2 virtual machineami, instance_type, availability_zone
aws_ebs_volumeCreates a standalone block storage volumeavailability_zone, size (GiB), type, encrypted
aws_volume_attachmentAttaches the volume to the instancedevice_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 and ec2: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_zone removes 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 with iops and throughput.
  • encrypted = true encrypts the volume with the AWS managed EBS key unless you set kms_key_id.
  • The outputs print the IDs and public IP after apply. You need them for the mounting steps.

Deploy and verify

  1. Save the configuration as main.tf in an empty directory.
  2. Run terraform init to download the AWS provider.
  3. Run terraform fmt and terraform validate to catch syntax errors.
  4. Run terraform plan and check that it shows 3 resources to add.
  5. Run terraform apply and type yes when prompted.
  6. 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

ErrorCauseFix
InvalidAMIID.NotFound or InvalidAMIID.MalformedThe hardcoded AMI ID does not exist in the current region or has been deregisteredUse the aws_ami data source shown above, or look up a current AMI ID for your region
InvalidVolume.ZoneMismatchThe volume and instance are in different Availability ZonesSet the volume's availability_zone from aws_instance.web.availability_zone
Unsupported instance type in the requested Availability ZoneThe instance type is not offered in that AZChoose another AZ or instance type
Volume detach hangs or times out during terraform destroyThe volume is still mounted and in use inside the OSUnmount it first, or set stop_instance_before_detaching = true on aws_volume_attachment
InvalidParameterValue for the device nameThe device name is already in use or not valid for the instanceUse an unused name in the range /dev/sdf to /dev/sdp
UnauthorizedOperationThe IAM identity lacks EC2 permissionsGrant 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.

ApproachLifecycleTypical use
aws_ebs_volume + aws_volume_attachmentVolume exists independently and can be detached and reattached to a replacement instancePersistent data disks
ebs_block_device inside aws_instanceCreated and normally destroyed with the instance; changes often force instance replacementScratch or disposable disks
root_block_device inside aws_instanceControls the boot volume size, type and encryptionResizing 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 = true or turn on EBS encryption by default for the account and region.
  • Prefer gp3 over gp2: 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 careless terraform 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 count or for_each to create several volumes. See Terraform Loops and Iteration.
  • Run terraform fmt, validate and security scanners automatically with pre-commit for Terraform.
  • Run terraform destroy after 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals

Related Posts

AWS Tutorial: Auto mount EBS Volume to ec2 Linux instance on Reboot

To make an extra Amazon EBS volume mount automatically after an EC2 Linux instance reboots, add an entry for it to /etc/fstab. Refer to the volume by…

Read More

EC2 Boot from EBS Explained: Architecture, Trade-offs, and an AWS CLI Workflow

Booting Amazon EC2 instances from Amazon EBS was a major shift from ephemeral root disks to persistent root volumes. This guide explains what changed, why it mattered, and how to use the model safely in modern operations.

Read More

Cloud Tools Adds Amazon EBS Support: Durable EC2 Storage for Database Workloads

This historical update covers when Cloud Tools introduced Amazon EBS support for EC2 applications, including database-backed deployments. It explains the supported storage modes, the backup/restore flow, and practical command-level equivalents.

Read More

AWS Tutorials: EBS – Steps to Increase the Disk Size on a Running EC2 Instance:

you can increase the disk size of an Amazon EC2 instance while it is running. Amazon allows you to modify the size of an Elastic Block Store…

Read More

AWS Storage: FAQ

Can u attach Aws vm or you can’t attach disks to a running VM? Yes, you can attach EBS volumes to running EC2 instances in AWS. This…

Read More

AWS Tutorial: How to Attach and Mount an EBS volume to EC2 Linux Instance?

Step 1 – Create a Volume Step 2 – Attach a Volume to EC2 Instance Step 3 – Verify if Volume is attached or not Verify if…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x