20
3

More than 1 year has passed since last update.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

【小ネタ】SecurityGroupにリソースが紐づいてるか確認スクリプト書いてみた

Posted at

はじめに

不要セキュリティグループを一掃しようと思いスクリプトを書いてみました。
本スクリプトでVPCリソースと紐づいているセキュリティグループをあらかた判別出来ます。

実行例

スクリプト

get_security_group_attachment.sh
#!/bin/bash

# 引数からプロファイル名を取得
profile="$1"

# 引数が渡されていない場合はデフォルトのプロファイルを使用
if [ -z "$profile" ]; then
  profile="default"
fi

# セキュリティグループのリソースIDのリストを作成
security_group_ids=$(aws ec2 describe-security-groups --query 'SecurityGroups[].GroupId' --output text --profile "$profile")

# CSVファイルにヘッダーを書き込む
echo "セキュリティグループ,Attachment ID" > result.csv

# スクリプトの実行
for security_group_id in $security_group_ids; do
  echo "セキュリティグループ: $security_group_id"
  attachment_ids=$(aws ec2 describe-network-interfaces \
    --filters Name=group-id,Values=$security_group_id \
    --query 'NetworkInterfaces[].Attachment.AttachmentId | join(`,`, @)' \
    --output text \
    --profile "$profile")

  # セキュリティグループとAttachment IDをカンマ区切りでCSV形式でファイルに書き込む
  if [ -z "$attachment_ids" ]; then
    attachment_ids="null"
  fi
  echo "$security_group_id,$attachment_ids" >> result.csv

done

引数にprofileを指定して実行

./get_security_group_attachment.sh sample-profile

結果例

※Attachment IDがnullなら何にも紐づいていない

セキュリティグループ,Attachment ID
sg-xxxxxxxxxxxxx,ela-attach-xxxxxxxxxxxxx,ela-attach-xxxxxxxxxxxxx,ela-attach-xxxxxxxxxxxxx
sg-xxxxxxxxxxxxx,ela-attach-xxxxxxxxxxxxx,ela-attach-xxxxxxxxxxxxx,ela-attach-xxxxxxxxxxxxx
sg-xxxxxxxxxxxxx,null
sg-xxxxxxxxxxxxx,null
sg-xxxxxxxxxxxxx,eni-attach-xxxxxxxxxxxxx

おわり

さくっと調べるには丁度いいかなと思います。1点注意が必要で、サポートにも確認しましたがAWSの仕様上、CodeBuildなどでVPC接続時に指定されていたSGはNICと紐づかないためか判別出来ないっぽいので全てを拾えるわけではないので、飽くまでも掃除のお助けツールのように使うことを想定しています。

20
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
3