Use DescribeSecurityGroups with an Amazon SDK or CLI - Amazon Elastic Compute Cloud
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use DescribeSecurityGroups with an Amazon SDK or CLI

The following code examples show how to use DescribeSecurityGroups.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <summary> /// Retrieve information for an Amazon EC2 security group. /// </summary> /// <param name="groupId">The Id of the Amazon EC2 security group.</param> /// <returns>A list of security group information.</returns> public async Task<List<SecurityGroup>> DescribeSecurityGroups(string groupId) { var request = new DescribeSecurityGroupsRequest(); var groupIds = new List<string> { groupId }; request.GroupIds = groupIds; var response = await _amazonEC2.DescribeSecurityGroupsAsync(request); return response.SecurityGroups; } /// <summary> /// Display the information returned by the call to /// DescribeSecurityGroupsAsync. /// </summary> /// <param name="securityGroup">A list of security group information.</param> public void DisplaySecurityGroupInfoAsync(SecurityGroup securityGroup) { Console.WriteLine($"{securityGroup.GroupName}"); Console.WriteLine("Ingress permissions:"); securityGroup.IpPermissions.ForEach(permission => { Console.WriteLine($"\tFromPort: {permission.FromPort}"); Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}"); Console.Write($"\tIpv4Ranges: "); permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); }); Console.WriteLine($"\n\tIpv6Ranges:"); permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); }); Console.Write($"\n\tPrefixListIds: "); permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} ")); Console.WriteLine($"\n\tTo Port: {permission.ToPort}"); }); Console.WriteLine("Egress permissions:"); securityGroup.IpPermissionsEgress.ForEach(permission => { Console.WriteLine($"\tFromPort: {permission.FromPort}"); Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}"); Console.Write($"\tIpv4Ranges: "); permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); }); Console.WriteLine($"\n\tIpv6Ranges:"); permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); }); Console.Write($"\n\tPrefixListIds: "); permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} ")); Console.WriteLine($"\n\tTo Port: {permission.ToPort}"); }); }
Bash
Amazon CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

############################################################################### # function ec2_describe_security_groups # # This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups. # # Parameters: # -g security_group_id - The ID of the security group to describe (optional). # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_describe_security_groups() { local security_group_id response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_describe_security_groups" echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups." echo " -g security_group_id - The ID of the security group to describe (optional)." echo "" } # Retrieve the calling parameters. while getopts "g:h" option; do case "${option}" in g) security_group_id="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 local query="SecurityGroups[*].[GroupName, GroupId, VpcId, IpPermissions[*].[IpProtocol, FromPort, ToPort, IpRanges[*].CidrIp]]" if [[ -n "$security_group_id" ]]; then response=$(aws ec2 describe-security-groups --group-ids "$security_group_id" --query "${query}" --output text) else response=$(aws ec2 describe-security-groups --query "${query}" --output text) fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports describe-security-groups operation failed.$response" return 1 fi echo "$response" return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DescribeSecurityGroupsRequest request; if (!groupID.empty()) { request.AddGroupIds(groupID); } Aws::String nextToken; do { if (!nextToken.empty()) { request.SetNextToken(nextToken); } auto outcome = ec2Client.DescribeSecurityGroups(request); if (outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "Name" << std::setw(30) << "GroupId" << std::setw(30) << "VpcId" << std::setw(64) << "Description" << std::endl; const std::vector<Aws::EC2::Model::SecurityGroup> &securityGroups = outcome.GetResult().GetSecurityGroups(); for (const auto &securityGroup: securityGroups) { std::cout << std::left << std::setw(32) << securityGroup.GetGroupName() << std::setw(30) << securityGroup.GetGroupId() << std::setw(30) << securityGroup.GetVpcId() << std::setw(64) << securityGroup.GetDescription() << std::endl; } } else { std::cerr << "Failed to describe security groups:" << outcome.GetError().GetMessage() << std::endl; return false; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty());
CLI
Amazon CLI

Example 1: To describe a security group

The following describe-security-groups example describes the specified security group.

aws ec2 describe-security-groups \ --group-ids sg-903004f8

Output:

{ "SecurityGroups": [ { "IpPermissionsEgress": [ { "IpProtocol": "-1", "IpRanges": [ { "CidrIp": "0.0.0.0/0" } ], "UserIdGroupPairs": [], "PrefixListIds": [] } ], "Description": "My security group", "Tags": [ { "Value": "SG1", "Key": "Name" } ], "IpPermissions": [ { "IpProtocol": "-1", "IpRanges": [], "UserIdGroupPairs": [ { "UserId": "123456789012", "GroupId": "sg-903004f8" } ], "PrefixListIds": [] }, { "PrefixListIds": [], "FromPort": 22, "IpRanges": [ { "Description": "Access from NY office", "CidrIp": "203.0.113.0/24" } ], "ToPort": 22, "IpProtocol": "tcp", "UserIdGroupPairs": [] } ], "GroupName": "MySecurityGroup", "VpcId": "vpc-1a2b3c4d", "OwnerId": "123456789012", "GroupId": "sg-903004f8", } ] }

Example 2: To describe security groups that have specific rules

The following describe-security-groups example uses filters to scope the results to security groups that have a rule that allows SSH traffic (port 22) and a rule that allows traffic from all addresses (0.0.0.0/0). The example uses the --query parameter to display only the names of the security groups. Security groups must match all filters to be returned in the results; however, a single rule does not have to match all filters. For example, the output returns a security group with a rule that allows SSH traffic from a specific IP address and another rule that allows HTTP traffic from all addresses.

aws ec2 describe-security-groups \ --filters Name=ip-permission.from-port,Values=22 Name=ip-permission.to-port,Values=22 Name=ip-permission.cidr,Values='0.0.0.0/0' \ --query "SecurityGroups[*].[GroupName]" \ --output text

Output:

default my-security-group web-servers launch-wizard-1

Example 3: To describe security groups based on tags

The following describe-security-groups example uses filters to scope the results to security groups that include test in the security group name, and that have the tag Test=To-delete. The example uses the --query parameter to display only the names and IDs of the security groups.

aws ec2 describe-security-groups \ --filters Name=group-name,Values=*test* Name=tag:Test,Values=To-delete \ --query "SecurityGroups[*].{Name:GroupName,ID:GroupId}"

Output:

[ { "Name": "testfornewinstance", "ID": "sg-33bb22aa" }, { "Name": "newgrouptest", "ID": "sg-1a2b3c4d" } ]

For additional examples using tag filters, see Working with tags in the Amazon EC2 User Guide.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static void describeSecurityGroups(Ec2Client ec2, String groupId) { try { DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder() .groupIds(groupId) .build(); // Use a paginator. DescribeSecurityGroupsIterable listGroups = ec2.describeSecurityGroupsPaginator(request); listGroups.stream() .flatMap(r -> r.securityGroups().stream()) .forEach(group -> System.out .println(" Group id: " +group.groupId() + " group name = " + group.groupName())); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import { DescribeSecurityGroupsCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; // Log the details of a specific security group. export const main = async () => { const command = new DescribeSecurityGroupsCommand({ GroupIds: ["SECURITY_GROUP_ID"], }); try { const { SecurityGroups } = await client.send(command); console.log(JSON.stringify(SecurityGroups, null, 2)); } catch (err) { console.error(err); } };
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

suspend fun describeEC2SecurityGroups(groupId: String) { val request = DescribeSecurityGroupsRequest { groupIds = listOf(groupId) } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeSecurityGroups(request) response.securityGroups?.forEach { group -> println("Found Security Group with id ${group.groupId}, vpc id ${group.vpcId} and description ${group.description}") } } }
PowerShell
Tools for PowerShell

Example 1: This example describes the specified security group for a VPC. When working with security groups belonging to a VPC you must use the security group ID (-GroupId parameter), not name (-GroupName parameter), to reference the group.

Get-EC2SecurityGroup -GroupId sg-12345678

Output:

Description : default VPC security group GroupId : sg-12345678 GroupName : default IpPermissions : {Amazon.EC2.Model.IpPermission} IpPermissionsEgress : {Amazon.EC2.Model.IpPermission} OwnerId : 123456789012 Tags : {} VpcId : vpc-12345678

Example 2: This example describes the specified security group for EC2-Classic. When working with security groups for EC2-Classic you may use either the group name (-GroupName parameter) or group ID (-GroupId parameter) to reference the security group.

Get-EC2SecurityGroup -GroupName my-security-group

Output:

Description : my security group GroupId : sg-45678901 GroupName : my-security-group IpPermissions : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission} IpPermissionsEgress : {} OwnerId : 123456789012 Tags : {} VpcId :

Example 3: This example retrieves all the security groups for the vpc-0fc1ff23456b789eb

Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class SecurityGroupWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions.""" def __init__(self, ec2_resource, security_group=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param security_group: A Boto3 SecurityGroup object. This is a high-level object that wraps security group actions. """ self.ec2_resource = ec2_resource self.security_group = security_group @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource) def describe(self): """ Displays information about the security group. """ if self.security_group is None: logger.info("No security group to describe.") return try: print(f"Security group: {self.security_group.group_name}") print(f"\tID: {self.security_group.id}") print(f"\tVPC: {self.security_group.vpc_id}") if self.security_group.ip_permissions: print(f"Inbound permissions:") pp(self.security_group.ip_permissions) except ClientError as err: logger.error( "Couldn't get data for security group %s. Here's why: %s: %s", self.security_group.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
SAP ABAP
SDK for SAP ABAP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

TRY. DATA lt_group_ids TYPE /aws1/cl_ec2groupidstrlist_w=>tt_groupidstringlist. APPEND NEW /aws1/cl_ec2groupidstrlist_w( iv_value = iv_group_id ) TO lt_group_ids. oo_result = lo_ec2->describesecuritygroups( it_groupids = lt_group_ids ). " oo_result is returned for testing purposes. " DATA(lt_security_groups) = oo_result->get_securitygroups( ). MESSAGE 'Retrieved information about security groups.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.

For a complete list of Amazon SDK developer guides and code examples, see Create Amazon EC2 resources using an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.