Upload files into AWS EC2 using aws cli

We all have heard about codepipeline which simply triggered by a source commit and start a pipeline to build application then deploy automatically to ec2 servers. Upload files to aws ec2. Well this article is not about code pipeline but a simple script that will make a build in your system and upload directly to ec2 machine. It is for developer use only who has access to AWS cli. If you don’t have AWS cli configure then you need to configure one with AWS secret ID. Upload files into AWS EC2 using aws cli.

We will be using SCP command which state as Secure Copy in order to transfer files from local computer to ec2 machine.

Upload files into AWS EC2 using aws cli using SCP

Let’s create a file sandbox.sh file or any file name you wish to begin. The code is preety straight forward. So you can customized according to your needs. First we run a command to make build and if the build is successfull we show message. Then we attempt to connect ec2 machine using SCP command which accept pem file then source and then remote ssh public dns ip with folder name where you need to copy files.

This command will upload a file source folder in your local computer of your laptop to folder destination folder on an Amazon instance. Note you still need to use the private key you used to connect to the Amazon instance with ssh. (In this example, it is the sandboxlinux.pem file inside the assets folder.

Note: The pem file need to be protected and should not be accessible publicy other wise it will not connect. So before running the script run chmod 400 ./yourpath/sandboxlinux.pem


echo "Building test"
if npm run build:prod:ssr ; then
   echo "Sandbox SSR Build Successful"
  echo "exiting.."
  exit 1

echo "Attempting to upload site .."
scp -i ./assets/sandboxlinux.pem ${SOURCE_DIR} ssh_public_dns:~/folder/

#your public dns would look like this.

# echo "Invalidating cloudfrond distribution to get fresh cache"
# aws cloudfront create-invalidation --distribution-id=replace_with_your_distribution_ID --paths / --profile=myawsprofile

echo "Deployment complete" 

This above script is to make build is for Angular based project. However you can customized the build command according to your needs.

Credit source

Credit source 2

Leave a Reply

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