简体   繁体   中英

Script to disassociate and release all Elastic IP addresses from all regions using bash and AWS CLI

I'm learning how to use AWS infrastructure and CLI tools. I had many EC2 instances with public IP that I have terminated using another CLI script authored by Russell Jurney Source .

I tried to modify this to release all Public IPs, but as I'm very new to scripting and json I can't get my head around this one. How to address all Public IPs in this script and do correct loops so each IP is released?

for region in `aws ec2 describe-regions | jq -r .Regions[].RegionName`
do
  echo "Releasing Elastic IPs in region $region..."
  for address in 'aws ecs describe-regions | jq -r .Regions[].RegionName[]'
  do
    aws ec2 disassociate-address --region $region | \
      jq -r .Reservations[].Instances[].PrivateIpAddress| \
        xargs -L 1 -I {} aws ec2 modify-instance-attribute \
          --region $region \
          --allocation-id {}\
          --public-ip {}
    aws ec2 release-address --region $region | \
      jq -r .Reservations[].Instances[].PrivateIpAddress | \
        xargs -L 1 -I {} aws ec2 terminate-instances \
          --region $region \
          --allocation-id {}
          --instance-id {}
  done
done

So, your objective is to:

  1. Disassociate all the Public IPs in all the regions and
  2. Release all of them back to AWS pool.

Try the below script, I could not try this since I do not have an environment handy however, this should work. In case you face any error messages, please update (With the error message mentioned clearly)

for region in $(aws ec2 describe-regions --profile default --output text | cut -f4)
do
for address in $(aws ec2 describe-addresses --region $region --profile default --query 'Addresses[].AssociationId' --output text)
do
echo -e "Disassociating $address from $region now..."
aws ec2 disassociate-address --association-id $address --region $region --profile default
for pubip in $(aws ec2 describe-addresses --region $region --profile default --query 'Addresses[].PublicIp' --output text)
do
echo -e "Now Releasing the PublicIP $pubip from region $region"
aws ec2 release-address --public-ip $pubip --region $region --profile default
done
done
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM