Skip to content

Instantly share code, notes, and snippets.

@chandra10207
Forked from raviagheda/github-action-ssh.md
Created April 7, 2023 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chandra10207/a3b6f19232516aad0f91b1b945f68329 to your computer and use it in GitHub Desktop.
Save chandra10207/a3b6f19232516aad0f91b1b945f68329 to your computer and use it in GitHub Desktop.
Github Action with EC2 using SSH

Github Action with EC2 using SSH

Configure SSH into aws ec2

Declare these git secrets

  • SSH_PRIVATE_KEY
  • HOST_NAME / IP_ADDRESS
  • USER_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
              '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment