You can use the below Python script to check if a key exists in an S3 bucket using boto3/
Step 1: Install and configure boto3
https://cloudaffaire.com/how-to-install-python-boto3-sdk-for-aws/
https://cloudaffaire.com/how-to-configure-python-boto3-sdk-for-aws/
https://pypi.org/project/argparse/
Step 2: Create a python script to check if a key exists in S3 bucket
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
## Create a python script that checks if a key exists in an S3 bucket cat << EOF > check_key_exists.py import argparse import boto3 from botocore.exceptions import ClientError parser = argparse.ArgumentParser(description='Check if a key exists in S3') parser.add_argument('--bucket_name', type=str, help='The name of the bucket') parser.add_argument('--key', type=str, help='file or folder path in S3') args = parser.parse_args() client = boto3.client('s3') def check_key_exists(bucket_name, key): try: client.head_object(Bucket=bucket_name, Key=key) print("key exists!") except ClientError as e: print(e) bucket_name = args.bucket_name key = args.key check_key_exists(bucket_name, key) EOF |
Step 3: Execute the script to check if a key exists in an S3 bucket using boto3
1 2 3 |
## Check if a key exists in s3 bucket python3 check_key_exists.py --bucket_name cloudaffaire1 --key targetDir/targetFile python3 check_key_exists.py --bucket_name cloudaffaire1 --key targetDir/filenotexists |