Skip to content

Instantly share code, notes, and snippets.

@muhammadardie
Created April 15, 2025 08:02
Show Gist options
  • Save muhammadardie/28e16198c25dd16ce4fead2e546d5c6c to your computer and use it in GitHub Desktop.
Save muhammadardie/28e16198c25dd16ce4fead2e546d5c6c to your computer and use it in GitHub Desktop.
Example step to create GitHub Action for Automatic Code Deployment via SSH

CI/CD Structure Used

Branch develop → Deploy to staging server
Branch main → Deploy to production server
Environment & Secrets are used to securely store credentials

1. Add SSH Key to VPS

GitHub Actions requires SSH access to the VPS for deployment.
On both the development and production VPS, run the following:

ssh-keygen -t ed25519 -C "github-actions" -f ~/.ssh/github_actions
cat ~/.ssh/github_actions.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

Copy the private key (~/.ssh/github_actions) and add it to GitHub Secrets:

2. Set Up Secrets in GitHub

Add secrets in GitHub Repository → Settings → Secrets and Variables → Actions

For staging (develop):

  • STAGING_VPS_HOST → IP of the staging VPS
  • STAGING_VPS_USER → SSH user on the VPS
  • STAGING_SECRET_KEY → Private SSH Key

For production (main):

  • PROD_VPS_HOST → IP of the production VPS
  • PROD_VPS_USER → SSH user on the VPS
  • PROD_SECRET_KEY → Private SSH Key

3. Create GitHub Actions (.github/workflows/deploy.yml)

name: Deploy to Server

on:
  push:
    branches:
      - develop
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: ${{ github.ref == 'refs/heads/main' && 'main' || 'develop' }}

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Setup SSH Connection
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H ${{ secrets.VPS_HOST }} >> ~/.ssh/known_hosts

      - name: Pull Latest Code on Server
        run: |
          ssh ${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }} << 'EOF'
            cd /var/www/myapp
            git pull origin $(basename ${{ github.ref }})
          EOF

4. Testing Deployment

  1. Push to develop → GitHub Actions will deploy to the staging server
  2. Push to main → GitHub Actions will deploy to the production server
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment