Chapter 12 · Lesson 5 of 10
CI/CD and automation

Deploy over SSH from GitHub Actions with a restricted key

An SSH deploy lets a workflow log in to your server with a dedicated key and run one fixed deploy script, so the key can do that job and nothing else.

By the end you will

Deploy from a workflow over SSH using a CI-only key restricted to one script, with the host key pinned and approval required.

Time
30 min
Level
Intermediate
Check
4 questions
You need
  • A server you can reach over SSH with sudo
  • A pushed image or code the server can fetch
  • A second SSH session kept open while you edit access

A workflow can deploy by logging in to your server over SSH and running a script. The risk is the key: whoever holds it can log in. So the design goal is a key that is only for CI, belongs to a user with almost no rights, and can run one script and nothing else. This lesson builds that, step by step, and uses the existing SSH keys and deploy keys lesson as background. The concepts behind SSH and SSH keys are in the glossary.

How it works#

The workflow holds a private key as a secret. On the runner it writes the key to a file, adds the server’s pinned host key to known_hosts, and runs ssh deploy@203.0.113.10. On the server, sshd checks the key against the deploy user’s authorized_keys. That entry carries restrictions, including a forced command, so the login runs one deploy script that pulls the image and restarts the service. A protected environment adds a human approval before the job starts.

Warning: you are about to change who can log in to your server. Keep a second SSH session open as root or your sudo user the whole time, and test the new login from a separate terminal before you close anything.

Step 1: Create a dedicated deploy user#

On the server:

bash
sudo adduser --disabled-password --gecos "" deploy
sudo usermod -aG docker deploy

Membership in the docker group is close to root access, because anyone who can talk to the Docker daemon can start a container that mounts the host filesystem. That is why the key below is locked to one forced command instead of a shell.

The docker group gives the user control of Docker, which is effectively root on that host. That is why the key must be locked to one command. If you can avoid the group by running a script through sudo with a narrow sudoers rule, do that. Read Users, groups and sudo before choosing.

Step 2: Generate a key for CI only#

On your own machine, not on the server and not shared with your personal key:

bash
ssh-keygen -t ed25519 -f ./ci-deploy -C "ci-deploy" -N ""

This writes ci-deploy (private) and ci-deploy.pub (public). An empty passphrase is normal here because a workflow cannot type one, which is why the restrictions in the next step matter. Delete the local private key after you store it as a secret.

Step 3: Add the public key with restrictions#

On the server, as the deploy user, edit ~/.ssh/authorized_keys and add one line (it must be a single line):

output
restrict,from="198.51.100.0/24",command="/usr/local/bin/deploy.sh" ssh-ed25519 AAAA...your-public-key... ci-deploy

What the options mean:

  • restrict turns off port forwarding, agent forwarding, X11 forwarding and PTY allocation in one word. You can instead list no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty.
  • command="..." forces that command on every login with this key. The client cannot ask for a shell.
  • from="..." limits which source addresses may use the key. GitHub-hosted runners come from a large, changing set of addresses, so only use from if you use self-hosted runners with a fixed address. Otherwise omit it. The 198.51.100.0/24 above is an example.

Set permissions:

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

Step 4: Write the deploy script#

Create /usr/local/bin/deploy.sh, owned by root, executable, not writable by the deploy user:

bash
#!/usr/bin/env bash
set -euo pipefail

TAG="${SSH_ORIGINAL_COMMAND:-}"
if ! [[ "$TAG" =~ ^sha-[0-9a-f]{7,40}$ ]]; then
  echo "refusing tag: $TAG" >&2
  exit 1
fi

cd /srv/app
IMAGE_TAG="$TAG" docker compose pull
IMAGE_TAG="$TAG" docker compose up -d

With a forced command, whatever the client typed is placed in SSH_ORIGINAL_COMMAND. The script validates it against a strict pattern before use, so the client can pass a tag but cannot inject commands. The compose file reads IMAGE_TAG for the image tag. See Deploy an app with Docker Compose.

Step 5: Pin the host key and store secrets#

On the server, read the real fingerprint, and use that to check what you pin:

bash
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub

From your machine, fetch the key and compare the fingerprint before trusting it:

bash
ssh-keyscan -t ed25519 203.0.113.10 > known_hosts.pin
ssh-keygen -lf known_hosts.pin

If the two fingerprints match, the file is safe to use. In the repository, add secrets under Settings, Secrets and variables, Actions (ideally in an environment, next step): DEPLOY_SSH_KEY (the private key text) and DEPLOY_KNOWN_HOSTS (the contents of known_hosts.pin).

Step 6: Write the workflow with an environment#

Create an environment named production in repository settings and add required reviewers. Then:

yaml
name: deploy

on:
  workflow_dispatch:
    inputs:
      tag:
        description: "Image tag, for example sha-1a2b3c4"
        required: true

permissions:
  contents: read

concurrency:
  group: deploy-production
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Prepare SSH
        run: |
          install -m 700 -d ~/.ssh
          printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_ci
          chmod 600 ~/.ssh/id_ci
          printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > ~/.ssh/known_hosts
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}

      - name: Deploy
        env:
          TAG: ${{ inputs.tag }}
        run: ssh -i ~/.ssh/id_ci -o IdentitiesOnly=yes deploy@203.0.113.10 "$TAG"

The job pauses until a reviewer approves, and only then are the environment secrets available. The plain ssh command needs no third-party action, which keeps the trust surface small. Host key checking stays on, so a changed server key makes the step fail. The tag reaches the shell through env rather than ${{ inputs.tag }} inside the run line, so a crafted input cannot inject commands on the runner.

Check it worked#

Run the workflow, approve it, and read the log: the script output appears and the job ends green. On the server, docker compose ps shows the new image tag. Then test the restriction: from your machine, try ssh -i ci-deploy deploy@203.0.113.10 id. The script should refuse the argument, and you should not get a shell. A key that gives a shell has no forced command.

Edge cases and gotchas#

  • Never use StrictHostKeyChecking=no. It disables the protection that tells you the server is the real one. A pinned known_hosts is the correct fix for host key prompts.
  • Rotate the key. If the secret leaks, delete the line from authorized_keys, generate a new key and update the secret. Do it on a schedule too.
  • Host key changes. After a server rebuild the host key changes and the job fails on purpose. Verify the new fingerprint through another channel, then update the pinned secret.
  • Do not log secrets. Keep set -x out of steps that handle the key.
  • Fork pull requests. Do not trigger deploys from pull_request. Deploy only from workflows on your own branches or manual runs.
  • Concurrent deploys. Use a concurrency group without cancel so two deploys never overlap.

Troubleshooting#

SymptomLikely causeFix
Permission denied (publickey)Wrong key, bad permissions or userCheck authorized_keys mode 600 and the key text. See the troubleshooting lesson
Host key verification failedknown_hosts missing or server key changedRe-pin after verifying the fingerprint
Load key ... invalid formatSecret pasted without line breaksStore the full key including header and footer lines
refusing tag:Input does not match the script’s patternPass a tag like sha-1a2b3c4
This account is currently not availableShell is nologinGive the user a real shell such as /bin/bash
Job waits and never startsEnvironment approval pendingApprove it in the run page
Connection timed outFirewall blocks port 22 from the runnerAllow SSH from GitHub runners or use a self-hosted runner

Quick reference#

output
authorized_keys:
restrict,command="/usr/local/bin/deploy.sh" ssh-ed25519 AAAA... ci-deploy

keygen:      ssh-keygen -t ed25519 -f ./ci-deploy -C "ci-deploy" -N ""
fingerprint: ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
pin host:    ssh-keyscan -t ed25519 203.0.113.10
never:       StrictHostKeyChecking=no

For a full self-hosted walk-through, see the blog guide Deploy a Docker Compose app, self-hosted.

Next#

Continue with Secrets and variables in CI pipelines.

Check what you learned4 questions
1What does a command= option pointing at a deploy script do in an authorized_keys entry?
2How should the workflow trust the server's host key?
3Why use a separate user and key just for CI?
4What does a required reviewer on an environment do?

Frequently asked questions

How do I deploy to a server over SSH from GitHub Actions?

Create a key pair used only by CI, add the public key to a dedicated deploy user on the server, store the private key as a secret, and run ssh deploy@host in a workflow step. Pin the server host key rather than turning off host checking.

Is it safe to put an SSH private key in GitHub secrets?

It is acceptable when the key is used only for deploys, belongs to a user with minimal rights, and is restricted in authorized_keys to a single command. Treat it as rotatable and keep it out of logs.

Why not use StrictHostKeyChecking=no?

It accepts any host key, so an attacker who intercepts the connection can impersonate your server and receive your deploy. Pin the real host key in known_hosts instead.

What does the command option in authorized_keys do?

It forces sshd to run that one command whenever the key logs in, ignoring what the client asked to run. The client can only trigger your deploy script.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios