CI/CD and infrastructure as code
- CI
- continuous integration
- CD
- continuous delivery
Mid-level Frequently asked 5 min
On this page
The question
What are the stages of a CI/CD pipeline for a Java service, from commit to production?
30-second answer
On every push: compile, unit tests and static analysis, the fastest feedback. Then build one container image, tag it with the commit hash, scan it and push it to a registry. Deploy that exact image to a test environment for integration and contract tests, and plan any infrastructure change for review. After the merge, promote the same image to staging, then to production behind an approval or automatically, with a canary or rolling deploy, smoke tests and a ready rollback.
Understand it
From commit to production
Step by stepA developer pushes a branch and opens a pull request. The pipeline starts on every push, so feedback arrives before review, not after the merge.
View as text
Seven pipeline stages, top to bottom: Commit + PR, Build, unit tests, Image + scan, Test environment, Terraform plan, Staging + approval, Production. Each stage shows a detail once reached, and a line at the bottom names the image running in production.
A developer pushes a branch and opens a pull request. The pipeline starts on every push, so feedback arrives before review, not after the merge.
Compile, unit tests and static analysis run first: the fastest checks, a few minutes. A red build stops the pipeline here, before anything is packaged.
The pipeline builds one container image, tags it with the commit hash, 3f9c2e1, scans it for known vulnerabilities and pushes it to the registry. It is never rebuilt.
That exact image is deployed to a short-lived test environment, where integration and contract tests run against a real database and broker.
The change also adds a queue, so Terraform computes a plan: one resource to add, nothing destroyed. Reviewers read the plan in the pull request, like code.
After the merge, Terraform applies and the image reaches staging. With continuous delivery a person approves production; with continuous deployment, passing checks are enough.
The same image is promoted to production as a canary, watched on error rate and latency, then rolled out to every instance. Nobody logged in to a server.
Had the canary’s error rate jumped, the pipeline would redeploy the previous image, 9a1b7d0, in minutes. Rollback is a deploy of a known artifact, not a repair.
Seven pipeline stages, top to bottom: Commit + PR, Build, unit tests, Image + scan, Test environment, Terraform plan, Staging + approval, Production. Each stage shows a detail once reached, and a line at the bottom names the image running in production.
A developer pushes a branch and opens a pull request. The pipeline starts on every push, so feedback arrives before review, not after the merge.
Compile, unit tests and static analysis run first: the fastest checks, a few minutes. A red build stops the pipeline here, before anything is packaged.
The pipeline builds one container image, tags it with the commit hash, 3f9c2e1, scans it for known vulnerabilities and pushes it to the registry. It is never rebuilt.
That exact image is deployed to a short-lived test environment, where integration and contract tests run against a real database and broker.
The change also adds a queue, so Terraform computes a plan: one resource to add, nothing destroyed. Reviewers read the plan in the pull request, like code.
After the merge, Terraform applies and the image reaches staging. With continuous delivery a person approves production; with continuous deployment, passing checks are enough.
The same image is promoted to production as a canary, watched on error rate and latency, then rolled out to every instance. Nobody logged in to a server.
Had the canary’s error rate jumped, the pipeline would redeploy the previous image, 9a1b7d0, in minutes. Rollback is a deploy of a known artifact, not a repair.
Takeaway: A pipeline gives fast feedback first, builds one immutable artifact, promotes that same artifact through environments, applies infrastructure changes from reviewed code, and rolls back by redeploying the previous version.
| Concept | AWS (Amazon Web Services) | Azure | GCP (Google Cloud Platform) |
|---|---|---|---|
| Pipelines | CodePipeline, CodeBuild | Azure Pipelines | Cloud Build, Cloud Deploy |
| Image registry | ECR (Elastic Container Registry) | ACR (Azure Container Registry) | Artifact Registry |
| Native IaC (infrastructure as code) | CloudFormation, CDK (Cloud Development Kit) | Bicep, ARM (Azure Resource Manager) templates | Infrastructure Manager, running Terraform |
| Terraform state backend | S3 (Simple Storage Service) bucket with a lock file | Blob Storage container | Cloud Storage bucket |
In code
name: orders
on: { push: { branches: [main] }, pull_request: {} }
permissions: { id-token: write, contents: read } # OIDC (OpenID Connect) token for the cloud role
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with: { distribution: temurin, java-version: '21', cache: gradle }
- run: ./gradlew build # compile, unit tests, static analysis
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/orders-ci
aws-region: eu-west-1
- uses: aws-actions/amazon-ecr-login@v2
id: ecr
- run: |
IMAGE=${{ steps.ecr.outputs.registry }}/orders:${{ github.sha }}
docker build -t "$IMAGE" . && docker push "$IMAGE"terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
backend "s3" {
bucket = "acme-terraform-state"
key = "orders/prod.tfstate"
region = "eu-west-1"
use_lockfile = true # one apply at a time
encrypt = true
}
}
resource "aws_sqs_queue" "invoice_jobs" {
name = "invoice-jobs"
visibility_timeout_seconds = 60
tags = { service = "orders", managed-by = "terraform" }
}# Wrong: a hand edit on one server; the next instance or deploy silently undoes it
Wrong ssh prod-7 'sudo sed -i "s/pool=20/pool=40/" /opt/orders/app.properties && sudo systemctl restart orders'
# Right: change the code, review the plan, and let the pipeline replace every instance
Right git commit -am "Raise the connection pool to 40" && git push origin raise-pool
Right terraform plan -out=tfplan && terraform apply tfplanSolve it
terraform plan wants to replace the production database. What do you do?
A pull request renames the Terraform resource aws_db_instance.db to aws_db_instance.orders for clarity and bumps the
PostgreSQL minor version. The pipeline’s plan reads 1 to add, 0 to change, 1 to destroy, and the database line says
-/+ must be replaced. A teammate says it is only a rename and wants to apply. Explain what would happen and fix the change.
- Read the plan as the truth. One to destroy is the production database. Terraform tracks resources by their address in state, so a new name looks like a new resource, and the old one, no longer in code, is destroyed.
- Separate the two changes. The rename needs no change in the cloud at all; the version bump is an in-place update. Each should show as zero to destroy, so a plan that destroys is a bug in the change, not a cost of it.
- Tell Terraform about the rename. A
movedblock maps the old address to the new one, so state follows the code and the plan shows an in-place version change only. - Guard what must never be destroyed. Add
prevent_destroy, keep deletion protection on, and have the pipeline fail any plan that destroys a stateful resource unless someone explicitly approves it. - Check. The new plan reads
0 to add, 1 to change, 0 to destroy, with the database as an in-place update. Apply it in staging first, inside the maintenance window.
moved {
from = aws_db_instance.db
to = aws_db_instance.orders
}
resource "aws_db_instance" "orders" {
identifier = "orders-db"
engine = "postgres"
engine_version = "17.6"
instance_class = "db.m7g.large"
deletion_protection = true
lifecycle {
prevent_destroy = true # any plan that destroys this fails
}
}How to answer
- Order the stages by speed so failures surface early.
- Build once, promote the same artifact; never rebuild per environment.
- Configuration differs per environment, the artifact does not.
- Rollback means redeploying the previous tag, which must stay available.
Common mistakes
- Rebuilding the jar or image separately for staging and production.
- Deploying to production by hand from a laptop.
Follow-up questions
What is Terraform, and how does it work?
Terraform is an IaC (infrastructure as code) tool: you declare resources, such as networks, databases and queues, in HCL (HashiCorp Configuration Language) files, and providers translate them into cloud API calls. It keeps a state file mapping your code to real resources. terraform plan compares code, state and reality and shows what would be added, changed or destroyed; terraform apply makes it so. State lives in a shared, locked backend, and modules package reusable pieces.
- Declarative, so you describe the end state, not the steps.
- Works across providers, unlike CloudFormation or Bicep, which are tied to one cloud.
- Review the plan in the pull request and apply from the pipeline only.
What is immutable infrastructure?
Servers and containers are never changed after they are deployed: no SSH fixes, no in-place upgrades, no hand-edited config. To change anything, you build a new image or version from code and replace the old instances with new ones. Every environment then runs exactly what was tested, drift cannot build up, a bad change is rolled back by redeploying the previous image, and any instance can be destroyed and recreated at will.
- Containers and machine images make it natural; configuration management on live servers is the mutable opposite.
- State lives outside the instances, in databases and storage, which are changed through migrations.
- It pairs with blue/green, canary and rolling deploys.
What is the difference between continuous integration, continuous delivery and continuous deployment?
CI (continuous integration) is merging small changes into the main branch often, each one built and tested automatically, so integration problems appear within minutes. CD (continuous delivery) goes further: every change that passes the pipeline is releasable, and production is one approved click away. Continuous deployment removes the click: every passing change goes to production automatically, which requires strong tests, monitoring, feature flags and automated rollback.
- CI is about the main branch staying healthy.
- Delivery keeps a human decision; deployment trusts the pipeline.
- Feature flags separate deploying code from releasing a feature.
Your pipeline takes 45 minutes. How do you speed it up?
Measure each stage first. Cache dependencies and build layers, run tests in parallel and only the affected modules, move slow end-to-end suites after the merge or to a nightly run, use Testcontainers instead of shared environments that queue, and keep the pull request path under about ten minutes. Never speed it up by skipping tests on failure.
Check yourself
Show answers
- The same image, orders:3f9c2e1: Correct. Production then runs exactly what was tested.
- A fresh build from the same commit, with production settings: Incorrect. A rebuild may pull different dependencies; settings come from configuration.
- Whatever the latest tag points to: Incorrect. latest moves; deploys must name an immutable tag.
Show answers
- Do not apply; add a moved block so state follows the rename: Correct. Terraform tracks resources by address; moved maps old to new.
- Apply it; a rename is harmless: Incorrect. The plan says it will destroy the database and create a new one.
- Delete the database from state by hand, then apply: Incorrect. Terraform would then create a second database beside the first.