How to upload files to S3 Bucket using AWS CLI

This post explains how to upload objects to AWS S3 Bucket using AWS CLI. In this tutorial we will learn how to upload object to S3 using both s3 cp and s3api put-object commands.

To run the AWS CLI commands you need to have AWS CLI installed and configured, follow below articles to set up AWS CLI.

[On Windows]

1. How to install AWS CLI on windows
2. How to configure AWS CLI

[On Ubuntu]

1. How to install AWS CLI on Ubuntu
2. How to configure AWS CLI

File upload to S3 using s3api

Syntax


   

aws s3api put-object --bucket "BUCKET_NAME" --key "OBJECT_KEY" --body "OBJECT"

   

Example


Following command uploads sample.txt file to test-s3-bucket with key data/sample.txt.

 

aws s3api put-object --bucket test-s3-bucket --key data/sample.txt --body sample.txt

   

File upload to S3 using s3 cp

Syntax


  

aws s3 cp [<Arguments> ...]

   

Examples


1. Upload single file to S3 bucket

Following command uploads file sample.txt to data folder inside bucket test-s3-bucket.

   

aws s3 cp sample2.txt s3://test-s3-bucket/data/

   

2. Upload all files from a folder to S3 bucket recursively

Following command uploads all files from folder tmp to data/tmp/ folder inside bucket test-s3-bucket.

   

aws s3 cp tmp/ s3://test-s3-bucket/data/tmp/ --recursive

   
Output
   
upload: tmp\test4.txt to s3://test-s3-bucket/data/tmp/test4.txt
upload: tmp\test2.txt to s3://test-s3-bucket/data/tmp/test2.txt
upload: tmp\sample2.html to s3://test-s3-bucket/data/tmp/sample2.html
upload: tmp\test1.txt to s3://test-s3-bucket/data/tmp/test1.txt
upload: tmp\sample.html to s3://test-s3-bucket/data/tmp/sample.html  
upload: tmp\sample3.html to s3://test-s3-bucket/data/tmp/sample3.html
upload: tmp\test3.txt to s3://test-s3-bucket/data/tmp/test3.txt   
   
3. Upload only text files

Following command uploads only the files which are ending with .txt from folder tmp to data/tmp/text/ folder inside bucket test-s3-bucket.

   

aws s3 cp tmp/ s3://test-s3-bucket/data/tmp/text/ --recursive --exclude "*" --include "*.txt"

   
Output
   
upload: tmp\test2.txt to s3://test-s3-bucket/data/tmp/text/test2.txt
upload: tmp\test4.txt to s3://test-s3-bucket/data/tmp/text/test4.txt
upload: tmp\test1.txt to s3://test-s3-bucket/data/tmp/text/test1.txt
upload: tmp\test3.txt to s3://test-s3-bucket/data/tmp/text/test3.txt
   
4. Exclude text files from getting uploaded

Following command excludes the files which are ending with .txt in folder tmp and uploads all other files to data/tmp/other/ folder inside bucket test-s3-bucket.

   

aws s3 cp tmp/ s3://test-s3-bucket/data/tmp/other/ --recursive --exclude "*.txt" 

 
Output
   
upload: tmp\sample3.html to s3://test-s3-bucket/data/tmp/other/sample3.html
upload: tmp\sample.html to s3://test-s3-bucket/data/tmp/other/sample.html
upload: tmp\sample2.html to s3://test-s3-bucket/data/tmp/other/sample2.html
 

Category: AWS