GitHub Action with EC2 using SSH
šŸš€

GitHub Action with EC2 using SSH

Published
Published August 25, 2023
Author
It's pretty easy to set up GitHub action with AWS EC2 for deployments using SSH key, follow these 3 breakdowns to implement the pipeline.

1. Generate SSH Key

cd ~/.ssh ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter file name: "key_name"
lsĀ and list out files of the .ssh folder, you should be seeing "key_name" and "key_name.pub"
  • Add public key to authorised keys
cat github-actions.pub >> ~/.ssh/authorized_keys
For detailed information on SSH Key generation process check this reference:Ā https://zellwk.com/blog/github-actions-deploy/

2. Set Github Secrets

SSH_PRIVATE_KEY: private key that we created on ec2
HOST_NAME / IP_ADDRESS: Elastic IP or IP of EC2
USER_NAME: user name of the ec2 user.

3. Create a branch_name.yml ( forĀ devĀ branchĀ dev.ymlĀ ) file under .github/workflows

Update the dev to your branch name
name: Deploy on: push: branches: [ dev ] jobs: Deploy: name: Deploy to EC2 runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Build & Deploy env: PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }} HOSTNAME: ${{secrets.SSH_HOST}} USER_NAME: ${{secrets.USER_NAME}} run: | echo "$PRIVATE_KEY" > private_key && chmod 600 private_key ssh -o StrictHostKeyChecking=no -i private_key ${USER_NAME}@${HOSTNAME} ' # Now we have got the access of EC2 and we will start the deploy . cd /home/ubuntu/<PROJECT_DIRECTORY> && git checkout dev && git fetch --all && git reset --hard origin/dev && git pull origin dev && sudo npm i && sudo npm run build && sudo pm2 stop ./dist/index.js && sudo pm2 start ./dist/index.js '
Ā 
If you are here it means you may have enjoyed reading this blog. Just follow meĀ "Ravi Agheda"Ā which will motivate to write more, and contribute to open source. You can make me aĀ coffeeā˜•ļøĀ . Small support comes a long way!