Boto3: Upload a file to s3

Create an IAM role for s3 and attach the role to the EC2 instance.

import boto3
import sys
import os
from datetime import datetime
import traceback

bucket_name = 'some-bucket'
file_to_upload = "/path/to/file"
file_name = 'file'

try :
  s3 = boto3.resource('s3')
  bucket = s3.Bucket(bucket_name)
  bucket.upload_file(file_to_upload, file_name)
  print( "{} copied to {}".format( file_to_upload, bucket ) )
except Exception as err:
  traceback.print_exc()
finally:
  # time is always in GMT 
  print (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

Leave a Reply

Your email address will not be published. Required fields are marked *