DEV Community

Ravi Agheda
Ravi Agheda

Posted on • Updated on

GitHub Action with EC2 using SSH

Rocket

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 fullscreen mode Exit fullscreen mode

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 authroised keys
cat github-actions.pub >> ~/.ssh/authorized_keys
Enter fullscreen mode Exit fullscreen mode

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
              '
Enter fullscreen mode Exit fullscreen mode

Gist Ref: https://gist.github.com/raviagheda/c69ae5e884f4490b1af656dbd80c00dd

Enjoy!

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!

Top comments (2)

Collapse
 
harikarumuri profile image
HariKarumuri • Edited

is this ci/cd?
when i commit and push code to github , will it directly change in ec2 ngnix?

Collapse
 
raviagheda profile image
Ravi Agheda

Yes, Indeed.