DevOps - CI/CD Part-5
DevOps - CI/CD Tutorial - Part 5
Understand pipeline architecture, security, and deployment with a real Java API and Docker CI example.
1What Is CI/CD?
In earlier parts we learned Docker and Kubernetes. Continuous Integration (CI) regularly builds and tests changes. Continuous Delivery keeps releases ready; Continuous Deployment can deploy successful changes automatically.
2Pipeline Architecture
This full diagram is a general architecture. The CI example below only builds and performs HTTP smoke tests; scanning, pushing, approval, and deployment must be configured separately.
Learning simulation: Viewing the stages does not run a pipeline or cluster.
3Developer Tools
- Git and GitHub: Manage changes, pull requests, and review.
- GitHub Actions, GitLab CI/CD, or Jenkins: Run jobs on runners or agents; security and configuration vary by platform.
- Maven or Gradle: Can manage dependencies, builds, and automated tests in a real Java project.
- Docker and a registry: Build images and share them through an authorized registry.
- Trivy, kubectl, and Helm: Help with security scanning, cluster operations, and Kubernetes packaging, respectively. Manage their installation and permissions separately.
4Real Example Prerequisites
- Use a GitHub repository you control with Actions enabled and a GitHub-hosted Ubuntu runner available. Check organization policies and possible usage charges first.
- Save the single YAML below as
.github/workflows/a143mk-ci.ymlin your repository and commit/push it to your branch. This is GitHub Actions' required workflow location, not a project-folder walkthrough. - Open the run in the Actions tab. For a manual run, the workflow must exist on the default branch and workflow dispatch must be allowed in the repository.
5Java API and Docker CI Workflow
This complete, self-contained workflow creates a small Java HTTP API and Dockerfile on the runner, builds an image, and checks real HTTP responses. It does not check out repository source or test your existing project.
name: A143MK Java Docker CI
on: [push, pull_request, workflow_dispatch]
permissions: {}
jobs:
build-and-test:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Create example application and Dockerfile
shell: bash
run: |
cat > HelloApi.java <<'JAVA'
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class HelloApi {
public static void main(String[] args) throws Exception {
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", exchange -> {
try (exchange) {
String path = exchange.getRequestURI().getPath();
int status;
String body;
if (!"GET".equals(exchange.getRequestMethod())) {
exchange.getResponseHeaders().set("Allow", "GET");
status = 405;
body = "{\"error\":\"Method not allowed\"}";
} else if ("/api/hello".equals(path)) {
status = 200;
body = "{\"message\":\"Hello from CI!\"}";
} else if ("/health".equals(path)) {
status = 200;
body = "{\"status\":\"UP\"}";
} else {
status = 404;
body = "{\"error\":\"Not found\"}";
}
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
exchange.sendResponseHeaders(status, bytes.length);
exchange.getResponseBody().write(bytes);
}
});
server.start();
System.out.println("Java API listening on port " + port);
}
}
JAVA
cat > Dockerfile <<'DOCKERFILE'
FROM eclipse-temurin:17-jdk
WORKDIR /app
COPY HelloApi.java /app/HelloApi.java
EXPOSE 8080
CMD ["java", "--add-modules", "jdk.httpserver", "/app/HelloApi.java"]
DOCKERFILE
- name: Build image
run: docker build -t a143mk-api:ci .
- name: Run HTTP smoke tests
shell: bash
run: |
set -euo pipefail
docker run -d --name a143mk-ci-api -p 127.0.0.1:18080:8080 a143mk-api:ci
trap 'docker rm -f a143mk-ci-api' EXIT
curl --fail --silent --show-error --retry 30 --retry-delay 1 --retry-connrefused \
http://localhost:18080/api/hello -o response.json
python3 -c 'import json; d=json.load(open("response.json")); assert d == {"message":"Hello from CI!"}, d'
curl --fail --silent --show-error http://localhost:18080/health -o health.json
python3 -c 'import json; d=json.load(open("health.json")); assert d == {"status":"UP"}, d'
echo "Java API smoke tests passed."
6Results and Tests
A push or pull request triggers the workflow; inspect the job and step logs in Actions. On success, the final step prints Java API smoke tests passed.
GET /api/hellomust return{"message":"Hello from CI!"}andGET /healthmust return{"status":"UP"}.- The smoke test checks only this small example's HTTP behavior. A real Java project also needs unit, integration, error, and security tests.
- The Docker image exists only on the job's runner. The workflow does not publish or deploy it anywhere.
7Adapt for Your Project
For an existing Maven project, you can use this separate GitHub Actions workflow. It requires a Java 17-compatible pom.xml at the repository root, appropriate tests, and Maven on a GitHub-hosted Ubuntu runner. It checks out repository code and runs verify; it does not build a Docker image or deploy.
Place this in your repository as a separate workflow YAML. This example uses readable version tags; for production, pin verified actions to full commit SHAs.
name: Java Maven CI
on: [push, pull_request, workflow_dispatch]
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Check out source
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Set up Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- name: Build and verify
run: mvn -B --no-transfer-progress verify
The actual effect of verify depends on your Maven plugins and tests; a successful build without configured tests is not proof of adequate testing. Keep pull-request and deployment workflows separate.
Further customization
- Instead of generating demo source, obtain the correct revision of your repository using a trusted checkout action or your organization's approved method. Pin actions to full commit SHAs and grant only required permissions.
- Use your actual Maven or Gradle project's build and test commands. Keep pull-request tests isolated from trusted credentials.
- Build an image containing the same build artifact from your Dockerfile and test actual endpoints and error cases. Configure dependency and image scanning for your project.
- Publish an image to a secure registry only for authorized releases; identify the tested image by digest and verify rollout and smoke tests after deployment.
Build caches can save time, but consider cache keys, untrusted inputs, and dependency updates. A cache is not a substitute for verification or security scans.
8Registry and Image Digest
A tag can move; a digest identifies specific image content. Establish registry permissions, credentials, retention, and image-signature policies first. The runnable workflow in this post does not push an image.
Image scanning and an SBOM are useful, but do not automatically guarantee security. Define policy, severity thresholds, and remediation processes.
9Kubernetes Deployment
In CD, a separate authorized job or GitOps controller can use a verified image digest in deployment configuration. The Part 3 source-ConfigMap demo does not automatically use this workflow's image.
This is an illustrative image reference; do not apply it until you supply a real registry, image, and full digest. Also adapt container command, port, probes, and permissions for the actual application.
containers:
- name: api
image: registry.example.com/team/api@sha256:REPLACE_WITH_REAL_DIGEST
ports:
- containerPort: 8080
- Before deployment, verify the cluster, namespace, change approval, and least-privilege RBAC; do not give production credentials to pull requests.
- Check rollout status and real health and smoke tests. Deployment rollback restores a previous Pod template, not the database or all external resources.
- If deploying directly from CI, configure runner connectivity and a short-lived identity separately; OIDC can help avoid long-lived credentials where supported.
10Pipeline Security
- Least privilege: This example uses
permissions: {}because it needs no repository token permissions. Add only the permissions your project requires. - Secrets: Do not put passwords or kubeconfig in YAML. Use an approved secret manager, rotation, and short-lived identity where available.
- Untrusted PRs: Do not run code from forks with secrets or on privileged runners. Carefully review combinations of privileged pull-request triggers and checkout.
- Supply chain: Choose trusted actions and base images, pin full action SHAs and image digests, and review updates.
- Logs and approvals: Do not log secrets; apply appropriate review and approvals to deployment environments.
11Troubleshooting and Checklist
- Workflow missing: Check YAML location, branch, trigger, Actions policy, and syntax. Check the default branch for manual runs.
- Image build fails: Check Docker on the runner, the base image name, registry/network access, and build logs.
- Smoke test fails: Check container startup, port mapping, HTTP status, and JSON response. A local port conflict or slow image pull may also be involved.
- Registry or deploy fails: Check authorization, identity, digest, cluster context, namespace, and rollout events. These steps are not included in this example.
No comments :
Post a Comment
Please Write a Message for Programming or something else 🙏