forked from awsdocs/aws-doc-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhello_ec2.py
More file actions
38 lines (31 loc) · 1.44 KB
/
hello_ec2.py
File metadata and controls
38 lines (31 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import logging
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
# snippet-start:[python.example_code.ec2.Hello]
def hello_ec2(ec2_client):
"""
Use the AWS SDK for Python (Boto3) to list the security groups in your account.
This example uses the default settings specified in your shared credentials
and config files.
:param ec2_client: A Boto3 EC2 client. This client provides low-level
access to AWS EC2 services.
"""
print("Hello, Amazon EC2! Let's list up to 10 of your security groups:")
try:
paginator = ec2_client.get_paginator("describe_security_groups")
response_iterator = paginator.paginate(PaginationConfig={'MaxItems': 10}) # List only 10 security groups.
logging.basicConfig(level=logging.INFO) # Enable logging.
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
if __name__ == "__main__":
hello_ec2(boto3.client("ec2"))
# snippet-end:[python.example_code.ec2.Hello]