Creating a GitHub Action to deploy using a remote script run via SSH

Creating a GitHub Action to deploy using a remote script run via SSH

~ 2 min read

AIM

This workflow will run whenever you push to the main branch, SSH into the host using your secret credentials, and run a command or script in this case make update.

Add Your SSH Private Key to GitHub Secrets

You need a private key GitHub Actions can use to SSH into your server.

🔐 On your local machine:

Generate an SSH key pair (if you don’t already have one for this purpose):

ssh-keygen -t ed25519 -C "github-action" -f ./github_action_ssh_key

You’ll get:

  • github_action_ssh_key (private key)
  • github_action_ssh_key.pub (public key)

On your server:

Add the public key to ~/.ssh/authorized_keys for the user you’ll SSH as:

cat github_action_ssh_key.pub >> ~/.ssh/authorized_keys

Ensure the permissions are correct:

chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh

In your GitHub repo:

Go to Settings → Secrets and variables → Actions → New repository secret and add:

  • SSH_PRIVATE_KEY → contents of github_action_ssh_key
  • SSH_HOST → e.g. your.server.com or its IP address
  • SSH_USER → e.g. ubuntu

Create the GitHub Action

In your repo, add this workflow:

.github/workflows/ssh-deploy.yml

name: SSH Deploy

on:
  push:
    branches:
      - main  # or any branch you want

jobs:
  remote-make-update:
    runs-on: ubuntu-latest

    steps:
      - name: Set up SSH key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts

      - name: SSH and run make update
        run: |
          ssh -i ~/.ssh/id_ed25519 ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }} 'make update'

Done!

This workflow will run whenever you push to the main branch, SSH into the host using your secret credentials, and run make update replace the later with whatever command deploys your code on the server e.g. a script that pulls the latest updates from git, checks out the production branch and runs migrations and builds frontend JavaScript and associated assets. A quick search of github will locate many starter deploy shell scripts.

all posts →