Ravindra BagaleCourses & study guides मराठी

Chapter 9: GitHub Actions Hands-On

DevOps

9.7 Deploy sketch — SSH to one lab VM

Why: the problem

Suppose we are at a small Pune startup that sells tiffin plans. The app runs on one EC2 server. Every release, the developer logs in with SSH, runs git pull, and restarts the app. One day he pulls the wrong branch. Another day he forgets the restart. Releases depend on one person and his laptop. The fix: let CI do the same SSH steps after tests pass, with a dedicated deploy key, a known host fingerprint, and a health check at the end.

What we will build

You will deploy to one lab VM over SSH from a workflow. First a plain shell deploy of a Node.js app with systemd, then a Docker image pull and restart, then a Python app with a health check and automatic rollback to the previous release folder.

What: every term in plain English

  • SSH — Secure Shell. A safe way to run commands on a remote server.
  • Deploy key — An SSH key pair made only for CI. The public half sits on the server; the private half is a secret.
  • known_hosts — A file of trusted server fingerprints. It stops fake servers (man-in-the-middle).
  • ssh-keyscan — Prints a server fingerprint so you can save it.
  • systemd — The Linux service manager. systemctl restart starts the new code.
  • Health check — A URL like /health that proves the app works after deploy.
  • Rollback — Going back to the last good release.
  • Release folder — A folder per version, like /srv/app/releases/a3f2c1d, with a current link to the live one.
Make a deploy key on your laptop Put the public key on the server for a deploy user Save the server fingerprint Store the private key as a secret Push to main and watch the deploy job
SSH deploy: tests pass, write key and known_hosts, ssh, switch release, health check, rollback if red

How: step by step

  1. Make a deploy key on your laptop

    ssh-keygen -t ed25519 -f deploy_key -N "" -C "ci-deploy"
    

    What it does: Two files: deploy_key (private) and deploy_key.pub.

    Output

    Your identification has been saved in deploy_key
    
  2. Put the public key on the server for a deploy user

    ssh ec2-user@203.0.113.10 "sudo useradd -m deploy; sudo mkdir -p /home/deploy/.ssh" && cat deploy_key.pub | ssh ec2-user@203.0.113.10 "sudo tee -a /home/deploy/.ssh/authorized_keys"
    

    What it does: A separate user with only deploy rights.

    Output

    ssh-ed25519 AAAAC3Nza... ci-deploy
    
  3. Save the server fingerprint

    ssh-keyscan -t ed25519 203.0.113.10
    

    What it does: Copy the output into a secret named DEPLOY_KNOWN_HOSTS.

    Output

    203.0.113.10 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...
    
  4. Store the private key as a secret

    gh secret set DEPLOY_SSH_KEY --body "$(cat deploy_key)"
    

    What it does: Then delete deploy_key from your laptop.

    Output

    ✓ Set Actions secret DEPLOY_SSH_KEY
    
  5. Push to main and watch the deploy job

    git push origin main
    

    What it does: Deploy runs after tests.

    Output

    deploy  Success  31s
    

Example 1: Node

Stack. Node.js, systemd, SSH

Goal. Node.js app with systemd: SSH, pull, install, restart.

.github/workflows/deploy.yml

name: deploy
on:
  push:
    branches: [main]
concurrency: deploy-prod
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci && npm test
  deploy:
    needs: test
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Set up SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519
          echo "${{ secrets.DEPLOY_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
          ssh-keygen -y -f ~/.ssh/id_ed25519 > /dev/null
      - name: Deploy
        run: |
          ssh deploy@203.0.113.10 "cd /srv/tiffin && git fetch --all && git reset --hard ${{ github.sha }} && npm ci --omit=dev && sudo systemctl restart tiffin"
      - name: Health check
        run: curl -fsS --retry 5 --retry-delay 3 http://203.0.113.10/health

What each line does

  • concurrency: deploy-prod — Only one deploy at a time; a second waits.
  • echo secret > ~/.ssh/id_ed25519 — Writes the private key on the throwaway runner only.
  • known_hosts from a secret — SSH refuses unknown servers. No StrictHostKeyChecking=no.
  • git reset --hard SHA — Deploy exactly the tested commit, not whatever main is now.
  • npm ci --omit=dev — Production packages only.
  • curl -fsS --retry 5 — Fail the job if the app does not answer.

Green output

Run ssh deploy@203.0.113.10 "cd /srv/tiffin && ..."
HEAD is now at a3f2c1d Add weekly plan
added 87 packages in 4s
Run curl -fsS --retry 5 --retry-delay 3 http://203.0.113.10/health
{"status":"ok","version":"a3f2c1d"}

Expected result. The live app reports the new commit id. No human logged in.

Example 2: Docker on the VM: pull the new image tag and restart

Stack. Docker, SSH

Goal. Docker on the VM: pull the new image tag and restart.

Deploy step

- name: Deploy container
  run: |
    ssh deploy@203.0.113.10 "
      docker pull registry.example.com/tiffin/api:${{ github.sha }} &&
      docker rm -f api || true &&
      docker run -d --name api --restart unless-stopped -p 80:8000 \
        --env-file /etc/tiffin/api.env \
        registry.example.com/tiffin/api:${{ github.sha }}
    "

What each line does

  • docker pull ...:SHA — Pull the image CI just built.
  • docker rm -f api || true — Remove the old container; ignore if none.
  • --restart unless-stopped — Comes back after a server reboot.
  • --env-file /etc/tiffin/api.env — Settings live on the server, not in the image.

Green output

Status: Downloaded newer image for registry.example.com/tiffin/api:a3f2c1d...
api
5e7a1c9d2b3f...

Expected result. The server runs exactly the image that passed CI.

Example 3: Python app with release folders and automatic rollback

Stack. Python, Gunicorn, systemd

Goal. Python app with release folders and automatic rollback.

scripts/remote_deploy.sh

#!/usr/bin/env bash
set -euo pipefail
SHA="$1"
BASE=/srv/menu
NEW="$BASE/releases/$SHA"
PREV=$(readlink -f "$BASE/current" || true)
mkdir -p "$NEW"
tar xzf "/tmp/menu-$SHA.tgz" -C "$NEW"
python3 -m venv "$NEW/venv"
"$NEW/venv/bin/pip" install -q -r "$NEW/requirements.txt"
ln -sfn "$NEW" "$BASE/current"
sudo systemctl restart menu
sleep 3
if ! curl -fsS http://127.0.0.1:8000/health; then
  echo "Health failed, rolling back to $PREV"
  ln -sfn "$PREV" "$BASE/current"
  sudo systemctl restart menu
  exit 1
fi

Workflow steps

- run: tar czf menu-${{ github.sha }}.tgz app requirements.txt
- run: scp menu-${{ github.sha }}.tgz scripts/remote_deploy.sh deploy@203.0.113.10:/tmp/
- run: ssh deploy@203.0.113.10 "bash /tmp/remote_deploy.sh ${{ github.sha }}"

What each line does

  • PREV=$(readlink -f current) — Remember the live release before switching.
  • releases/$SHA — Each version has its own folder.
  • ln -sfn NEW current — Switch the live link in one fast step.
  • if ! curl ... /health — If the new app is not healthy, switch back.
  • exit 1 — Make the CI job red so people notice.

Green output

{"status":"ok"}
Deploy of 7c1e9a2 is live.
--- a bad release ---
curl: (7) Failed to connect to 127.0.0.1 port 8000
Health failed, rolling back to /srv/menu/releases/a3f2c1d
Error: Process completed with exit code 1.

Expected result. A bad release rolls back by itself in seconds, and CI shows red.

Verify: did it work?

  1. Check the live version

    curl -s http://203.0.113.10/health
    

    What it does: The version should match the commit you pushed.

    Output

    {"status":"ok","version":"a3f2c1d"}
    
  2. Check the service on the VM

    ssh deploy@203.0.113.10 "systemctl status tiffin --no-pager | head -3"
    

    What it does: Active (running) is good.

    Output

    ● tiffin.service - Tiffin API
       Active: active (running) since Sun 2026-10-25 09:41:12 IST
    

When it is red 1

Host key verification failed.

Cause. known_hosts is empty or the server was rebuilt and has a new fingerprint.

Fix, step by step

  1. Run ssh-keyscan again and check the fingerprint with the cloud console.
  2. Update the DEPLOY_KNOWN_HOSTS secret.

When it is red 2

deploy@203.0.113.10: Permission denied (publickey).

Cause. The public key is not in authorized_keys, or the secret has the wrong private key.

Fix, step by step

  1. Check the server file has the ci-deploy key.
  2. Re-save the secret including the BEGIN and END lines.

When it is red 3

Load key "/home/runner/.ssh/id_ed25519": bad permissions

Cause. SSH requires the private key file to be readable only by its owner.

Fix, step by step

  1. Before writing the key, run umask 077 in the same step.
  2. Then write the file with echo as shown.

Cleanup

  1. Remove old release folders

    ssh deploy@203.0.113.10 "ls -1dt /srv/menu/releases/* | tail -n +6 | xargs rm -rf"
    

    What it does: Keep the last five releases.

    Output

    (no output)
    

Ravindra Bagale's Tip

If there is no health check after deploy, the deploy is not complete. Keep a rollback plan ready before you start!

Practice tasks

Easy Health endpoint

Why: Proof of life.

What to do: Add /health that returns the version.

How:
  1. Read the version from an env var.

Check: curl shows the version.

Medium Deploy with concurrency

Why: No clashes.

What to do: Add concurrency to the deploy job.

How:
  1. Push twice fast.

Check: The second deploy waits.

Hard Rollback

Why: Safe releases.

What to do: Use release folders and auto rollback.

How:
  1. Break /health on purpose.

Check: The old release is live again.

Easy Say SSH deploy from CI in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about SSH deploy from CI for a fresher who knows only Linux and Git basics.

How:
  1. Write the problem it solves.
  2. Write the one workflow line or command you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Make a throwaway practice repo

Why: Practice needs a repo you can break. If the workflow history gets messy, you delete the repo and start again.

What to do: Create a new empty repo named actions-lab with one small app and push it.

How:
  1. mkdir actions-lab && cd actions-lab && git init -b main
  2. Add app code and a test file.
  3. git remote add origin https://git.example.com/ravi/actions-lab.git && git push -u origin main

Check: The Actions tab of the repo shows your first run.

Medium Do it on a second stack

Why: A CI idea must work for Node.js, Python and Java. Only the setup and test lines should change.

What to do: Repeat this lesson with a different language than the one you used first.

How:
  1. If you used Python, use Node.js now.
  2. Change only the setup action and the test command.
  3. Keep the same job names.

Check: Same result, and the job names did not change.

Medium Break it on purpose

Why: You must know the red log by face. In a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers YAML keys. A short page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when to use, exact YAML or commands, how to check, how to undo.

Check: A teammate can follow it alone.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the workflow lines you wrote, and one error you hit.

Check: Your answer has a real YAML line and a real error message.

Hard Draw the flow top to bottom

Why: A drawing shows the order of work and which job waits for which.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at git push, go through each job and step, end at the green check or the deployed app.

Check: Each box matches a real step in your run log.

Homework: try at home

Try at home

At home, make a free-tier VM, create a deploy user and key, and deploy a small app from CI with a health check. Then push a broken build and watch the rollback.

Recap

  • CI can do your SSH deploy steps, the same way every time.
  • Use a deploy user, a deploy key and known_hosts.
  • Ship the exact tested commit or image tag.
  • Always finish with a health check.
  • Keep release folders for fast rollback.

FAQ

Is SSH deploy old-fashioned?

It is fine for one or two servers. For many, use Ansible, ECS or Kubernetes.

Can I avoid opening SSH to the world?

Use a self-hosted runner inside the network or AWS SSM instead of SSH.

Should the deploy user have full sudo?

No. Allow only systemctl restart for the app.

What about database migrations?

Run them as a separate step before the restart, and make them backward compatible.

Why not StrictHostKeyChecking=no?

It turns off the protection against fake servers.

Interview questions

  1. How do you deploy to a VM from CI securely?

    Deploy user, deploy key in secrets, pinned known_hosts, limited sudo, health check, environment approval.

  2. How do you roll back on a VM?

    Release folders with a current symlink; switch back and restart.

  3. How do you prevent parallel deploys?

    The concurrency key.

  4. How do you make sure the tested code is deployed?

    Deploy by commit SHA or image tag, not branch name.

  5. Alternative to SSH?

    AWS SSM Run Command, Ansible from CI, or a pull-based agent.

Quick quiz

Q1. Why a separate deploy key?

So it can be removed without touching personal keys.

Q2. Why known_hosts?

To make sure CI talks to the real server.

Q3. Why deploy github.sha and not main?

To ship exactly the tested commit.

Q4. What does concurrency do?

Stops two deploys at the same time.

Q5. How does the rollback know the old version?

It saves the current link target before switching.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards