import boto3
from botocore.exceptions import ClientError
def check_s3_bucket_exists(bucket_name):
"""
指定したS3バケットが存在するかどうかをチェックします。
:param bucket_name: チェックするバケットの名前
:return: バケットが存在する場合はTrue、そうでない場合はFalse
"""
s3 = boto3.client('s3')
try:
s3.head_bucket(Bucket=bucket_name)
return True
except ClientError as e:
# バケットが存在しない場合、エラーコードは404 NotFoundになります
if e.response['Error']['Code'] == '404':
return False
# 他のエラーの場合は例外を再スロー
raise
# バケット名を指定して関数をテスト
bucket_name = "your-bucket-name"
if check_s3_bucket_exists(bucket_name):
print(f"バケット {bucket_name} は存在します。")
else:
print(f"バケット {bucket_name} は存在しません。")
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme