End-to-End DevOps Project: Complete Implementation
· Pavan Y N · devops, kubernetes, terraform, cicd, gitops, aws
This guide walks through a complete DevOps project, from application code to a production deployment: a containerized Node.js microservice running on Amazon Elastic Kubernetes Service (EKS), provisioned with Terraform, built and scanned by a continuous integration and delivery (CI/CD) pipeline in GitHub Actions, delivered by Argo CD, and monitored with Prometheus and Grafana. EduGeek explains each phase and flags the details that commonly break in practice, such as renamed Terraform module inputs, unpinned CI actions, and Helm templating inside Alertmanager configuration.
Every configuration file below was validated against the current tooling as of October 2026: Terraform with terraform validate, Kubernetes manifests with kubeconform against the Kubernetes 1.36 schema, the workflow with actionlint, and the application by building and running it against PostgreSQL and Valkey. The account IDs, domain names, and bucket names are placeholders.
# Project overview
## Application architecture
Internet
|
+--------------v---------------+
| Application Load Balancer | created by the AWS Load Balancer
| (from a Kubernetes Ingress) | Controller, not by Terraform
+--------------+---------------+
|
+------------+------------+
| |
+-------v--------+ +--------v--------+
| Frontend | | API services |
| (React) | | (Node.js) |
+----------------+ +--------+--------+
|
+------------------+------------------+
| | |
+------v-----+ +------v------+ +------v-----+
| User | | Product | | Order |
| service | | service | | service |
+------+-----+ +------+------+ +------+-----+
| | |
+--------v------------------v------------------v-------+
| PostgreSQL (Amazon RDS) Valkey (ElastiCache) |
+------------------------------------------------------+
The rest of this guide implements the user service in detail. The product and order services follow the same pattern.
## Technology stack
| Layer | Tooling |
|---|---|
| Frontend | React, TypeScript |
| Backend | Node.js 24 (Active LTS), Express 5, TypeScript |
| Data | PostgreSQL 17 on Amazon Relational Database Service (RDS), Valkey 8 on Amazon ElastiCache |
| Containers | Docker, Amazon Elastic Container Registry (ECR) |
| Orchestration | Amazon EKS (Kubernetes 1.36) |
| CI/CD | GitHub Actions, Argo CD |
| Infrastructure | Terraform, AWS |
| Monitoring | Prometheus, Grafana (kube-prometheus-stack) |
| Security | Trivy, SonarQube, AWS Secrets Manager, External Secrets Operator |
Logging is deliberately not covered here. Common options are Grafana Loki with Grafana Alloy or the Elastic Stack.
Versions matter in this stack, and several defaults in older tutorials have expired. As of October 2026:
- →Amazon EKS supports Kubernetes 1.34 through 1.37 in standard support. Each version gets 14 months of standard support, followed by 12 months of extended support at an additional cost. Version 1.28 is no longer offered.
- →Node.js 20 reached end of life on April 30, 2026. Node.js 24 is in Active LTS until October 20, 2026 and then moves to Maintenance LTS through April 2028.
- →Amazon RDS for PostgreSQL supports major versions 14 through 18, and PostgreSQL 14 leaves standard support in February 2027.
# Phase 1: Application development
## Microservice structure
user-service/
├── src/
│ └── app.ts
├── tests/
├── Dockerfile
├── package.json
└── tsconfig.json
Larger services split src/ into controllers, routes, and middleware. A single file keeps this example readable.
## User service example
src/app.ts:
import express, { NextFunction, Request, Response } from 'express';
import { createClient } from 'redis';
import { Pool } from 'pg';
import * as promClient from '@prometheus-io/client';
const register = new promClient.Registry();
promClient.collectDefaultMetrics({ register });
const httpRequestDuration = new promClient.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code'],
buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
registers: [register],
});
const httpRequestsTotal = new promClient.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status_code'],
registers: [register],
});
// Database connection pool
const pool = new Pool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT ?? '5432', 10),
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
pool.on('error', (err) => console.error('Unexpected database error:', err));
// Cache connection (Redis or Valkey)
const redis = createClient({ url: process.env.REDIS_URL });
redis.on('error', (err) => console.error('Cache error:', err));
const app = express();
app.use(express.json());
// Record request duration and count, labeled by route pattern (not raw path)
app.use((req: Request, res: Response, next: NextFunction) => {
const stopTimer = httpRequestDuration.startTimer();
res.on('finish', () => {
const route = req.route ? `${req.baseUrl}${req.route.path}` : 'unmatched';
const labels = { method: req.method, route, status_code: res.statusCode };
stopTimer(labels);
httpRequestsTotal.inc(labels);
});
next();
});
// Liveness: the process is up and the event loop responds
app.get('/health', (_req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});
// Readiness: dependencies are reachable
app.get('/ready', async (_req, res) => {
try {
await pool.query('SELECT 1');
await redis.ping();
res.json({ status: 'ready' });
} catch (error) {
console.error('Readiness check failed:', error);
res.status(503).json({ status: 'unavailable' });
}
});
app.get('/metrics', async (_req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});
app.get('/users', async (_req, res) => {
try {
const cached = await redis.get('users:all');
if (cached) {
return res.json(JSON.parse(cached));
}
const result = await pool.query('SELECT id, name, email FROM users ORDER BY id LIMIT 100');
await redis.setEx('users:all', 300, JSON.stringify(result.rows));
res.json(result.rows);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/users', async (req, res) => {
const { name, email } = req.body ?? {};
if (typeof name !== 'string' || typeof email !== 'string' || !name || !email) {
return res.status(400).json({ error: 'name and email are required strings' });
}
try {
const result = await pool.query(
'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email',
[name, email]
);
await redis.del('users:all'); // invalidate the cached list
res.status(201).json(result.rows[0]);
} catch (error) {
console.error('Error creating user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
async function main(): Promise<void> {
await redis.connect();
const port = Number(process.env.PORT ?? 3000);
const server = app.listen(port, () => {
console.log(`User service listening on port ${port}`);
});
// Kubernetes sends SIGTERM before stopping a pod: finish requests, then close connections
process.on('SIGTERM', () => {
server.close(async () => {
await redis.quit();
await pool.end();
process.exit(0);
});
});
}
main().catch((error) => {
console.error('Failed to start user service:', error);
process.exit(1);
});
The service differs from many tutorial versions in a few ways that matter on Kubernetes:
- →Metrics: the Node.js Prometheus client
prom-clienthas been replaced on npm by@prometheus-io/client(version 0.16 and later, Node.js 22 or newer). Request metrics use the route pattern instead of the raw path, so a bot scanning random URLs cannot create unbounded time series. See the Prometheus guide for details. - →Health endpoints:
/healthanswers whether the process is alive, and/readyalso checks the database and cache. Using one endpoint for both probes would restart pods during a database outage instead of just removing them from the load balancer. - →Graceful shutdown: Kubernetes sends
SIGTERMbefore it stops a pod. The handler finishes in-flight requests and closes connections, and a container started withdocker stopexits with code 0 in under a second instead of waiting for the kill timeout. - →Input handling: the
POSTroute validates its body, and the list query has aLIMIT.
The service assumes a users table with id, name, and email columns.
## Dockerfile (multi-stage)
# Build stage
FROM node:24-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
# Production stage
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev && \
npm cache clean --force
COPY --from=builder --chown=node:node /app/dist ./dist
# The official Node.js images include an unprivileged "node" user
USER node
EXPOSE 3000
CMD ["node", "dist/app.js"]
- →
npm ci --only=productionis deprecated syntax. The current flag is--omit=dev. - →The official Node.js images already contain an unprivileged
nodeuser, so the image does not need to create one. - →A Dockerfile
HEALTHCHECKis ignored by Kubernetes, which uses the probes in the Deployment instead, so it is omitted. - →Pin the tag more tightly (for example to a digest) when reproducible builds matter.
# Phase 2: Infrastructure as code
## Terraform configuration
The infrastructure uses the community terraform-aws-modules for the virtual private cloud (VPC), the EKS cluster, and the RDS instance. Terraform state contains every secret that Terraform creates, so it lives in an encrypted S3 bucket. The S3 backend now supports native locking with use_lockfile, and the DynamoDB-based locking it replaces is deprecated.
main.tf (networking and cluster):
terraform {
required_version = ">= 1.10"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 6.59"
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
backend "s3" {
bucket = "example-terraform-state"
key = "production/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
}
}
provider "aws" {
region = var.region
}
variable "region" {
type = string
default = "us-east-1"
}
variable "github_repository" {
description = "GitHub repository allowed to push images, in owner/name form"
type = string
}
data "aws_availability_zones" "available" {
state = "available"
}
locals {
name = "production"
azs = slice(data.aws_availability_zones.available.names, 0, 3)
common_tags = {
Environment = "production"
ManagedBy = "terraform"
}
}
# VPC
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 6.0"
name = "${local.name}-vpc"
cidr = "10.0.0.0/16"
azs = local.azs
public_subnets = ["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/24"]
private_subnets = ["10.0.10.0/24", "10.0.11.0/24", "10.0.12.0/24"]
database_subnets = ["10.0.20.0/24", "10.0.21.0/24", "10.0.22.0/24"]
create_database_subnet_group = true
enable_nat_gateway = true
one_nat_gateway_per_az = true
enable_dns_hostnames = true
enable_flow_log = true
create_flow_log_cloudwatch_log_group = true
create_flow_log_cloudwatch_iam_role = true
# Subnet tags that the AWS Load Balancer Controller uses for discovery
public_subnet_tags = { "kubernetes.io/role/elb" = 1 }
private_subnet_tags = { "kubernetes.io/role/internal-elb" = 1 }
tags = local.common_tags
}
# EKS cluster
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "~> 21.0"
name = "${local.name}-eks"
kubernetes_version = "1.36"
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.private_subnets
endpoint_public_access = true
enable_cluster_creator_admin_permissions = true
addons = {
coredns = {}
kube-proxy = {}
metrics-server = {}
eks-pod-identity-agent = { before_compute = true }
vpc-cni = { before_compute = true }
}
eks_managed_node_groups = {
general = {
ami_type = "AL2023_x86_64_STANDARD"
instance_types = ["t3.large"]
capacity_type = "ON_DEMAND"
min_size = 2
max_size = 10
desired_size = 3
labels = {
role = "general"
}
}
spot = {
ami_type = "AL2023_x86_64_STANDARD"
instance_types = ["t3.large", "t3a.large"]
capacity_type = "SPOT"
min_size = 0
max_size = 5
desired_size = 2
labels = {
role = "spot"
}
taints = {
spot = {
key = "spot"
value = "true"
effect = "NO_SCHEDULE"
}
}
}
}
tags = local.common_tags
}
Notes on the cluster definition:
- →Version 21 of the EKS module renamed most inputs.
cluster_namebecamename,cluster_versionbecamekubernetes_version, andcluster_endpoint_public_accessbecameendpoint_public_access. The module needs AWS provider 6.59 or later. - →
taintsis a map of objects, and theeffectvalues are the EKS API constantsNO_SCHEDULE,NO_EXECUTE, andPREFER_NO_SCHEDULE, not the Kubernetes spellingNoSchedule. - →
metrics-serveris installed as an EKS community add-on because the HorizontalPodAutoscaler in Phase 3 depends on it. - →Restrict the public API endpoint with
endpoint_public_access_cidrs, or turn it off when a VPN or bastion is available.
main.tf (data stores and secrets):
# RDS PostgreSQL
resource "aws_security_group" "rds" {
name_prefix = "${local.name}-rds-"
vpc_id = module.vpc.vpc_id
tags = local.common_tags
lifecycle {
create_before_destroy = true
}
}
resource "aws_vpc_security_group_ingress_rule" "rds_from_nodes" {
security_group_id = aws_security_group.rds.id
referenced_security_group_id = module.eks.node_security_group_id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
}
module "rds" {
source = "terraform-aws-modules/rds/aws"
version = "~> 7.0"
identifier = "${local.name}-db"
engine = "postgres"
engine_version = "17"
family = "postgres17"
major_engine_version = "17"
instance_class = "db.t3.medium"
allocated_storage = 100
max_allocated_storage = 500
storage_encrypted = true
db_name = "appdb"
username = "appadmin"
port = 5432
# RDS creates and rotates the master password in AWS Secrets Manager
manage_master_user_password = true
create_db_subnet_group = false
db_subnet_group_name = module.vpc.database_subnet_group_name
vpc_security_group_ids = [aws_security_group.rds.id]
multi_az = true
backup_retention_period = 7
backup_window = "03:00-04:00"
maintenance_window = "Mon:04:00-Mon:05:00"
enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]
deletion_protection = true
tags = local.common_tags
}
# ElastiCache for Valkey (Redis-compatible)
resource "aws_security_group" "cache" {
name_prefix = "${local.name}-cache-"
vpc_id = module.vpc.vpc_id
tags = local.common_tags
lifecycle {
create_before_destroy = true
}
}
resource "aws_vpc_security_group_ingress_rule" "cache_from_nodes" {
security_group_id = aws_security_group.cache.id
referenced_security_group_id = module.eks.node_security_group_id
ip_protocol = "tcp"
from_port = 6379
to_port = 6379
}
resource "aws_elasticache_subnet_group" "cache" {
name = "${local.name}-cache"
subnet_ids = module.vpc.private_subnets
}
resource "aws_elasticache_replication_group" "cache" {
replication_group_id = "${local.name}-cache"
description = "Cache for application services"
engine = "valkey"
engine_version = "8.2"
node_type = "cache.t3.medium"
num_cache_clusters = 2
port = 6379
automatic_failover_enabled = true
multi_az_enabled = true
at_rest_encryption_enabled = true
transit_encryption_enabled = true
subnet_group_name = aws_elasticache_subnet_group.cache.name
security_group_ids = [aws_security_group.cache.id]
tags = local.common_tags
}
# Application secrets (read into Kubernetes by External Secrets Operator)
resource "random_password" "jwt_secret" {
length = 48
special = false
}
resource "aws_secretsmanager_secret" "app" {
name = "production/app-secrets"
tags = local.common_tags
}
resource "aws_secretsmanager_secret_version" "app" {
secret_id = aws_secretsmanager_secret.app.id
secret_string = jsonencode({
db_host = module.rds.db_instance_address
redis_url = "rediss://${aws_elasticache_replication_group.cache.primary_endpoint_address}:6379"
jwt_secret = random_password.jwt_secret.result
})
}
output "db_master_secret_arn" {
value = module.rds.db_instance_master_user_secret_arn
}
Notes on the data stores:
- →
manage_master_user_password = truemakes RDS create the master password and store it in AWS Secrets Manager, so it never appears in Terraform state or in this file. - →An Application Load Balancer is not defined in Terraform. The AWS Load Balancer Controller creates one from the Kubernetes Ingress in Phase 3. Cross-zone load balancing is always on for Application Load Balancers.
- →ElastiCache with transit encryption requires clients to connect with the
rediss://scheme, as the secret above does. - →ElastiCache for Valkey is Redis-compatible and the
redisnpm package works with it unchanged. - →The
random_passwordvalue is stored in Terraform state, which is another reason to keep state encrypted and access-controlled.
cicd.tf (container registry and keyless CI access):
# Container registry and keyless GitHub Actions access
resource "aws_ecr_repository" "user_service" {
name = "user-service"
image_tag_mutability = "IMMUTABLE"
tags = local.common_tags
}
resource "aws_iam_openid_connect_provider" "github" {
url = "https://token.actions.githubusercontent.com"
client_id_list = ["sts.amazonaws.com"]
}
data "aws_iam_policy_document" "github_trust" {
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [aws_iam_openid_connect_provider.github.arn]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:sub"
values = ["repo:${var.github_repository}:ref:refs/heads/main"]
}
}
}
resource "aws_iam_role" "github_actions" {
name = "github-actions-user-service"
assume_role_policy = data.aws_iam_policy_document.github_trust.json
}
data "aws_iam_policy_document" "ecr_push" {
statement {
actions = ["ecr:GetAuthorizationToken"]
resources = ["*"]
}
statement {
actions = [
"ecr:BatchCheckLayerAvailability",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:PutImage",
]
resources = [aws_ecr_repository.user_service.arn]
}
}
resource "aws_iam_role_policy" "ecr_push" {
name = "ecr-push"
role = aws_iam_role.github_actions.id
policy = data.aws_iam_policy_document.ecr_push.json
}
The AWS Identity and Access Management (IAM) role trusts GitHub's OpenID Connect (OIDC) identity provider and only for the main branch of one repository, so no long-lived AWS keys are stored in GitHub. Immutable image tags mean a tag can never be silently replaced, but re-running a workflow for the same commit fails at the push step.
# Phase 3: Kubernetes deployment
## Cluster add-ons
Four controllers sit between the Terraform-built cluster and the manifests below. Install them with Helm or Argo CD, and give each an IAM role through EKS Pod Identity (the eks-pod-identity-agent add-on is already enabled above) or IAM roles for service accounts:
- →AWS Load Balancer Controller creates an Application Load Balancer for each
Ingresswith thealbclass. - →External Secrets Operator copies values from AWS Secrets Manager into Kubernetes Secrets.
- →kube-prometheus-stack provides Prometheus, Alertmanager, and Grafana (Phase 5).
- →Argo CD applies the manifests from Git (Phase 4).
External Secrets Operator reads from Secrets Manager through a cluster-wide store. The controller's IAM role needs secretsmanager:GetSecretValue on the secrets it serves.
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
name: aws-secrets-manager
spec:
provider:
aws:
service: SecretsManager
region: us-east-1
## Kubernetes manifests
The manifests live in k8s/user-service/ and are assembled by Kustomize. The Deployment refers to the bare image name user-service, and the images block in the Kustomization sets the registry and tag. The pipeline changes only that block, so the Deployment file itself never contains a mutable tag such as latest.
k8s/user-service/kustomization.yaml:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: production
resources:
- serviceaccount.yaml
- deployment.yaml
- service.yaml
- hpa.yaml
- pdb.yaml
- ingress.yaml
- externalsecret.yaml
- podmonitor.yaml
images:
- name: user-service
newName: 123456789012.dkr.ecr.us-east-1.amazonaws.com/user-service
newTag: bootstrap # replaced by the pipeline with the commit SHA
k8s/user-service/deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
labels:
app: user-service
spec:
# No replicas field: the HorizontalPodAutoscaler owns the replica count.
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
spec:
serviceAccountName: user-service
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: user-service
containers:
- name: user-service
image: user-service # tag is set by kustomize
ports:
- containerPort: 3000
name: http
env:
- name: NODE_ENV
value: production
- name: PORT
value: "3000"
- name: DB_NAME
value: appdb
envFrom:
- secretRef:
name: user-service-secrets
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 512Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
startupProbe:
httpGet:
path: /health
port: http
periodSeconds: 2
failureThreshold: 30
readinessProbe:
httpGet:
path: /ready
port: http
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
livenessProbe:
httpGet:
path: /health
port: http
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
Differences from older examples:
- →The Deployment has no
replicasfield. The HorizontalPodAutoscaler owns the replica count, and a fixed value in Git would fight it on every sync. - →Separate startup, readiness, and liveness probes use the two endpoints from the service code.
- →The pod runs as a non-root user with a read-only root filesystem, no added capabilities, and the default seccomp profile.
runAsUser: 1000is required because Kubernetes cannot verify that a user namednodeis non-root. - →A topology spread constraint spreads pods across availability zones, which is clearer than pod anti-affinity for this purpose.
- →The
prometheus.io/*annotations are gone. They are only a convention for hand-written scrape rules, and the PodMonitor below replaces them.
k8s/user-service/service.yaml:
apiVersion: v1
kind: Service
metadata:
name: user-service
labels:
app: user-service
spec:
type: ClusterIP
selector:
app: user-service
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
k8s/user-service/hpa.yaml:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: user-service
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: user-service
minReplicas: 3
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
- type: Pods
value: 4
periodSeconds: 15
selectPolicy: Max
CPU is a good autoscaling signal for this service. Memory utilization can be a poor one for Node.js, because the garbage collector may keep memory allocated after load drops, so the memory metric was removed.
k8s/user-service/pdb.yaml:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: user-service
spec:
maxUnavailable: 1
selector:
matchLabels:
app: user-service
k8s/user-service/ingress.yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: user-service
annotations:
alb.ingress.kubernetes.io/scheme: internet-facing
alb.ingress.kubernetes.io/target-type: ip
alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS": 443}]'
alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-east-1:123456789012:certificate/REPLACE_ME
alb.ingress.kubernetes.io/healthcheck-path: /ready
spec:
ingressClassName: alb
rules:
- host: api.example.com
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: user-service
port:
name: http
The alb IngressClass hands the Ingress to the AWS Load Balancer Controller. target-type: ip sends traffic directly to pod IP addresses, and scheme: internet-facing creates a public load balancer (the default is internal).
k8s/user-service/externalsecret.yaml:
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: user-service
spec:
refreshInterval: 1h
secretStoreRef:
name: aws-secrets-manager
kind: ClusterSecretStore
target:
name: user-service-secrets
creationPolicy: Owner
data:
- secretKey: DB_HOST
remoteRef:
key: production/app-secrets
property: db_host
- secretKey: REDIS_URL
remoteRef:
key: production/app-secrets
property: redis_url
# The RDS-managed master secret holds "username" and "password".
# Use the ARN from the Terraform output db_master_secret_arn.
- secretKey: DB_USER
remoteRef:
key: arn:aws:secretsmanager:us-east-1:123456789012:secret:rds!db-REPLACE_ME
property: username
- secretKey: DB_PASSWORD
remoteRef:
key: arn:aws:secretsmanager:us-east-1:123456789012:secret:rds!db-REPLACE_ME
property: password
The user-service-secrets Secret that the Deployment reads is created by this resource, so the application's credentials are never committed to Git. Replace the REPLACE_ME ARN with the db_master_secret_arn Terraform output.
k8s/user-service/podmonitor.yaml:
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: user-service
spec:
selector:
matchLabels:
app: user-service
podMetricsEndpoints:
- port: http
path: /metrics
interval: 15s
# Phase 4: CI/CD pipeline
## GitHub Actions workflow
.github/workflows/deploy.yml:
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
env:
AWS_REGION: us-east-1
ECR_REPOSITORY: user-service
jobs:
test:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '24'
cache: npm
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test -- --coverage
security-scan:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Scan the repository with Trivy
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: fs
scan-ref: .
severity: CRITICAL,HIGH
ignore-unfixed: true
exit-code: '1' # without this, Trivy reports findings but never fails the job
- name: SonarQube scan
# Secrets are not available to pull requests from forks
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
build-and-push:
needs: [test, security-scan]
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
permissions:
contents: read
id-token: write # lets the job request an OIDC token for AWS
outputs:
image: ${{ steps.image.outputs.uri }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Configure AWS credentials (OIDC, no stored keys)
uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Log in to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2.1.7
- name: Compute the image reference
id: image
run: echo "uri=${{ steps.login-ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:${{ github.sha }}" >> "$GITHUB_OUTPUT"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- name: Build the image (not pushed yet)
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
load: true
tags: ${{ steps.image.outputs.uri }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Scan the image with Trivy
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: ${{ steps.image.outputs.uri }}
severity: CRITICAL,HIGH
ignore-unfixed: true
exit-code: '1'
- name: Push the image
env:
IMAGE: ${{ steps.image.outputs.uri }}
run: docker push "$IMAGE"
deploy:
needs: build-and-push
runs-on: ubuntu-24.04
permissions:
contents: write # the job commits the new image tag
concurrency:
group: deploy-user-service
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Update the image in the manifests
env:
IMAGE: ${{ needs.build-and-push.outputs.image }}
run: |
cd k8s/user-service
kustomize edit set image "user-service=${IMAGE}"
- name: Commit and push
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add k8s/user-service/kustomization.yaml
git commit -m "chore: deploy user-service ${GITHUB_SHA::7}"
git push
The workflow fixes several problems that are common in copied pipelines:
- →Security scanning that never fails: Trivy exits with code 0 by default even when it finds vulnerabilities. Setting
exit-code: '1'is what makes the job fail. - →Scan before push: the image is built locally with
load: true, scanned, and pushed only if the scan passes. Scanning after the push leaves a vulnerable image in the registry. - →Pinned actions: every third-party action is pinned to a full commit SHA with the version in a comment. In March 2026, attackers force-pushed malicious code to 76 of the 77 version tags of
aquasecurity/trivy-action, so workflows that referenced those tags ran an infostealer before the real scan and had to treat their secrets as exposed. Tags can be moved, but a full commit SHA cannot, so GitHub's guidance is to pin actions to a commit SHA, verify that the SHA belongs to the original repository, and let Dependabot or Renovate keep the pins current. The Trivy SHA below is the signedv0.36.0release. - →No stored cloud credentials: the job requests an OIDC token and assumes the IAM role from
cicd.tf, which requiresid-token: writeon that job only. Default permissions are read-only. - →Current actions:
actions/checkout,setup-node,docker/build-push-action, andaws-actions/configure-aws-credentialshave all moved forward several major versions since 2025, andactionlintreports thatcodecov/codecov-action@v3is too old to run on GitHub Actions, so the coverage upload step was dropped. - →A stable runner image:
ubuntu-latestmoves to Ubuntu 26.04 in November 2026, soubuntu-24.04is pinned. Kustomize is preinstalled on that image. - →A single image reference: the tag is the commit SHA, which avoids the multi-line
tagsoutput ofdocker/metadata-actionthat breakskustomize edit.
The deploy job commits to main, so branch protection must allow the workflow to push, or the job should open a pull request against a separate configuration repository instead. Pushes made with the default GITHUB_TOKEN do not start new workflow runs, so the commit does not retrigger the pipeline.
## GitOps delivery with Argo CD
Argo CD watches the repository and applies whatever k8s/user-service/ contains. It detects the Kustomization automatically. For more on this model, see the GitOps guide.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: user-service
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: default
source:
repoURL: https://github.com/example-org/devops-project.git
targetRevision: main
path: k8s/user-service
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
With automated sync, prune removes resources that were deleted from Git, and selfHeal reverts manual changes made with kubectl. The Application resource lives in the argocd namespace, which must match the namespace where Argo CD is installed.
# Phase 5: Monitoring
The kube-prometheus-stack Helm chart installs Prometheus, Alertmanager, Grafana, kube-state-metrics, and node exporter, and it discovers scrape targets through PodMonitor and ServiceMonitor resources.
values.yaml:
prometheus:
prometheusSpec:
retention: 30d
# Select ServiceMonitors and PodMonitors from every namespace, not only
# those labeled with this Helm release.
serviceMonitorSelectorNilUsesHelmValues: false
podMonitorSelectorNilUsesHelmValues: false
storageSpec:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 50Gi
alertmanager:
alertmanagerSpec:
# Mounted at /etc/alertmanager/secrets/<secret-name>/
secrets:
- alertmanager-slack
config:
global:
resolve_timeout: 5m
route:
receiver: slack
group_by: ['alertname', 'namespace']
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
receivers:
- name: slack
slack_configs:
- api_url_file: /etc/alertmanager/secrets/alertmanager-slack/webhook-url
channel: '#alerts'
send_resolved: true
title: 'Alert: {{ .GroupLabels.alertname }}'
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install kube-prometheus-stack prometheus-community/kube-prometheus-stack \
--namespace monitoring --create-namespace \
--values values.yaml
By default the chart does not run Helm templating over alertmanager.config. A placeholder such as '{{ .Values.slackWebhook }}', which appears in many tutorials, therefore reaches Alertmanager as literal text and breaks the Slack integration. The values above read the webhook from a mounted Kubernetes Secret instead. Create it before installing:
kubectl create namespace monitoring
kubectl create secret generic alertmanager-slack \
--namespace monitoring \
--from-literal=webhook-url='https://hooks.slack.com/services/REPLACE/ME'
The PodMonitor from Phase 3 makes Prometheus scrape each user-service pod on /metrics. Alert rules, recording rules, and PromQL for the metrics this service exposes are in the Prometheus guide, and dashboards for them are in the Grafana guide. For the Terraform concepts used above, see the Terraform guide.
# Production readiness checklist
The pieces above are a foundation, not proof that the system is production-ready. Verify each area with a test instead of assuming it works.
| Area | What to verify |
|---|---|
| Deployments | A bad image fails the rollout and the previous version keeps serving traffic. Roll back by reverting the Git commit. |
| Availability | Delete a pod, drain a node, and block one availability zone, and confirm requests keep succeeding. |
| Data | Restore the RDS backup into a new instance and confirm the application works against it. |
| Secrets | Rotate a secret in AWS Secrets Manager and confirm the pods pick up the change. |
| Alerts | Trigger each critical alert on purpose and confirm that it reaches the right channel with a link to a runbook. |
| Scaling | Run a load test and confirm that the HorizontalPodAutoscaler and node groups scale up and back down. |
| Upgrades | Plan an EKS minor-version upgrade at least once a year, because a version leaves extended support 26 months after release. |
| Security | Review IAM roles, enforce network policies with a network plugin that supports them, and keep image scanning blocking. |
| Cost | Check NAT gateway, load balancer, and idle node costs, and use the Spot node group only for interruption-tolerant work. |
# Key takeaways
- →Terraform module inputs change between major versions, so pin module versions and run
terraform validate, because version 21 of the EKS module renamedcluster_nametonameandcluster_versiontokubernetes_version. - →Let RDS manage the master password in Secrets Manager and sync secrets into Kubernetes with External Secrets Operator, so credentials never appear in Git or Terraform state.
- →Use separate liveness and readiness endpoints, and handle
SIGTERM, so deployments and node drains do not drop requests. - →Authenticate GitHub Actions to AWS with OIDC, pin every third-party action to a commit SHA, and make security scanners fail the build with a non-zero exit code.
- →Build the image, scan it, and push it only if the scan passes, and tag images with the commit SHA instead of
latest. - →Prefer PodMonitor or ServiceMonitor resources over annotation-based scrape rules, and never put Helm placeholders inside Alertmanager configuration.
- →Check that tool versions are still supported before pinning them: EKS 1.28 and Node.js 20 are both past end of life as of October 2026.
# Further reading
Test yourself: End-to-End DevOps Project assessment