简体   繁体   English

使用 bash 和 AWS CLI 从所有区域取消关联和释放所有弹性 IP 地址的脚本

[英]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.我正在学习如何使用 AWS 基础设施和 CLI 工具。 I had many EC2 instances with public IP that I have terminated using another CLI script authored by Russell Jurney Source .我有许多带有公共 IP 的 EC2 实例,我已经使用 Russell Jurney Source编写的另一个 CLI 脚本终止了这些实例。

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.我试图修改它以释放所有公共 IP,但由于我对脚本和 json 非常陌生,我无法理解这个。 How to address all Public IPs in this script and do correct loops so each IP is released?如何解决此脚本中的所有公共 IP 并执行正确的循环以便释放每个 IP?

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取消关联所有区域中的所有公共 IP 并
  2. Release all of them back to AWS pool.将它们全部释放回 AWS 池。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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