如何获取未使用的Elastic IP及编写Shell脚本关联至新实例?
How to Query Unused AWS Elastic IPs & Automate Association with New Instances
Hey there! Let's break down your request into two actionable parts: first, a direct AWS CLI command to find unused Elastic IPs, and second, a shell script that automates the full workflow—finding idle EIPs, spinning up a new instance, and linking them together.
1. Query Unused Elastic IPs with AWS CLI
To get a list of EIPs that aren't associated with any EC2 instance, we can use aws ec2 describe-addresses with a filter targeting empty AssociationId values (this is how AWS marks unused EIPs).
Here's the command:
aws ec2 describe-addresses --filters "Name=association-id,Values=''" --query 'Addresses[*].[PublicIp,AllocationId]' --output table
What each part does:
--filters "Name=association-id,Values=''": Filters results to only include EIPs with no association (i.e., unused).--query 'Addresses[*].[PublicIp,AllocationId]': Narrows down the output to just the public IP and allocation ID (the two values you'll need for association later).--output table: Makes the results human-readable. Swap this forjsonortextif you need machine-parsable output.
2. Shell Script to Automate EIP Association with a New Instance
This script will:
- Check for any unused EIPs
- If none exist, create a new EIP
- Launch a new EC2 instance (you'll need to tweak the AMI ID and instance type for your region/needs)
- Wait for the instance to be running
- Associate the EIP (existing or new) with the instance
#!/bin/bash # Query the first unused Elastic IP (returns AllocationId and PublicIp) FREE_EIP=$(aws ec2 describe-addresses --filters "Name=association-id,Values=''" --query 'Addresses[0].[AllocationId,PublicIp]' --output text) # Handle case where no unused EIPs exist if [ -z "$FREE_EIP" ]; then echo "No unused Elastic IPs found. Creating a new one..." NEW_EIP=$(aws ec2 allocate-address --query '[AllocationId,PublicIp]' --output text) ALLOCATION_ID=$(echo "$NEW_EIP" | awk '{print $1}') PUBLIC_IP=$(echo "$NEW_EIP" | awk '{print $2}') else ALLOCATION_ID=$(echo "$FREE_EIP" | awk '{print $1}') PUBLIC_IP=$(echo "$FREE_EIP" | awk '{print $2}') echo "Found unused Elastic IP: $PUBLIC_IP (Allocation ID: $ALLOCATION_ID)" fi # Launch a new EC2 instance (UPDATE THESE PARAMETERS FOR YOUR USE CASE!) # Replace the AMI ID with one valid for your AWS region (e.g., Amazon Linux 2, Ubuntu, etc.) INSTANCE_ID=$(aws ec2 run-instances \ --image-id ami-0c55b159cbfafe1f0 \ # us-east-1 Amazon Linux 2 AMI—swap for your region! --instance-type t2.micro \ --count 1 \ --query 'Instances[0].InstanceId' \ --output text) echo "Created EC2 instance: $INSTANCE_ID" # Wait for the instance to enter the running state (critical for successful association) echo "Waiting for instance to start up..." aws ec2 wait instance-running --instance-ids $INSTANCE_ID # Associate the Elastic IP with the new instance aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOCATION_ID echo "Successfully linked Elastic IP $PUBLIC_IP to instance $INSTANCE_ID"
Key Notes & Customizations:
- AWS CLI Setup: Ensure your CLI is configured with valid credentials and the correct region (run
aws configureto set this up). - AMI ID: The example uses a us-east-1 Amazon Linux 2 AMI. Find the right AMI for your region via the AWS Console or
aws ec2 describe-images. - Instance Configuration: Add flags like
--security-group-ids sg-xxxxxxor--subnet-id subnet-xxxxxxto customize the instance's network settings. - IAM Permissions: Make sure your IAM user/role has these permissions:
ec2:DescribeAddresses,ec2:AllocateAddress,ec2:RunInstances,ec2:AssociateAddress, andec2:WaitInstanceRunning. - Error Handling: For production use, add checks (e.g.,
if [ $? -ne 0 ]) to catch failures at each step and exit gracefully.
内容的提问来源于stack exchange,提问作者Tanjila
相关产品推荐
相关产品推荐

