AWS Code Sample
Catalog

bucket_exists.py

bucket_exists.py demonstrates how to determine whether an Amazon S3 bucket exists.

# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import logging import boto3 from botocore.exceptions import ClientError def bucket_exists(bucket_name): """Determine whether bucket_name exists and the user has permission to access it :param bucket_name: string :return: True if the referenced bucket_name exists, otherwise False """ s3 = boto3.client('s3') try: response = s3.head_bucket(Bucket=bucket_name) except ClientError as e: logging.debug(e) return False return True def main(): """Exercise bucket_exists()""" # Assign this value before running the program test_bucket_name = 'BUCKET_NAME' # Set up logging logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(asctime)s: %(message)s') # Check if the bucket exists if bucket_exists(test_bucket_name): logging.info(f'{test_bucket_name} exists and you have permission to access it.') else: logging.info(f'{test_bucket_name} does not exist or ' f'you do not have permission to access it.') if __name__ == '__main__': main()

Sample Details

Service: s3

Last tested: 2019-2-12

Author: AWS

Type: full-example

On this page: