Skip to content

Instantly share code, notes, and snippets.

@dmccuk
Last active January 30, 2025 09:37
Show Gist options
  • Save dmccuk/12b73e4165aeccb72ad9952a0a5f9ee6 to your computer and use it in GitHub Desktop.
Save dmccuk/12b73e4165aeccb72ad9952a0a5f9ee6 to your computer and use it in GitHub Desktop.
  1. Retrieve Security Groups via AWS CLI Get the Security Groups Attached to an Instance Run:
aws ec2 describe-instances --instance-id $(curl -s http://169.254.169.254/latest/meta-data/instance-id) --query "Reservations[].Instances[].SecurityGroups" --output json

This will return something like:

[
  {
    "GroupName": "MySecurityGroup",
    "GroupId": "sg-0a1b2c3d4e5f67890"
  }
]
2. Get Open Ports in the Security Group

Once you have the Security Group ID, check the allowed ports:

sh Copy Edit aws ec2 describe-security-groups --group-ids sg-0a1b2c3d4e5f67890 --query "SecurityGroups[].IpPermissions" Example output:

json Copy Edit [ { "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "IpRanges": [{"CidrIp": "0.0.0.0/0"}] }, { "IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "IpRanges": [{"CidrIp": "0.0.0.0/0"}] } ] This means ports 22 (SSH) and 80 (HTTP) are open to the internet.

  1. Automate Everything in One Command sh Copy Edit aws ec2 describe-security-groups --group-ids $(aws ec2 describe-instances --instance-id $(curl -s http://169.254.169.254/latest/meta-data/instance-id) --query "Reservations[].Instances[].SecurityGroups[].GroupId" --output text) --query "SecurityGroups[].IpPermissions" This retrieves the instance’s Security Group(s) and lists open ports in one go.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment