2022-10-11 15:26:03 -07:00
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
2024-09-05 12:39:58 -04:00
import logging
2022-10-11 15:26:03 -07:00
import boto3
2024-09-05 12:39:58 -04:00
from botocore . exceptions import ClientError
logger = logging . getLogger ( __name__ )
2022-10-11 15:26:03 -07:00
2023-10-18 10:35:05 -07:00
2024-09-05 12:39:58 -04:00
# snippet-start:[python.example_code.ec2.Hello]
def hello_ec2 ( ec2_client ) :
2022-10-11 15:26:03 -07:00
"""
2024-09-05 12:39:58 -04:00
Use the AWS SDK for Python (Boto3) to list the security groups in your account.
2022-10-11 15:26:03 -07:00
This example uses the default settings specified in your shared credentials
and config files.
2024-09-05 12:39:58 -04:00
:param ec2_client: A Boto3 EC2 client. This client provides low-level
access to AWS EC2 services.
2022-10-11 15:26:03 -07:00
"""
print ( " Hello, Amazon EC2! Let ' s list up to 10 of your security groups: " )
2024-09-05 12:39:58 -04:00
try :
paginator = ec2_client . get_paginator ( " describe_security_groups " )
2025-03-06 15:43:23 +03:00
response_iterator = paginator . paginate ( PaginationConfig = { ' MaxItems ' : 10 } ) # List only 10 security groups.
logging . basicConfig ( level = logging . INFO ) # Enable logging.
2024-09-05 12:39:58 -04:00
for page in response_iterator :
for sg in page [ " SecurityGroups " ] :
logger . info ( f " \t { sg [ ' GroupId ' ] } : { sg [ ' GroupName ' ] } " )
except ClientError as err :
logger . error ( " Failed to list security groups. " )
if err . response [ " Error " ] [ " Code " ] == " AccessDeniedException " :
logger . error ( " You do not have permission to list security groups. " )
raise
2022-10-11 15:26:03 -07:00
2023-10-18 10:35:05 -07:00
if __name__ == " __main__ " :
2024-09-05 12:39:58 -04:00
hello_ec2 ( boto3 . client ( " ec2 " ) )
2022-10-11 15:26:03 -07:00
# snippet-end:[python.example_code.ec2.Hello]