Skip to main content

Lab 012: Attach Volume to EC2 Instance



Requirements

The Nautilus DevOps team has been creating a couple of services on AWS cloud. They have been breaking down the migration into smaller tasks, allowing for better control, risk mitigation, and optimization of resources throughout the migration process. Recently they came up with requirements mentioned below.

  1. An instance named datacenter-ec2 and a volume named datacenter-volume already exists in us-east-1 region.
  2. Attach the datacenter-volume volume to the datacenter-ec2 instance.
  3. Make sure to set the device name to /dev/sdb while attaching the volume.

Note

This page keeps the original requirement text unchanged and documents one direct CLI flow to attach and validate the EBS volume.

Prerequisites

  • AWS CLI is installed and authenticated.
  • The instance datacenter-ec2 and volume tag datacenter-volume exist in us-east-1.
  • The volume is in an attachable state and compatible AZ with the instance.

Steps

INSTANCE_NAME="datacenter-ec2"
VOLUME_NAME="datacenter-volume"
REGION="us-east-1"
DEVICE_NAME="/dev/sdb"

INSTANCE_ID=$(aws ec2 describe-instances \
--region "$REGION" \
--filters "Name=tag:Name,Values=$INSTANCE_NAME" \
--query "Reservations[*].Instances[*].InstanceId" \
--output text)

if [ -z "$INSTANCE_ID" ]; then
echo "Instance with name $INSTANCE_NAME not found."
exit 1
fi

VOLUME_ID=$(aws ec2 describe-volumes \
--region "$REGION" \
--filters "Name=tag:Name,Values=$VOLUME_NAME" \
--query "Volumes[*].VolumeId" \
--output text)

if [ -z "$VOLUME_ID" ]; then
echo "Volume with name $VOLUME_NAME not found."
exit 1
fi

aws ec2 attach-volume \
--region "$REGION" \
--volume-id "$VOLUME_ID" \
--instance-id "$INSTANCE_ID" \
--device "$DEVICE_NAME"

aws ec2 wait volume-in-use --region "$REGION" --volume-ids "$VOLUME_ID"

echo "Volume $VOLUME_NAME is now attached to instance $INSTANCE_NAME as $DEVICE_NAME."

Verification

  • Confirm the volume attachment status is attached.
  • Confirm device name is /dev/sdb on the target instance.
aws ec2 describe-volumes \
--region us-east-1 \
--volume-ids "$VOLUME_ID" \
--query "Volumes[0].Attachments[0].{InstanceId:InstanceId,Device:Device,State:State}" \
--output table

Resources