DevOps for Data Engineering
Shipping data pipelines like software: automated tests, CI/CD with Jenkins and GitLab, infrastructure as code with Terraform, and containers with Docker and Kubernetes.
1. Why Data Teams Need DevOps
Pipelines are software. Without DevOps practices, changes are deployed by hand, broken SQL reaches production, environments drift apart, and nobody can rebuild the platform after an incident. DevOps for data adds:
| Practice | What it gives a data team |
|---|---|
| Version control (Git) | Every change reviewed, traceable and reversible |
| Continuous integration | Lint, unit tests and data tests on every pull request |
| Continuous delivery | The same tested artefact promoted dev → test → prod automatically |
| Infrastructure as code | Buckets, clusters, permissions and jobs recreated identically from code |
| Containers | The same runtime on a laptop, in CI and in production |
| Observability | Alerts on failures, duration, freshness and quality |
developer --push--> Git (pull request)
| CI: lint -> unit tests -> dbt build on CI schema -> data tests -> image build
v
merge to main --> CD: deploy to TEST (terraform + jobs) --> checks --> approval --> PROD
|
monitoring + rollback (previous image / table version)
Data adds problems application CI does not have: tests need representative data, changes can break downstream consumers, and a bad deploy can corrupt tables, so rollback means code and data (time travel, backups).
2. CI/CD Pipelines and Testing Data Code
| Test type | Checks | Tools |
|---|---|---|
| Lint / format | Style and obvious errors in Python and SQL | ruff, black, sqlfluff |
| Unit tests | Transformation logic on small, hand-made inputs | pytest (with a local SparkSession for PySpark) |
| Data tests | Uniqueness, nulls, relationships, accepted values on real tables | dbt tests, Great Expectations, Soda |
| Contract tests | Schemas and types consumers depend on did not break | dbt contracts, schema registry compatibility |
| Integration tests | The pipeline end to end on a CI environment | Ephemeral schemas, Databricks Asset Bundles, test workspaces |
Unit-testing a transformation with pytest
# src/transforms.py
def clean_orders(rows):
"""Drop rows without an id, normalise status, convert amounts, remove duplicate ids (keep last)."""
out = {}
for r in rows:
if not r.get("order_id"):
continue
out[r["order_id"]] = {
"order_id": r["order_id"],
"status": (r.get("status") or "UNKNOWN").strip().upper(),
"amount": round(float(r.get("amount") or 0), 2),
}
return list(out.values())
# tests/test_transforms.py
import pytest
from transforms import clean_orders
def test_drops_rows_without_id():
assert clean_orders([{"order_id": None, "amount": 5}]) == []
def test_normalises_status_and_amount():
[row] = clean_orders([{"order_id": 1, "status": " delivered ", "amount": "10.456"}])
assert row == {"order_id": 1, "status": "DELIVERED", "amount": 10.46}
def test_keeps_last_duplicate():
rows = [{"order_id": 1, "status": "new", "amount": 5}, {"order_id": 1, "status": "shipped", "amount": 5}]
assert [r["status"] for r in clean_orders(rows)] == ["SHIPPED"]
@pytest.mark.parametrize("raw, expected", [(None, 0.0), ("", 0.0), ("3", 3.0)])
def test_missing_amounts_become_zero(raw, expected):
assert clean_orders([{"order_id": 9, "amount": raw}])[0]["amount"] == expected
6 passed in 0.02s
Keep business logic in plain functions (or DataFrame-in, DataFrame-out functions for Spark) so it can be tested without a cluster. The same tests run on a laptop and in CI.
Slim CI for dbt
Building every model on every pull request is slow and expensive. dbt's state comparison builds only models changed in the pull request plus everything downstream, deferring unchanged upstream models to production: dbt build --select state:modified+ --defer --state prod-artifacts/.
3. Jenkins and GitLab CI
GitLab CI: pipeline as YAML in the repository
stages: [lint, test, build, deploy]
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache"
lint:
stage: lint
image: python:3.12-slim
script:
- pip install ruff sqlfluff
- ruff check src tests
- sqlfluff lint models --dialect databricks
unit-tests:
stage: test
image: python:3.12-slim
script:
- pip install -r requirements.txt pytest
- pytest -q --junitxml=report.xml
artifacts:
reports:
junit: report.xml
dbt-ci:
stage: test
image: ghcr.io/dbt-labs/dbt-databricks:1.9.latest
script:
- dbt deps
- dbt build --target ci --select state:modified+ --defer --state prod-artifacts/
build-image:
stage: build
image: docker:27
services: [docker:27-dind]
script:
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
deploy-prod:
stage: deploy
image: hashicorp/terraform:1.10
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
script:
- terraform -chdir=infra init
- terraform -chdir=infra apply -auto-approve -var "image_tag=$CI_COMMIT_SHORT_SHA"
GitLab CI: 5 jobs in stages ['lint', 'test', 'build', 'deploy']; every job uses a declared stage
Jenkins: declarative pipeline (Jenkinsfile)
pipeline {
agent { docker { image 'python:3.12-slim' } }
environment { DATABRICKS_TOKEN = credentials('databricks-token') } // from the Jenkins credential store
options { timeout(time: 30, unit: 'MINUTES') }
stages {
stage('Install') { steps { sh 'pip install -r requirements.txt pytest ruff' } }
stage('Lint') { steps { sh 'ruff check src tests' } }
stage('Test') { steps { sh 'pytest -q --junitxml=report.xml' } }
stage('Deploy to test') {
steps { sh 'databricks bundle deploy --target test' }
}
stage('Deploy to prod') {
when { branch 'main' }
input { message 'Deploy to production?' }
steps { sh 'databricks bundle deploy --target prod' }
}
}
post {
always { junit 'report.xml' }
failure { echo 'Notify the team channel here' }
}
}
Jenkinsfile: follows the official syntax but was not executed here, because it needs a live cloud account or service.
| Jenkins | GitLab CI | GitHub Actions | |
|---|---|---|---|
| Hosting | Self-hosted server and agents | Built into GitLab (SaaS or self-hosted) | Built into GitHub |
| Definition | Jenkinsfile (Groovy) | .gitlab-ci.yml | .github/workflows/*.yml |
| Strengths | Huge plugin ecosystem, full control | Integrated with repo, registry and environments | Marketplace of actions, simple setup |
| Watch out for | Plugin and server maintenance | Runner capacity and costs | Secrets and third-party action trust |
Deep dive: the Jenkins guide covers this in more depth.
4. Infrastructure as Code with Terraform
Terraform describes infrastructure in declarative HCL files. terraform plan shows exactly what will change; terraform apply makes it so. A state file maps code to real resources, so store it remotely with locking (for example an S3 backend with lock files, or Terraform Cloud).
terraform {
required_version = ">= 1.10" # S3 native state locking (use_lockfile)
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
backend "s3" {
bucket = "acme-tf-state"
key = "data-platform/prod.tfstate"
region = "ap-south-1"
use_lockfile = true
}
}
variable "env" { type = string }
resource "aws_s3_bucket" "lake" {
bucket = "acme-lake-${var.env}"
}
resource "aws_s3_bucket_lifecycle_configuration" "lake" {
bucket = aws_s3_bucket.lake.id
rule {
id = "landing-to-ia"
status = "Enabled"
filter { prefix = "landing/" }
transition {
days = 30
storage_class = "STANDARD_IA"
}
expiration {
days = 365
}
}
}
resource "aws_glue_job" "orders_silver" {
name = "orders-silver-${var.env}"
role_arn = aws_iam_role.glue.arn
command {
script_location = "s3://${aws_s3_bucket.lake.bucket}/code/orders_silver.py"
python_version = "3"
}
glue_version = "5.0"
worker_type = "G.1X"
number_of_workers = 5
}
terraform init terraform plan -var env=prod -out plan.tfplan # review the diff in the pull request terraform apply plan.tfplan # apply exactly what was reviewed
Terraform configuration: follows the official syntax but was not executed here, because it needs a live cloud account or service.
| Practice | Why |
|---|---|
| One state per environment | A mistake in dev cannot touch prod |
| Modules | Reuse a "data lake" or "pipeline" building block across teams |
| Plan in CI, apply on merge | Every change reviewed before it happens |
| No manual console changes | Drift makes the next apply destructive |
5. Containers: Docker and Kubernetes
Docker: package the pipeline with its runtime
# Dockerfile FROM python:3.12-slim AS base ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # cached layer: rebuilt only when requirements change COPY src/ ./src/ RUN useradd --create-home runner USER runner # never run as root ENTRYPOINT ["python", "-m", "src.main"]
docker build -t orders-pipeline:1.4.0 . docker run --rm -e RUN_DATE=2026-03-01 orders-pipeline:1.4.0 --run-date 2026-03-01
Dockerfile and docker commands: follows the official syntax but was not executed here, because it needs a live cloud account or service.
Kubernetes: run it on a schedule with retries
apiVersion: batch/v1
kind: CronJob
metadata:
name: orders-daily
spec:
schedule: "0 2 * * *"
concurrencyPolicy: Forbid # never run two loads at once
jobTemplate:
spec:
backoffLimit: 2 # retry a failed pod twice
template:
spec:
restartPolicy: Never
containers:
- name: orders
image: registry.example.com/orders-pipeline:1.4.0
args: ["--run-date", "$(RUN_DATE)"]
env:
- name: RUN_DATE
value: "yesterday"
- name: DB_PASSWORD
valueFrom:
secretKeyRef: {name: warehouse-creds, key: password}
resources:
requests: {cpu: "500m", memory: "1Gi"}
limits: {cpu: "2", memory: "4Gi"}
CronJob 'orders-daily': schedule '0 2 * * *', concurrency Forbid, container registry.example.com/orders-pipeline:1.4.0
kubectl apply -f orders-cronjob.yaml kubectl get cronjobs kubectl create job --from=cronjob/orders-daily orders-manual-run # run now kubectl logs job/orders-manual-run
| Kubernetes concept | Use in data platforms |
|---|---|
| Pod / Job / CronJob | Run batch steps; CronJob schedules them |
| Deployment / Service | Long-running APIs, Kafka consumers, Airflow webserver |
| Secret / ConfigMap | Credentials and configuration outside the image |
| Requests and limits | Fair sharing and protection from runaway jobs |
| Operators | Spark on Kubernetes, Flink Kubernetes Operator, Strimzi for Kafka |
Deep dive: the Kubernetes guide covers this in more depth.
"I treat pipelines as software: Git with pull requests, CI that lints, unit-tests transformations with pytest, runs dbt slim CI and data tests, then builds a Docker image; CD promotes the same artefact through test to prod with Terraform-managed infrastructure and an approval gate. Containers make runtimes reproducible, Kubernetes CronJobs or orchestrators run them with retries, and rollback covers both code and data."