CI/CD and automation · Advanced · 20 min
How to Deploy to Your Server over SSH from GitHub Actions
By Padding · Updated 15 Nov 2026
GitHub Actions · Ubuntu 26.04.1 LTS
You will set up a deploy key that can only do one thing on your Ubuntu 26.04 server, store it as an encrypted GitHub environment secret, and write a workflow that uploads each release over SSH and switches to it with a single atomic step.
On this page
A deploy from GitHub Actions means giving a machine you do not control, the runner, a way into your server. Get this wrong and you have put a master key into a CI system. The usual shortcut, the admin's own SSH key pasted into a secret, hands over a login shell and often root. This tutorial gives the runner a key that can do exactly one thing.
The design is small. A dedicated deploy user owns a releases folder. Its SSH key is tied to one forced command: a root-owned script that receives a tar archive on standard input, unpacks it into a new release folder, and moves a current symlink to it. The runner pipes the site into that script. Whatever the runner sends, it cannot open a shell, copy other files, or edit the script. Your web server serves /srv/app/current, so a deploy is one atomic switch.
Step 1 · Create the deploy user and the release script
On the server, as your sudo user. Create a user with no password and no way to log in except by SSH key. The user owns /srv/app, where releases live:
sudo adduser --disabled-password --gecos "" deploy
sudo mkdir -p /srv/app/releases
sudo chown -R deploy:deploy /srv/appNow the script that the key will be tied to. It must be owned by root and not writable by deploy. If the deploy user could edit its own forced command, the restriction would mean nothing. The script unpacks standard input into a fresh folder, removes that folder again if anything fails, swaps the current symlink in one step, and keeps the five newest releases:
sudo tee /usr/local/bin/receive-release >/dev/null <<'SCRIPT'
#!/bin/bash
set -euo pipefail
base=/srv/app
release="$(mktemp -d "$base/releases/$(date +%Y%m%d%H%M%S).XXXXXX")"
chmod 755 "$release"
trap 'rm -rf "$release"' ERR
tar -xzf - -C "$release"
test -n "$(ls -A "$release")"
ln -sfn "$release" "$base/current.new"
mv -T "$base/current.new" "$base/current"
trap - ERR
ls -1dt "$base"/releases/* | tail -n +6 | xargs -r rm -rf
echo "deployed $release"
SCRIPT
sudo chown root:root /usr/local/bin/receive-release
sudo chmod 755 /usr/local/bin/receive-releaseHow it works:
mktemp -dcreates a new folder with a unique name (the date plus random characters), so two deploys in the same second can never share, and delete, one folder. It creates it private, so the next line makes it readable for the web server.tar -xzf -reads a gzip-compressed tar archive from standard input, which is what the SSH connection supplies.- The
trapdeletes the half-made release iftaror the empty-folder test fails, andset -estops the script, socurrentnever points at a broken release.trap - ERRswitches the cleanup off oncecurrentpoints at the new release, so a failure in the later pruning step can never delete the release that is live. ln -sfnbuilds the new link under a temporary name, andmv -Trenames it overcurrent. A rename is atomic, so a visitor sees the old release or the new one, never a mixture.
Point your web server's root at /srv/app/current. For Nginx, see /tutorials/install-nginx-on-ubuntu-26-04.
Step 2 · Make a key that only runs that script
On your own computer, create a new key pair for CI only. Use a new key, never your personal one. A CI key cannot have a passphrase, because nobody is there to type it, which is the reason to limit what it can do. Work in an empty folder, and delete it when you finish:
mkdir ci-key
cd ci-key
ssh-keygen -t ed25519 -N '' -C "github-actions-deploy" -f deploy_keyssh-keygen writes deploy_key (private, mode 600) and deploy_key.pub. Show the public half, which is safe to share, so that you can copy it:
cat deploy_key.pubNow authorise it on the server, with options in front of it. restrict turns off port forwarding, agent forwarding, X11 and terminal allocation, and command= forces this one script no matter what the client asks to run. The file must be private from the start. On the server, paste the line you copied when read waits for it:
read -r PUBKEYThen create the file and add the key:
sudo install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
sudo install -m 600 -o deploy -g deploy /dev/null /home/deploy/.ssh/authorized_keys
printf 'restrict,command="/usr/local/bin/receive-release" %s\n' "$PUBKEY" | sudo tee -a /home/deploy/.ssh/authorized_keys >/dev/null
sudo cat /home/deploy/.ssh/authorized_keysThe last command prints one line starting with restrict,command="/usr/local/bin/receive-release" ssh-ed25519 AAAA. If your server already blocks users that are not in a list (AllowUsers in /etc/ssh/sshd_config, see /tutorials/harden-ssh-on-ubuntu-26-04), add deploy to it, and reload SSH as that tutorial shows. A mistake there can lock you out, so keep your current session open and test from a second terminal.
Record the server's host key, so that the runner can prove it is talking to your server and not an impostor. First compare the fingerprint that the server reports about itself with the one the network gives you. On the server:
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubIf the server was created before the host key existed, sshd generates it on first start. Now, on your computer, fetch the same key and compare fingerprints. Set DEPLOY_HOST to your server's address first. The result goes into a file you will upload as a secret:
DEPLOY_HOST=203.0.113.10ssh-keyscan -t ed25519 "$DEPLOY_HOST" > known_hosts 2>/dev/null
ssh-keygen -lf known_hostsThe two fingerprints must match. If they differ, stop: someone may be intercepting the connection, or you used the wrong address.
Check it worked
On your computer: pack a test site and send it the way the workflow will. -o IdentitiesOnly=yes makes SSH use only this key, and UserKnownHostsFile uses the file you just verified:
mkdir -p ../site
printf '<h1>Release one</h1>\n' > ../site/index.html
tar -czf - -C ../site . | ssh -i deploy_key -o IdentitiesOnly=yes -o UserKnownHostsFile=known_hosts -o StrictHostKeyChecking=yes deploy@"$DEPLOY_HOST"The script prints deployed /srv/app/releases/<timestamp>.<random>.
On the server: look at the result.
sudo ls -l /srv/app
sudo cat /srv/app/current/index.htmlcurrent is a symlink to the new release folder, and the page file holds <h1>Release one</h1>. Now confirm that the key cannot do anything else.
On your computer: ask for a different command. The forced command ignores it and runs the script, which fails on empty input and cleans up after itself:
ssh -i deploy_key -o IdentitiesOnly=yes -o UserKnownHostsFile=known_hosts deploy@"$DEPLOY_HOST" 'cat /etc/passwd' </dev/null || echo "exit status $?: the requested command was not run"On the server: count the releases.
sudo ls /srv/app/releases | wc -lYou do not get /etc/passwd. The error comes from the script's tar, and the number of releases is still 1.
Troubleshooting
Permission denied (publickey): check the permissions withsudo ls -ld /home/deploy /home/deploy/.ssh /home/deploy/.ssh/authorized_keys. The home folder must not be writable by others,.sshmust be700and the file600, all owned bydeploy. TheAllowUserssetting is another cause.- The connection closes at once, or the upload reports an error: the forced script failed. Run
sudo -u deploy /usr/local/bin/receive-release < /dev/nullon the server to see its error. On the server,/var/log/auth.logalso records why a login was refused. Host key verification failed: theknown_hostsfile does not hold the key of the address you connect to. If you changed the address, runssh-keyscanagain.
Step 3 · Store the secrets in a GitHub environment
Upload the private key and the host key as encrypted secrets. Run these on your computer. Secrets are write-only in GitHub: after you save them, nobody can read them back, but any workflow that is allowed to use them can print them in a modified run, so only let trusted code run in this workflow. Use an environment named production, so you can restrict who and what can use them. The gh commands read the value from a file, not from the command line, so it stays out of your shell history. Replace OWNER/REPO with your repository. Create the environment first, with the REST call for creating or updating an environment (the token behind gh needs the repo scope), and then add the secrets to it:
gh api --method PUT repos/OWNER/REPO/environments/production
gh secret set SSH_PRIVATE_KEY --env production --repo OWNER/REPO < deploy_key
gh secret set SSH_KNOWN_HOSTS --env production --repo OWNER/REPO < known_hosts
gh variable set DEPLOY_HOST --env production --repo OWNER/REPO --body "203.0.113.10"SSH_PRIVATE_KEY and SSH_KNOWN_HOSTS are secrets. The host name is not secret, so it is a variable. GitHub also creates an environment on its own when a workflow first names it, but then it starts with no secrets, so create it first as above. 203.0.113.10 is a documentation address; use your server's.
You can do the same in the web interface: in the repository settings, look for something like Environments, open or create production, and add the two secrets and the variable there. Then, still in that environment's settings, restrict deployment branches to main, and consider adding required reviewers, which makes every deploy wait for an approval click. Labels change from time to time, so follow the current guide at docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments.
Once the secrets are saved, delete the local copies of the private key, so the only copy is in GitHub:
cd ..
rm -rf ci-keyKeep known_hosts if you want it, since it holds only public information. If you ever suspect the key has leaked, remove its line from authorized_keys on the server, which cuts off access at once, and create a new pair.
Step 4 · Write the workflow
Create .github/workflows/deploy.yml. The tests job is a stand-in for your own checks; a deploy that skips them is a gamble. The deploy job waits for it with needs, runs only on main, and uses the production environment:
mkdir -p .github/workflows
cat > .github/workflows/deploy.yml <<'YAML'
name: Deploy
on:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: deploy-production
cancel-in-progress: false
jobs:
tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: Check that the site has a home page
run: test -f site/index.html
deploy:
needs: tests
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v7
- name: Prepare SSH
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
run: |
install -d -m 700 ~/.ssh
install -m 600 /dev/null ~/.ssh/deploy_key
printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/deploy_key
printf '%s\n' "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
- name: Upload the release
env:
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
run: |
tar -czf - -C site . | ssh -i ~/.ssh/deploy_key \
-o IdentitiesOnly=yes -o StrictHostKeyChecking=yes \
deploy@"$DEPLOY_HOST"
YAMLThe choices worth knowing:
- Secrets reach the shell as environment variables (
env:), never inline in arun:line. That keeps them out of the script text, and GitHub masks their values in logs. Do notechothem, and do not enable debug logging while they are in use. - The key file is created private first (
install -m 600 /dev/null) and then filled, so it is never readable by other users on the runner.printf '%s\n'writes the key with the trailing newline that OpenSSH insists on. StrictHostKeyChecking=yesrefuses any host whose key is not inknown_hosts. Never useStrictHostKeyChecking=noin a deploy: it removes the one check that stops an impostor.concurrencywithcancel-in-progress: falsequeues deploys instead of cancelling one that has started, so two deploys never overlap.- The workflow uses no third-party action.
actions/checkout@v7is GitHub's own at its current major version (github.com/actions/checkout/releases). If you adopt a third-party action for SSH, pin it to a full commit hash, because a tag can be moved. - The workflow's token is
contents: readonly. The deploy uses the SSH key, not GitHub's token.
Check the file with actionlint (github.com/rhysd/actionlint, version 1.7.12; /tutorials/github-actions-first-workflow shows how to download it):
actionlint
echo "actionlint exit code: $?"No output and exit code 0 mean the file is well formed.
Step 5 · Push, then check the result
Commit the workflow and push to main. The Actions tab shows the Deploy run, and if you set required reviewers, it waits for approval first. After it turns green, load your site: it serves the new release.
git add .github/workflows/deploy.yml
git commit -m "Add deploy workflow"
git push origin main
gh run watchTo confirm on the server, as your admin user:
sudo ls -l /srv/appcurrent points at the newest folder in releases. Each deploy adds a folder and the script prunes all but the five newest.
Roll back
To go back, repoint the link at a previous release. You do this as an admin, not through the CI key. List the releases, newest first, and pick the one you want. <timestamp> stands for a real folder name from the list:
sudo sh -c 'ls -1dt /srv/app/releases/*'sudo ln -sfn /srv/app/releases/<timestamp> /srv/app/current.new
sudo mv -T /srv/app/current.new /srv/app/currentThe next push deploys the newest commit again, so revert the bad commit in Git as well.
Step 6 · Clean up
To remove the setup from a server you used only to follow along, delete the user, its home folder and the files. The next commands delete /srv/app, including every release, and the deploy user's home folder, so skip them on a server that is serving a real site:
sudo deluser --remove-home deploy
sudo rm -rf /srv/app /usr/local/bin/receive-releaseThe key also lives in GitHub. On your computer, delete the production environment. Deleting an environment deletes the secrets and protection rules that belong to it (GitHub's documentation says so). Then delete the local known_hosts file and the .github/workflows/deploy.yml file if you do not want them:
gh api --method DELETE repos/OWNER/REPO/environments/productionThe secrets and DEPLOY_HOST were scoped to that environment, so they are gone with it. If you keep the server setup instead, nothing on the server needs cleaning, and removing the authorized_keys line revokes the key at once.
Next steps
- Run tests before every deploy:
/tutorials/run-node-tests-in-github-actions. - Tighten the SSH server that the runner connects to:
/tutorials/harden-ssh-on-ubuntu-26-04. - Review how keys and secrets stay out of Git:
/tutorials/keep-secrets-out-of-git. - GitHub's documentation: docs.github.com/en/actions/how-tos/security-for-github-actions/security-guides/using-secrets-in-github-actions and docs.github.com/en/actions/reference/security/secure-use.
Related tutorials
- How to Log In to a Linux Server with SSH KeysYou will create an Ed25519 SSH key, install its public half on a server, log in without a password, and save the connection as a short name.
- How to Harden SSH on Ubuntu 26.04: Keys Only, No Root, Custom LimitsYou will switch an Ubuntu 26.04 server's SSH daemon to key-only logins, turn off root login, limit who can connect and how many guesses they get, and test the change without locking yourself out.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials