Skip to lesson

Automatic deploys from the main branch

A teammate merges a pull request with a failing test, and the platform deploys it within a minute. Customers see the bug before CI even turns red. How do you make deploys follow the tests?

Platform auto-deploy vs a deploy job

Continuous deployment means every change merged into main goes live on its own, but only after the pipeline has built, tested and packaged it. The deploy is one more job at the end of ci.yml.

Platform auto-deploy ships every push to main, even while CI is red. A deploy job calls the platform only after the tests pass, for example through a deploy hook:

YAML
# A platform deploy hook, called only after the tests pass- name: Trigger the platform deploy  env:    DEPLOY_HOOK_URL: ${{ secrets.DEPLOY_HOOK_URL }}  run: curl --fail --silent --show-error -X POST "$DEPLOY_HOOK_URL"

Example 1 · Which jobs run for which event

PipelineDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class PipelineDemo {    static List<String> jobs(String event, String branch, boolean testsPass) {        List<String> run = new ArrayList<>();        run.add("build-test");        if (!testsPass) {            run.add("(image and deploy skipped: build-test failed)");            return run;        }        if (event.equals("push") && branch.equals("main")) {            run.add("image");            run.add("deploy");        }        return run;    }
    public static void main(String[] args) {        System.out.println("PR from feature/cart:     " + jobs("pull_request", "feature/cart", true));        System.out.println("push to main, tests pass: " + jobs("push", "main", true));        System.out.println("push to main, tests fail: " + jobs("push", "main", false));        System.out.println("Platform auto-deploy on that failing push: deploys anyway");    }}
Output
PR from feature/cart:     [build-test]
push to main, tests pass: [build-test, image, deploy]
push to main, tests fail: [build-test, (image and deploy skipped: build-test failed)]
Platform auto-deploy on that failing push: deploys anyway

What this code does

  • The rules match needs: and if: in the workflow: pull requests only build and test; a push to main also builds the image and deploys, and a failure stops everything after it.
  • The last line is the reason to prefer a deploy job: a platform's auto-deploy watches the branch, not your test results.

Many platforms offer auto-deploy: connect the repository and every push to main deploys. It is easy, but the platform does not know whether your tests passed.

A deploy job in GitHub Actions tells the platform or the server what to run, through a deploy hook (a secret URL that starts a deploy when called), the platform's CLI (command-line tool), or ssh to your VM. If you use a deploy job, turn the platform's own auto-deploy off, or every push deploys twice.

The deploy job: needs, environment and secrets

An environment is a named GitHub deploy target, such as production, with its own environment secrets and protection rules. Only jobs that name the environment can read its secrets.

A deploy job waits for the build and the image, runs only on main, and names its environment. Here is the job in ci.yml:

The order of a safe automatic deploy. A pull request runs only build and test. A push to main runs five steps in order: build and test, build and push an image tagged with the commit SHA, optional approval, deploy that same tag, then a smoke test of the live URL. A red step stops every later step.

Example 2 · The deploy job in .github/workflows/ci.yml

Runs in: a GitHub repository with build-test and image jobs in ci.yml

YAML
# .github/workflows/ci.yml (the third job; build-test and image are above it)  deploy:    needs: [build-test, image]    if: github.event_name == 'push' && github.ref == 'refs/heads/main'    runs-on: ubuntu-latest    environment:      name: production      url: https://api.shoplite.example    concurrency:      group: production      cancel-in-progress: false    steps:      - name: Deploy the tested image to the VM        env:          SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}          KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}          DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}        run: |          install -m 700 -d ~/.ssh          printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519          chmod 600 ~/.ssh/id_ed25519          printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts          ssh "deploy@$DEPLOY_HOST" "/opt/shoplite/deploy.sh ${{ github.sha }}"      - name: Smoke test        run: |          curl --fail --silent --show-error --retry 10 --retry-delay 6 --retry-all-errors \            https://api.shoplite.example/actuator/health          curl --fail --silent --show-error https://api.shoplite.example/api
Sample output
deploy  Deploy the tested image to the VM
  [+] Pulling 1/1
   ✔ api Pulled
  [+] Running 2/2
   ✔ Container shoplite-api-1    Healthy
   ✔ Container shoplite-caddy-1  Running
  Deployed 3f9c2e1b7d4a5c6e8f90a1b2c3d4e5f6a7b8c9d0
deploy  Smoke test
  {"groups":["liveness","readiness"],"status":"UP"}
  {"name":"shoplite-api","version":"1.2.0"}

What this code does

  • Secrets reach the shell through env: and are written to files, never echoed; GitHub also masks them in the log. vars.DEPLOY_HOST is a plain configuration variable, because a host name is not secret.
  • deploy.sh on the VM writes the SHA into .env, pulls that image and waits until the container is healthy. The url: under environment shows as a link on the run page.

needs: [build-test, image] makes the deploy wait for both jobs and skip itself if either fails. An if: condition limits it to pushes on main, so pull requests build and test but never deploy.

environment: production unlocks the SSH key or deploy hook for this job only, so a workflow on a feature branch cannot read them. concurrency: production makes deploys run one at a time, never two at once on the same server.

Find the bug

Find the unsafe deploy line

Tap the line that lets a bad change reach production.

The deploy must wait for the tests.

Round 1 of 2

Deploy the exact image that passed the tests

A commit SHA tag is an image tag equal to the 40-character id of the commit that built it, such as shoplite-api:${{ github.sha }}. By convention nobody pushes a different image under it, so it always names the same bytes.

Tag every image with the commit SHA, and deploy that tag. The program shows what happens when a server pulls latest after a crash:

Example 3 · latest moves, a SHA tag does not

ImageTagDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class ImageTagDemo {    static Map<String, String> registry = new LinkedHashMap<>();
    static void push(String sha, String build) {        registry.put(sha, build);        registry.put("latest", build);    }
    public static void main(String[] args) {        push("3f9c2e1", "build A (tested, deployed)");        String deployedTag = "3f9c2e1";        String lazyTag = "latest";
        push("8b41d07", "build B (merged, waiting for approval)");
        System.out.println("Container crashes at night; the server pulls again:");        System.out.println("  with SHA tag: " + registry.get(deployedTag));        System.out.println("  with latest:  " + registry.get(lazyTag));        System.out.println("Roll back to the previous version:");        System.out.println("  with SHA tags: deploy 3f9c2e1 again");        System.out.println("  with latest:  no name for the previous image");    }}
Output
Container crashes at night; the server pulls again:
  with SHA tag: build A (tested, deployed)
  with latest:  build B (merged, waiting for approval)
Roll back to the previous version:
  with SHA tags: deploy 3f9c2e1 again
  with latest:  no name for the previous image

What this code does

  • Each push adds a SHA tag and moves latest. A server that asked for latest silently gets build B after a restart, even though nobody approved B for production.
  • SHA tags make every version addressable, which is what makes deploys repeatable and rollbacks one command. Real tags hold all 40 characters; 7 are shown here to keep the output short.

The CI module's docker/metadata-action used type=sha, which gives a short tag such as sha-3f9c2e1. Add type=sha,format=long,prefix= so one tag is exactly ${{ github.sha }}, the value the deploy job knows.

latest is a moving label that points at whatever was pushed last. A server that pulls it after a crash may silently start a never-deployed version, two servers can run different code under one name, and "go back" has no name to go back to. Keep latest for people who want to try the app, never for deploys.

Predict the output

Which build runs after a restart?

Build B was pushed to the registry, but its deploy was never approved.

Round 1 of 2

Which build runs after the crash?

Push A -> tags sha-aaa, latest
Push B -> tags sha-bbb, latest (moves to B)
The server runs A, then crashes and restarts.
Its config says: image: shoplite-api:latest

A post-deploy smoke test with retries

A smoke test is a quick check, run right after a deploy, that the live app answers: health is UP and one real endpoint works. It does not replace the test suite; it catches what only production can break.

The new container needs some seconds to start, so the first calls may fail. Retry the health call for about a minute:

YAML
- name: Smoke test  run: |    curl --fail --silent --show-error --retry 10 --retry-delay 6 --retry-all-errors \      https://api.shoplite.example/actuator/health    curl --fail --silent --show-error https://api.shoplite.example/api

Example 4 · A smoke test that waits for the app to start

SmokeTestDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.concurrent.atomic.AtomicInteger;
public class SmokeTestDemo {    public static void main(String[] args) throws Exception {        // A stand-in for the new container: "starting" (503) for the first two calls        AtomicInteger calls = new AtomicInteger();        HttpServer app = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        app.createContext("/actuator/health", exchange -> {            boolean ready = calls.incrementAndGet() > 2;            byte[] body = (ready ? "{\"status\":\"UP\"}" : "{\"status\":\"DOWN\"}").getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(ready ? 200 : 503, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        app.start();
        URI health = URI.create("http://127.0.0.1:" + app.getAddress().getPort() + "/actuator/health");        HttpClient client = HttpClient.newHttpClient();        boolean passed = false;        for (int attempt = 1; attempt <= 5 && !passed; attempt++) {            try {                HttpResponse<String> r = client.send(HttpRequest.newBuilder(health).build(),                        HttpResponse.BodyHandlers.ofString());                System.out.println("attempt " + attempt + ": " + r.statusCode() + " " + r.body());                passed = r.statusCode() == 200;            } catch (IOException e) {                System.out.println("attempt " + attempt + ": no answer yet");            }            if (!passed) {                Thread.sleep(200);            // --retry-delay 6 in the real workflow            }        }        System.out.println(passed ? "Smoke test passed" : "Smoke test FAILED: the run turns red");        app.stop(0);    }}
Output
attempt 1: 503 {"status":"DOWN"}
attempt 2: 503 {"status":"DOWN"}
attempt 3: 200 {"status":"UP"}
Smoke test passed

What this code does

  • The small server answers 503 while "starting" and 200 afterwards, like a Spring Boot container whose health is DOWN until the database pool is ready.
  • The loop does what curl --fail --retry does: a non-200 answer counts as a failure, it waits and tries again, and it gives up after a fixed number of attempts.

A smoke test catches a missing environment variable or a wrong port. curl --fail --retry 10 --retry-delay 6 --retry-all-errors retries for about a minute: --fail turns HTTP errors such as 503 into a failed command, and --retry-all-errors also retries refused connections.

If the app is still not healthy after the retries, the step fails, the run turns red and you get an email.

Manual approval with protection rules

Continuous delivery keeps every green change ready to release, but a person presses the button. In GitHub you add that step with required reviewers on the production environment.

Continuous delivery keeps a release ready but lets a person press the button. In GitHub you add the button without changing the workflow:

Example 5 · Required reviewers on the production environment

Runs in: GitHub: Settings → Environments → production

Text
Environment: production  Required reviewers:   asha-rao, ravi-kumar   (one approval is enough)  Prevent self-review:  on  Wait timer:           0 minutes  Deployment branches:  Selected branches and tags → main  Environment secrets:  DEPLOY_SSH_KEY, DEPLOY_KNOWN_HOSTS  Environment variables: DEPLOY_HOST
Sample output
CI #57: Merge pull request #31 from asha-rao/feature/order-history
  ✓ build-test   3m 12s
  ✓ image        1m 48s
  ⏸ deploy       Waiting for review: production needs approval to start deploying changes.

ravi-kumar approved and deployed to production (comment: "Checked the changelog")
  ✓ deploy       1m 05s   https://api.shoplite.example

What this code does

  • The workflow file does not change: naming environment: production is enough for GitHub to apply these rules to the deploy job.
  • Deployment branches stop a workflow on any other branch from using the production secrets, and "prevent self-review" makes a second person look at every release.

Open Settings → Environments → production and add required reviewers. The deploy job then pauses with "waiting for review" until a reviewer approves it; the image and tests are already done.

The same page has more protection rules: a wait timer (wait N minutes before deploying), deployment branches (only main may deploy to production) and the environment's secrets. Environments work for public repositories on free plans; some rules in private repositories need a paid plan, so check GitHub's current docs.

Order of execution

The safe deploy order

Put one push to main in the order the pipeline runs it.

Next step

Check your understanding

11 quick questions