-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1-attach-elastic-ip-ec2.sh
More file actions
40 lines (34 loc) · 1.19 KB
/
1-attach-elastic-ip-ec2.sh
File metadata and controls
40 lines (34 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/bin/bash
# Configuration
REGION=$1
INSTANCE_NAME=$2
EIP_NAME=$3
if [ -z "$REGION" ] || [ -z "$INSTANCE_NAME" ] || [ -z "$EIP_NAME" ]; then
echo "Usage: $0 <REGION> <INSTANCE_NAME> <EIP_NAME>"
exit 1
fi
echo "Retrieving IDs for $INSTANCE_NAME and $EIP_NAME..."
# 1. Get Instance ID
INSTANCE_ID=$(aws ec2 describe-instances \
--region $REGION \
--filters "Name=tag:Name,Values=$INSTANCE_NAME" "Name=instance-state-name,Values=running,pending" \
--query "Reservations[*].Instances[*].InstanceId" \
--output text)
# 2. Get Allocation ID of the Elastic IP
ALLOCATION_ID=$(aws ec2 describe-addresses \
--region $REGION \
--filters "Name=tag:Name,Values=$EIP_NAME" \
--query "Addresses[*].AllocationId" \
--output text)
# 3. Associate the Elastic IP
if [ -n "$INSTANCE_ID" ] && [ -n "$ALLOCATION_ID" ]; then
echo "Associating EIP ($ALLOCATION_ID) with Instance ($INSTANCE_ID)..."
aws ec2 associate-address \
--region $REGION \
--instance-id $INSTANCE_ID \
--allocation-id $ALLOCATION_ID
echo "Success: Elastic IP associated."
else
echo "Error: Could not find Instance ID or Allocation ID. Please check your resource names."
exit 1
fi