Skip to content

Instantly share code, notes, and snippets.

@yordanoweb
Last active January 13, 2025 19:42
Show Gist options
  • Save yordanoweb/6984a74abb1b163eebb95479a61cc2bf to your computer and use it in GitHub Desktop.
Save yordanoweb/6984a74abb1b163eebb95479a61cc2bf to your computer and use it in GitHub Desktop.

SSH to VPS from GitHub actions

SSH Key: Generate an SSH key pair if you don't have one:

ssh-keygen -t rsa -b 4096 -C "[email protected]"

Copy the public key to your VPS:

ssh-copy-id username@your_vps_ip

Can do it manually adding the public key to ~/.ssh/authorized_keys

Actions config

Add SSH Private Key to GitHub Secrets

  • Go to your repository on GitHub.
  • Navigate to Settings > Secrets and variables > Actions.
  • Add a new secret named SSH_PRIVATE_KEY and paste the contents of your private key (id_ed25519).

Create a Workflow File

Create a YAML workflow file in your repository: .github/workflows/deploy.yml

Define the Workflow

Add the following content to your deploy.yml file:

name: Deploy to Server

on:
  push:
    branches:
      - master  # Adjust based on your branch strategy

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Setup SSH
        uses: webfactory/[email protected]
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

      - name: Add known hosts
        run: |
          mkdir -p ~/.ssh
          ssh-keyscan -H your_vps_ip >> ~/.ssh/known_hosts

      - name: Upload files to server
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.SERVER_IP }}
          username: ${{ secrets.SERVER_USERNAME }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          port: 22  # Change if your SSH runs on a different port
          source: "path/to/local/files/*"  # Adjust based on your local file paths
          target: "/path/to/remote/directory/"  # Adjust to your target directory on the VPS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment