Sub topic 13
Automating build, test, and release in CI/CD
This chapter assumes you can build a Spring Boot application with Maven or Gradle and that you know what an executable JAR and a container image are. It also assumes you have used Git and can read a YAML file. You will see how a pipeline turns a commit into a tested, versioned artifact that is ready to deploy.
What a pipeline does
CI/CD stands for continuous integration and continuous delivery. Continuous integration means every change is built and tested automatically. Continuous delivery means every change that passes ends up as an artifact you could deploy. Deployment itself may be automatic (continuous deployment) or wait for a person to approve it.
The goal is that the artifact you test is the artifact you ship. You build it once, test it, publish it with a unique version, and promote that same artifact through environments. Environment differences come from externalized configuration, not from rebuilding.
A typical pipeline has these stages:
- Check out the code.
- Build and run unit tests.
- Run integration tests and static checks.
- Package the executable JAR.
- Build and publish a container image.
- Deploy to a test environment, then to production.
Build and test stages
Run the build with the wrapper script (mvnw or gradlew) that is committed to the repository. The wrapper pins the build tool version, so the CI server and your laptop use the same one. The JDK version should also be pinned in the pipeline, and it should match the one in your container base image.
For Maven, the verify phase compiles, runs unit tests, packages the JAR, and runs integration tests bound to later phases. For Gradle, build does the equivalent.
# Maven
./mvnw --batch-mode verify
# Gradle
./gradlew build --no-daemonThe --batch-mode flag removes interactive output and download progress lines. The --no-daemon flag avoids leaving a long-lived Gradle process on a build agent that is thrown away anyway.
Keeping tests reliable
Tests in CI fail for reasons that never show up on your machine. Watch for these:
- Tests that depend on a fixed port. Use
@SpringBootTest(webEnvironment = RANDOM_PORT)so parallel jobs do not collide. - Tests that need a real database. Use Testcontainers, which starts a throwaway Docker container from inside the test. The CI agent then needs access to a Docker daemon.
- Tests that depend on the clock, locale, or time zone. Fix these in the test, or set them in the pipeline.
- Tests that depend on the order of other tests. Run them in a random order occasionally to find the problem.
Caching dependencies
Downloading dependencies on every run is slow. Most CI systems can cache the Maven repository (~/.m2/repository) or the Gradle cache (~/.gradle/caches). Key the cache on a hash of pom.xml or the *.gradle files, so the cache is rebuilt when dependencies change. A cache is an optimization only. The build must still succeed with an empty cache.
A complete example pipeline
The following GitHub Actions workflow builds and tests on every push and pull request. On a version tag, it also builds and publishes a container image. The same stages map to GitLab CI, Jenkins, and other tools with different syntax.
name: ci
on:
pull_request:
push:
branches: [main]
tags: ["v*"]
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
cache: maven
- name: Build and test
run: ./mvnw --batch-mode verify
- name: Upload JAR
uses: actions/upload-artifact@v4
with:
name: app-jar
path: target/*.jar
image:
needs: build
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:${{ github.ref_name }}
ghcr.io/${{ github.repository }}:${{ github.sha }}Several details in this file matter:
permissionsgrants the workflow token only what it needs. Everything else is denied.needs: buildmeans the image job runs only if build and tests passed.- The
ifcondition limits image publishing to version tags, so pull requests never publish anything. - The
imagejob'sdocker buildexpects the JAR attarget/myapp-1.0.0.jaras in the Dockerfile from the container chapter. If your Dockerfile copies a built JAR, the image job must either rebuild it or download the artifact from the first job. A multi-stage Dockerfile that builds the JAR itself avoids this problem. - The image gets two tags, the release name and the commit SHA, so you can trace any running image back to a commit.
Versioning and artifact identity
A deployment is only reproducible if you can say exactly what is running. Use these rules:
- Give each release a unique, immutable version. Do not reuse a tag after publishing.
- Avoid deploying the
latesttag. It points to different images at different times, so two servers can run different code under the same name. - Record the commit SHA in the artifact. The Spring Boot plugin can generate
META-INF/build-info.properties, and the Actuatorinfoendpoint then shows the version and build time.
With Maven, add the build-info goal to the plugin configuration:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>With Gradle, use springBoot { buildInfo() }.
Secrets in the pipeline
The pipeline needs credentials, for example to push to a registry. Store them in the CI system's secret store and read them as masked variables. Never write them in the repository or in the Dockerfile, because image layers keep them. Prefer short-lived credentials where the platform supports them, such as OpenID Connect tokens exchanged for cloud access, over long-lived keys.
Application secrets, like DB_PASSWORD, do not belong in the pipeline's build step at all. The artifact reads them at run time, as described in the earlier chapters on configuration and secrets.
Releasing and deploying
Once an image is published, deployment means telling the target environment to run that version. Common approaches are:
| Approach | How it works | Trade-off |
|---|---|---|
| Push from the pipeline | A pipeline step runs `kubectl set image` or `helm upgrade` | Simple, but the CI system needs cluster credentials |
| GitOps | The pipeline commits the new version to a config repository, and an in-cluster tool applies it | Cluster credentials stay inside the cluster, and Git records every change |
| Manual promotion | A person triggers the production job after checking staging | Slower, but gives a human gate |
After a deploy step, the pipeline should verify the result. For Kubernetes, kubectl rollout status deployment/myapp --timeout=120s waits until the new pods pass their readiness probes, and it fails the job if they do not. Because the application has health probes and graceful shutdown, a failed rollout leaves the old pods serving traffic. You can then roll back with kubectl rollout undo.
Common errors
- The pipeline works locally but fails in CI. The JDK version, time zone, or available services differ. Pin versions and make test dependencies explicit.
- Tests pass, but the deployed app fails at start-up. Tests ran with a test profile, so a missing production property was never exercised. The smoke test and the rollout check catch this.
- Different builds for staging and production. Rebuilding per environment means the production artifact was never tested. Build once and change only configuration.
- A published image cannot be traced to code. Tag with the commit SHA and expose build info.
- Secrets appear in logs. Do not echo environment variables in scripts, and use the CI system's masking.
Exercise
Your pipeline builds the JAR, runs tests, and then a later job runs ./mvnw package again to build the container image for production. Name two problems with this, and describe the fix.
Show answer
First, the second build is a different artifact from the one that was tested, so a changed dependency or a flaky build step can put untested code in production. Second, it wastes time and makes the image hard to trace to the tested build. The fix is to build once, pass the JAR to the image job as a pipeline artifact (or use a multi-stage Dockerfile in one controlled build), tag the image with the version and commit SHA, and promote that same image through environments.
Exercise
Why does the example workflow restrict the image job with if: startsWith(github.ref, 'refs/tags/v') and needs: build?
Show answer
The if condition means only tagged releases publish an image, so pull requests and ordinary commits cannot push to the registry. The needs: build line means the image is built only after the build and test job succeeds, so a failing test blocks publishing.