# 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.

URL: https://levelrail.com/learn/ci-cd/deploy-over-ssh-from-github-actions/
Updated: 2026-11-27

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](https://levelrail.com/learn/git/ssh-keys-and-deploy-keys-for-git/)) lesson as background. The concepts behind [SSH](https://levelrail.com/learn/glossary/#ssh)) and [SSH keys](https://levelrail.com/learn/glossary/#ssh-key)) 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](https://levelrail.com/learn/linux/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):

```text
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](https://levelrail.com/learn/deploy-operate/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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `Permission denied (publickey)` | Wrong key, bad permissions or user | Check `authorized_keys` mode 600 and the key text. See the troubleshooting lesson |
| `Host key verification failed` | known_hosts missing or server key changed | Re-pin after verifying the fingerprint |
| `Load key ... invalid format` | Secret pasted without line breaks | Store the full key including header and footer lines |
| `refusing tag:` | Input does not match the script's pattern | Pass a tag like `sha-1a2b3c4` |
| `This account is currently not available` | Shell is nologin | Give the user a real shell such as /bin/bash |
| Job waits and never starts | Environment approval pending | Approve it in the run page |
| `Connection timed out` | Firewall blocks port 22 from the runner | Allow SSH from GitHub runners or use a self-hosted runner |

## Quick reference

```text
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
```

## Related lessons

- [SSH keys and deploy keys for Git](https://levelrail.com/learn/git/ssh-keys-and-deploy-keys-for-git/)): key basics and deploy keys on the Git side.
- [Fix SSH permission denied (publickey)](https://levelrail.com/learn/troubleshooting/fix-ssh-permission-denied-publickey/)): when the login fails.
- [Secrets and variables in CI pipelines](https://levelrail.com/learn/ci-cd/secrets-and-variables-in-ci-pipelines/)): where the private key is stored and how it is scoped.
- [Create a sudo user](https://levelrail.com/learn/server-basics/create-a-sudo-user/)): users and rights on the server.
- [Deploy an app with Docker Compose](https://levelrail.com/learn/deploy-operate/deploy-an-app-with-docker-compose/)): what the script runs.

For a full self-hosted walk-through, see the blog guide [Deploy a Docker Compose app, self-hosted](https://levelrail.com/blog/deploy-docker-compose-app-self-hosted/)).

## Next

Continue with [Secrets and variables in CI pipelines](https://levelrail.com/learn/ci-cd/secrets-and-variables-in-ci-pipelines/)).

## 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

- [man7, sshd(8) authorized_keys file format](https://man7.org/linux/man-pages/man8/sshd.8.html)
- [GitHub Docs, using secrets in GitHub Actions](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions)
- [GitHub Docs, managing environments for deployment](https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-deployments/managing-environments-for-deployment)
