edit-icon download-icon

Query IDs of security groups not associated with any instances in all regions

Last Updated: Dec 20, 2017

You can run the following script in Alibaba Cloud CLI to query security groups not associated with any instances in all regions and perform operations (such as DELETE) on the security groups. You can download or edit the script.

Click to download the script: getUnUsedSecurityGroupId.zip.

The script is as follows:

  1. #!/bin/bash
  2. for RegionId in `aliyuncli ecs DescribeRegions --filter Regions.Region[*].RegionId --output json | sed '1d' | sed '$d' | sed 's/,//g' | sed 's/"//g'| sed 's/ //g'`
  3. do
  4. cat /dev/null >/tmp/UnUsedSecurityGroupIds.txt
  5. pageNum=1
  6. tcount=`aliyuncli ecs DescribeSecurityGroups --RegionId $RegionId --output json --filter TotalCount`
  7. while ((tcount>0))
  8. do
  9. aliyuncli ecs DescribeSecurityGroups --RegionId $RegionId --filter SecurityGroups.SecurityGroup[*].SecurityGroupId --PageSize 100 --PageNumber $pageNum --output json | sed '1d' | sed '$d' | sed 's/,//g' | sed 's/"//g'| sed 's/ //g'>>/tmp/UnUsedSecurityGroupIds.txt
  10. let pageNum++
  11. let tcount-=100
  12. done
  13. cat /tmp/UnUsedSecurityGroupIds.txt | while read line
  14. do
  15. usedVMCount=`aliyuncli ecs DescribeInstances --RegionId $RegionId --SecurityGroupId $line --output json --filter TotalCount`
  16. if [[ $usedVMCount -eq 0 ]];then
  17. echo $RegionId " " $line
  18. fi
  19. done
  20. done

After editing or downloading the script and granting the permission (by running the chmod + x command), you can run the script in the following format to export IDs of security groups (in pairs) not associated with any instances in all regions by region and security group.

Format:

  1. ./getUnUsedSGInfo.sh

Sample output:

  1. [root@AliyunTest]# ./getUnUsedSGInfo.sh
  2. cn-qingdao sg-227f61lts
  3. cn-shenzhen sg-22esa0f7s
Thank you! We've received your feedback.