Skip to main content

Lab 010: Attach Elastic IP 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.There is an instance named xfusion-ec2 and an elastic-ip named xfusion-ec2-eip in us-east-1 region. Attach the xfusion-ec2-eip elastic-ip to the xfusion-ec2 instance.


Note

The requirement statement is preserved verbatim. This document uses one CLI workflow to map the named Elastic IP to the target EC2 instance.

Prerequisites

  • AWS CLI is installed and authenticated.
  • The instance xfusion-ec2 and Elastic IP tag xfusion-ec2-eip exist in us-east-1.
  • Your identity can describe instances/addresses and associate Elastic IPs.

Steps

INSTANCE_NAME="xfusion-ec2"
ELASTIC_IP_NAME="xfusion-ec2-eip"
REGION="us-east-1"

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

ALLOCATION_ID=$(aws ec2 describe-addresses \
--region "$REGION" \
--filters "Name=tag:Name,Values=$ELASTIC_IP_NAME" \
--query "Addresses[*].AllocationId" \
--output text)

if [ -z "$ALLOCATION_ID" ]; then
echo "Elastic IP with name $ELASTIC_IP_NAME not found."
exit 1
fi

aws ec2 associate-address \
--region "$REGION" \
--instance-id "$INSTANCE_ID" \
--allocation-id "$ALLOCATION_ID"

echo "Successfully associated Elastic IP $ELASTIC_IP_NAME with instance $INSTANCE_NAME."

Verification

  • Confirm the Elastic IP is associated with xfusion-ec2.
  • Confirm the address record has a non-empty AssociationId and expected InstanceId.
aws ec2 describe-addresses \
--region us-east-1 \
--filters "Name=tag:Name,Values=xfusion-ec2-eip" \
--query "Addresses[0].{AllocationId:AllocationId,PublicIp:PublicIp,AssociationId:AssociationId,InstanceId:InstanceId}" \
--output table

Resources