{"id":31041,"date":"2026-12-03T22:04:11","date_gmt":"2026-12-03T22:04:11","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=31041"},"modified":"2026-12-03T22:04:11","modified_gmt":"2026-12-03T22:04:11","slug":"terraform-example-aws-ec2-instance-with-ebs","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/terraform-example-aws-ec2-instance-with-ebs\/","title":{"rendered":"Terraform Example &#8211; AWS EC2 Instance with EBS"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This page shows how to create an AWS EC2 instance with an extra EBS data volume using Terraform. It uses three resources: <code>aws_instance<\/code>, <code>aws_ebs_volume<\/code> and <code>aws_volume_attachment<\/code>. 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.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/8be11b4605021f67c11e3a58eaadc7cd.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How the example works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Resource<\/th><th>Purpose<\/th><th>Key arguments<\/th><\/tr><\/thead><tbody><tr><td><code>aws_instance<\/code><\/td><td>Launches the EC2 virtual machine<\/td><td><code>ami<\/code>, <code>instance_type<\/code>, <code>availability_zone<\/code><\/td><\/tr><tr><td><code>aws_ebs_volume<\/code><\/td><td>Creates a standalone block storage volume<\/td><td><code>availability_zone<\/code>, <code>size<\/code> (GiB), <code>type<\/code>, <code>encrypted<\/code><\/td><\/tr><tr><td><code>aws_volume_attachment<\/code><\/td><td>Attaches the volume to the instance<\/td><td><code>device_name<\/code>, <code>volume_id<\/code>, <code>instance_id<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> An EBS volume can only be attached to an instance in the <strong>same Availability Zone<\/strong>. That is why both resources in the example use <code>ap-south-1a<\/code>. If the two values differ, the attachment fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Terraform CLI installed (<code>terraform -version<\/code>).<\/li>\n\n\n<li>AWS credentials available to Terraform, for example through <code>aws configure<\/code>, environment variables or an IAM role. The identity needs permissions for EC2 instances, volumes, volume attachments and <code>ec2:DescribeImages<\/code>.<\/li>\n\n\n<li>A default VPC in the target region, or a subnet ID you can pass to the instance.<\/li>\n\n\n<li>An existing EC2 key pair or AWS Systems Manager Session Manager access if you plan to log in and mount the volume.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected and complete configuration<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This version can be run as is. It adds the <code>terraform<\/code> and <code>provider<\/code> blocks, looks up the latest Amazon Linux 2023 AMI instead of hardcoding an ID, takes the volume&#039;s Availability Zone from the instance so the two always match, and sets the volume type to gp3 with encryption turned on.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">terraform {\n  required_providers {\n    aws = {\n      source  = <span class=\"hljs-string\">\"hashicorp\/aws\"<\/span>\n      version = <span class=\"hljs-string\">\"&gt;= 5.0\"<\/span>\n    }\n  }\n}\n\nvariable <span class=\"hljs-string\">\"region\"<\/span> {\n  type    = string\n  <span class=\"hljs-keyword\">default<\/span> = <span class=\"hljs-string\">\"ap-south-1\"<\/span>\n}\n\nvariable <span class=\"hljs-string\">\"availability_zone\"<\/span> {\n  type    = string\n  <span class=\"hljs-keyword\">default<\/span> = <span class=\"hljs-string\">\"ap-south-1a\"<\/span>\n}\n\nprovider <span class=\"hljs-string\">\"aws\"<\/span> {\n  region = <span class=\"hljs-keyword\">var<\/span>.region\n}\n\n<span class=\"hljs-comment\"># Latest Amazon Linux 2023 AMI for the selected region<\/span>\ndata <span class=\"hljs-string\">\"aws_ami\"<\/span> <span class=\"hljs-string\">\"al2023\"<\/span> {\n  most_recent = <span class=\"hljs-keyword\">true<\/span>\n  owners      = &#91;<span class=\"hljs-string\">\"amazon\"<\/span>]\n\n  filter {\n    name   = <span class=\"hljs-string\">\"name\"<\/span>\n    values = &#91;<span class=\"hljs-string\">\"al2023-ami-2023.*-x86_64\"<\/span>]\n  }\n}\n\nresource <span class=\"hljs-string\">\"aws_instance\"<\/span> <span class=\"hljs-string\">\"web\"<\/span> {\n  ami               = data.aws_ami.al2023.id\n  instance_type     = <span class=\"hljs-string\">\"t3.micro\"<\/span>\n  availability_zone = <span class=\"hljs-keyword\">var<\/span>.availability_zone\n  <span class=\"hljs-comment\"># key_name        = \"my-key-pair\"   # uncomment to allow SSH<\/span>\n\n  tags = {\n    Name = <span class=\"hljs-string\">\"HelloWorld\"<\/span>\n  }\n}\n\nresource <span class=\"hljs-string\">\"aws_ebs_volume\"<\/span> <span class=\"hljs-string\">\"data\"<\/span> {\n  availability_zone = aws_instance.web.availability_zone\n  size              = <span class=\"hljs-number\">40<\/span>\n  type              = <span class=\"hljs-string\">\"gp3\"<\/span>\n  encrypted         = <span class=\"hljs-keyword\">true<\/span>\n\n  tags = {\n    Name = <span class=\"hljs-string\">\"HelloWorld-data\"<\/span>\n  }\n}\n\nresource <span class=\"hljs-string\">\"aws_volume_attachment\"<\/span> <span class=\"hljs-string\">\"data_att\"<\/span> {\n  device_name = <span class=\"hljs-string\">\"\/dev\/sdf\"<\/span>\n  volume_id   = aws_ebs_volume.data.id\n  instance_id = aws_instance.web.id\n}\n\noutput <span class=\"hljs-string\">\"instance_id\"<\/span> {\n  value = aws_instance.web.id\n}\n\noutput <span class=\"hljs-string\">\"volume_id\"<\/span> {\n  value = aws_ebs_volume.data.id\n}\n\noutput <span class=\"hljs-string\">\"public_ip\"<\/span> {\n  value = aws_instance.web.public_ip\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>data &quot;aws_ami&quot;<\/code> finds the newest matching Amazon-owned image at plan time, so the configuration works in any region.<\/li>\n\n\n<li><code>availability_zone = aws_instance.web.availability_zone<\/code> removes the duplicated AZ string and creates a dependency, so the volume is always created in the instance&#039;s AZ.<\/li>\n\n\n<li><code>type = &quot;gp3&quot;<\/code> 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 <code>iops<\/code> and <code>throughput<\/code>.<\/li>\n\n\n<li><code>encrypted = true<\/code> encrypts the volume with the AWS managed EBS key unless you set <code>kms_key_id<\/code>.<\/li>\n\n\n<li>The outputs print the IDs and public IP after <code>apply<\/code>. You need them for the mounting steps.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Deploy and verify<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Save the configuration as <code>main.tf<\/code> in an empty directory.<\/li>\n\n\n<li>Run <code>terraform init<\/code> to download the AWS provider.<\/li>\n\n\n<li>Run <code>terraform fmt<\/code> and <code>terraform validate<\/code> to catch syntax errors.<\/li>\n\n\n<li>Run <code>terraform plan<\/code> and check that it shows 3 resources to add.<\/li>\n\n\n<li>Run <code>terraform apply<\/code> and type <code>yes<\/code> when prompted.<\/li>\n\n\n<li>Check the attachment with the AWS CLI.<\/li>\n<\/ol>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">terraform init\nterraform fmt\nterraform validate\nterraform plan\nterraform apply\n\n<span class=\"hljs-comment\"># Expected at the end of apply:<\/span>\n<span class=\"hljs-comment\"># Apply complete! Resources: 3 added, 0 changed, 0 destroyed.<\/span>\n\naws ec2 describe-volumes \\\n  --volume-ids $(terraform output -raw volume_id) \\\n  --query <span class=\"hljs-string\">'Volumes&#91;0].Attachments&#91;0].&#91;InstanceId,Device,State]'<\/span> \\\n  --output text\n<span class=\"hljs-comment\"># i-0abc123...   \/dev\/sdf   attached<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Format and mount the volume inside the instance<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>\/dev\/sdf<\/code> appears in Linux as an NVMe device, usually <code>\/dev\/nvme1n1<\/code>. Always check with <code>lsblk<\/code> before formatting.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># Identify the new 40 GiB disk (no MOUNTPOINT, no partitions)<\/span>\nlsblk\n\n<span class=\"hljs-comment\"># Confirm it has no filesystem yet; output 'data' means empty<\/span>\nsudo file -s \/dev\/nvme1n1\n\n<span class=\"hljs-comment\"># Create a filesystem (ONLY on a new, empty volume)<\/span>\nsudo mkfs -t xfs \/dev\/nvme1n1\n\n<span class=\"hljs-comment\"># Mount it<\/span>\nsudo mkdir -p \/data\nsudo mount \/dev\/nvme1n1 \/data\ndf -h \/data\n\n<span class=\"hljs-comment\"># Make the mount persistent across reboots using the UUID<\/span>\nUUID=$(sudo blkid -s UUID -o value \/dev\/nvme1n1)\n<span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"UUID=$UUID  \/data  xfs  defaults,nofail  0  2\"<\/span> | sudo tee -a \/etc\/fstab\nsudo mount -a<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Running <code>mkfs<\/code> on a volume that already holds data erases it. Use the UUID in <code>\/etc\/fstab<\/code> rather than the device name, because NVMe device names can change between boots. The <code>nofail<\/code> option lets the instance boot even if the volume is detached.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>InvalidAMIID.NotFound<\/code> or <code>InvalidAMIID.Malformed<\/code><\/td><td>The hardcoded AMI ID does not exist in the current region or has been deregistered<\/td><td>Use the <code>aws_ami<\/code> data source shown above, or look up a current AMI ID for your region<\/td><\/tr><tr><td><code>InvalidVolume.ZoneMismatch<\/code><\/td><td>The volume and instance are in different Availability Zones<\/td><td>Set the volume&#039;s <code>availability_zone<\/code> from <code>aws_instance.web.availability_zone<\/code><\/td><\/tr><tr><td><code>Unsupported<\/code> instance type in the requested Availability Zone<\/td><td>The instance type is not offered in that AZ<\/td><td>Choose another AZ or instance type<\/td><\/tr><tr><td>Volume detach hangs or times out during <code>terraform destroy<\/code><\/td><td>The volume is still mounted and in use inside the OS<\/td><td>Unmount it first, or set <code>stop_instance_before_detaching = true<\/code> on <code>aws_volume_attachment<\/code><\/td><\/tr><tr><td><code>InvalidParameterValue<\/code> for the device name<\/td><td>The device name is already in use or not valid for the instance<\/td><td>Use an unused name in the range <code>\/dev\/sdf<\/code> to <code>\/dev\/sdp<\/code><\/td><\/tr><tr><td><code>UnauthorizedOperation<\/code><\/td><td>The IAM identity lacks EC2 permissions<\/td><td>Grant the required EC2 actions or use a role that has them<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Separate volume resource or inline ebs_block_device<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Terraform can also define extra disks inline with an <code>ebs_block_device<\/code> block inside <code>aws_instance<\/code>. The separate-resource pattern used in this example is usually the better choice for data disks.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Approach<\/th><th>Lifecycle<\/th><th>Typical use<\/th><\/tr><\/thead><tbody><tr><td><code>aws_ebs_volume<\/code> + <code>aws_volume_attachment<\/code><\/td><td>Volume exists independently and can be detached and reattached to a replacement instance<\/td><td>Persistent data disks<\/td><\/tr><tr><td><code>ebs_block_device<\/code> inside <code>aws_instance<\/code><\/td><td>Created and normally destroyed with the instance; changes often force instance replacement<\/td><td>Scratch or disposable disks<\/td><\/tr><tr><td><code>root_block_device<\/code> inside <code>aws_instance<\/code><\/td><td>Controls the boot volume size, type and encryption<\/td><td>Resizing or encrypting the root disk<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Do not manage the same instance&#039;s extra volumes with both <code>ebs_block_device<\/code> and <code>aws_volume_attachment<\/code>. The two methods conflict and cause constant drift in <code>terraform plan<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Always set <code>encrypted = true<\/code> or turn on EBS encryption by default for the account and region.<\/li>\n\n\n<li>Prefer <code>gp3<\/code> over <code>gp2<\/code>: performance does not depend on volume size, and it typically costs less per GiB.<\/li>\n\n\n<li>Add <code>lifecycle { prevent_destroy = true }<\/code> to data volumes that must survive a careless <code>terraform destroy<\/code>.<\/li>\n\n\n<li>Back up data volumes with EBS snapshots or AWS Backup. Terraform state does not protect your data.<\/li>\n\n\n<li>Use variables for region, AZ, size and instance type, and use <code>count<\/code> or <code>for_each<\/code> to create several volumes. See <a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-do-looping-iterations-in-terraform\/\">Terraform Loops and Iteration<\/a>.<\/li>\n\n\n<li>Run <code>terraform fmt<\/code>, <code>validate<\/code> and security scanners automatically with <a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-configure-pre-commit-for-terraform-complete-devops-guide-with-15-practical-use-cases-commands-security-checks-and-best-practices\/\">pre-commit for Terraform<\/a>.<\/li>\n\n\n<li>Run <code>terraform destroy<\/code> after lab exercises so that instances and volumes do not keep running up charges.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Why does my EBS volume show as \/dev\/nvme1n1 instead of \/dev\/sdf?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">On Nitro-based instance types, EBS volumes are exposed as NVMe devices, whatever device name you set in Terraform. Use <code>lsblk<\/code> to find the disk, and use the filesystem UUID in <code>\/etc\/fstab<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I attach an EBS volume to an instance in a different Availability Zone?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does terraform destroy delete the EBS volume?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Running <code>terraform destroy<\/code> on this configuration detaches and deletes the volume along with the instance. Add <code>prevent_destroy<\/code> in a <code>lifecycle<\/code> block, or take a snapshot first, if the data must be kept.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I increase the size of the EBS volume with Terraform?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Change <code>size<\/code> to a larger value and run <code>terraform apply<\/code>. EBS volumes can be resized in place, but you must then grow the filesystem inside the OS, for example with <code>sudo xfs_growfs \/data<\/code> for XFS. EBS volumes cannot be shrunk.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does Terraform format and mount the volume automatically?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/infrastructure-as-code\/terraform\/\">More Terraform tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-do-looping-iterations-in-terraform\/\">Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/how-to-configure-pre-commit-for-terraform-complete-devops-guide-with-15-practical-use-cases-commands-security-checks-and-best-practices\/\">How to Configure pre-commit for Terraform: Complete DevOps Guide with 15 Practical Use Cases, Commands, Security Checks, and Best Practices<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/cloud-computing\/aws\/\">More AWS tutorials<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[5129,5633],"tags":[3400,3354],"class_list":["post-31041","post","type-post","status-publish","format-standard","hentry","category-terraform","category-aws","tag-amazon-ebs","tag-amazon-ec2"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31041","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=31041"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31041\/revisions"}],"predecessor-version":[{"id":80610,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31041\/revisions\/80610"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=31041"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=31041"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=31041"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}