Extending size of a EBS mounted on an active EC2 Instance

The first part of this blog post covers how a EBS volume automatically allcocated while creating a EC2 instnace can be imported to the Terraform state. After that, we define the new configuration (i.e.: size) of the EBS and provision the configuration with Terraform. Then we go to the machine and actually resize the XFS volume mounted on the OS without any downtime.

Notice that it's not easily possible to shrink the size of an XFS volume once resized. So choose a size carefully based on your project budget.

First of all, go to the AWS console, find the ID of the EBS volume. (e.g.: vol-0abeefe03e7dab6d6). Go to your Terraform project and run

terraform import aws_ebs_volume.EBS-1 vol-0abeefe03e7dab6d6

Then define a Terraform resource with that name for the EBS, below is an example one, where 100 is the new size of the volume (which will be updated accordingly after we run terraform apply)

resource "aws_ebs_volume" "EBS-1" {
  availability_zone = "us-east-2a"
  size = 100
  type = "gp2"

  # tags: {
    name = "EBS-1"
  }
}

Then provision the new configuration:

terraform apply -target=aws_ebs_volume.EBS-1

After the provision, connect to your instance and ensure your current size and filesystem of the / mountpoint.

$ df -hT /
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/xvda1     xfs        10G  4.7G  5.4G  47% /

Check the size of the logical volume:

$ lsblk
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0  100G  0 disk
└─xvda1 202:1    0   10G  0 part /

We can see that the new size has been provisioned to the volume but not the partition. Next we grow the size of the partition:

$ growpart /dev/xvda 1
CHANGED: partition=1 start=2048 old: size=20969439 end=20971487 new: size=209713119 end=209715167

Where 1 is the partition number of /dev/xvda1. Verify the change with lsblk:

$ lsblk
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0  100G  0 disk
└─xvda1 202:1    0  100G  0 part /

Finally, we can grow the size of the filesystem on the partition we just resized.

xfs_growfs /dev/xvda1

Verify with df -hT /:

$ df -hT /
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/xvda1     xfs       100G  4.7G 95.3G   4% /