Snippets

Levelset Engineering Upload File to S3

Created by Patrick Marlow
import argparse
import boto3
from botocore.exceptions import ClientError

parser = argparse.ArgumentParser(description='Upload the specified file to the specified AWS S3 bucket.')

parser.add_argument('--file',  help='path of the file to upload to S3')
parser.add_argument('--bucket', help='path of the S3 bucket')

args = parser.parse_args()

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    s3 = boto3.client('s3')
    try:
        response = s3.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True

if __name__ == '__main__':
    file_name = args.file
    bucket = args.bucket
    upload_file(file_name, bucket, object_name=None)

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.