devops-patterns
DevOps and cloud infrastructure patterns.
how to use
when to apply
Reference these guidelines when:
- writing Terraform modules or managing state
- configuring Kubernetes resources
- writing Dockerfiles or Docker Compose
- setting up CI/CD pipelines (GitHub Actions)
- managing secrets in infrastructure
- configuring monitoring and alerting
rule categories by priority
| priority |
category |
impact |
| 1 |
infrastructure as code |
critical |
| 2 |
container best practices |
critical |
| 3 |
Kubernetes patterns |
high |
| 4 |
CI/CD pipelines |
high |
| 5 |
secrets management |
critical |
| 6 |
monitoring |
medium |
quick reference
1. infrastructure as code (critical)
Terraform:
- use modules for reusable components; keep modules small and focused
- remote state with locking (S3 + DynamoDB, Terraform Cloud)
- separate state per environment (dev/staging/prod)
- use
terraform plan before every apply; review changes
- pin provider versions:
required_providers { aws = { version = "~> 5.0" } }
- use
data sources to reference existing resources; never hardcode IDs
- tag all resources with: environment, project, owner, managed-by
- use
terraform fmt and terraform validate in CI
- keep sensitive values in
terraform.tfvars (gitignored) or secrets manager
- use workspaces sparingly; prefer separate state files per environment
Structure:
modules/
<module-name>/
main.tf
variables.tf
outputs.tf
environments/
dev/
main.tf # calls modules
terraform.tfvars
prod/
main.tf
terraform.tfvars
2. container best practices (critical)
- use multi-stage builds to minimize image size
- pin base image versions with SHA digest
- run as non-root user (
USER 1001)
- one process per container
- use
.dockerignore to exclude unnecessary files
- order Dockerfile layers for cache efficiency (dependencies before code)
- scan images for vulnerabilities in CI (trivy, snyk)
- set resource limits (memory, CPU)
- use health checks
- prefer COPY over ADD
- never store secrets in images; use runtime injection
Multi-stage template:
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production=false
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
RUN addgroup -g 1001 -S app && adduser -S app -u 1001
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
USER 1001
EXPOSE 3000
HEALTHCHECK CMD wget -q --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]
3. Kubernetes patterns (high)
- always set resource requests AND limits
- use liveness, readiness, and startup probes
- use namespaces for environment separation
- use RBAC with least-privilege service accounts
- store config in ConfigMaps, secrets in Secrets (or external secrets operator)
- use Deployments for stateless, StatefulSets for stateful workloads
- set Pod Disruption Budgets for availability
- use horizontal pod autoscaler (HPA) for scaling
- use network policies to restrict pod-to-pod traffic
- prefer rolling updates; set maxSurge and maxUnavailable
Resource template:
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 15
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
4. CI/CD pipelines (high)
GitHub Actions:
- pin action versions with SHA:
uses: actions/checkout@<sha>
- use
concurrency to cancel outdated runs
- cache dependencies (node_modules, pip cache, Docker layers)
- separate build, test, and deploy jobs
- use environment protection rules for production deploys
- store secrets in GitHub Secrets; never in workflow files
- use matrix builds for multi-version testing
- fail fast on lint/type errors before running tests
- use OIDC for cloud provider authentication (no long-lived keys)
Pipeline stages:
- Lint + format check
- Type check
- Unit tests
- Build
- Integration tests
- Security scan
- Deploy to staging
- E2E tests on staging
- Deploy to production (manual approval)
5. secrets management (critical)
Hierarchy (most to least preferred):
- Cloud secrets manager (AWS Secrets Manager, GCP Secret Manager)
- External secrets operator (K8s)
- CI/CD platform secrets (GitHub Secrets)
- Encrypted files (SOPS, age)
- Environment variables (acceptable for non-sensitive config)
- Hardcoded values (NEVER for secrets)
- rotate secrets regularly; automate rotation where possible
- audit secret access
- separate secrets by environment
- use short-lived credentials (OIDC, STS) over long-lived keys
6. monitoring (medium)
- instrument with metrics (Prometheus), logs (structured JSON), and traces (OpenTelemetry)
- define SLIs and SLOs for critical services
- alert on symptoms (error rate, latency), not causes
- use dashboards for context, not primary alerting
- implement health check endpoints for all services
- monitor resource utilization and cost
- set up on-call rotation and escalation policies
common fixes
| problem |
fix |
| Terraform state drift |
terraform plan to detect, terraform import for unmanaged resources |
| Large Docker image |
use multi-stage build, alpine base, .dockerignore |
| Pod CrashLoopBackOff |
check logs, verify resource limits, check probes |
| Slow CI pipeline |
cache dependencies, parallelize jobs, fail fast |
| Secret in git history |
rotate immediately, use git-filter-repo to purge |
| OOM killed pod |
increase memory limit or optimize application |
CI/CD best practices (from CI/CD handbook patterns)
GitHub Actions Advanced Patterns
Reusable Workflows:
# .github/workflows/reusable-deploy.yml
on:
workflow_call:
inputs:
environment:
required: true
type: string
secrets:
AWS_ROLE_ARN:
required: true
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
permissions:
id-token: write # OIDC
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@<sha>
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
Composite Actions (reusable steps):
# .github/actions/setup-project/action.yml
name: Setup Project
runs:
using: composite
steps:
- uses: actions/setup-python@<sha>
with:
python-version: '3.11'
- run: pip install uv && uv sync
shell: bash
Matrix Strategies:
strategy:
fail-fast: false
matrix:
python: ['3.10', '3.11', '3.12']
os: [ubuntu-latest, macos-latest]
exclude:
- python: '3.10'
os: macos-latest
Pipeline Optimization Techniques
| Technique |
Savings |
How |
| Dependency caching |
30-60s |
actions/cache with hash key |
| Docker layer caching |
1-3min |
docker/build-push-action with cache |
| Parallel jobs |
40-60% |
Split tests, lint independently |
| Conditional runs |
Variable |
if: github.event_name == 'push' |
| Artifact reuse |
30-60s |
Build once, deploy to multiple envs |
| Path filters |
Variable |
Only run when relevant files change |
cross-references
- security-review skill: CI/CD security rules
- DEVOPS_TOOLKIT.md: Infrastructure tools reference
- SECURITY_ARSENAL.md: CI/CD security checklist
1---2name: devops-patterns3description: DevOps and cloud infrastructure patterns for Terraform, Kubernetes, Docker, and CI/CD. Use when writing infrastructure code, configuring deployments, or setting up pipelines.4---56# devops-patterns78DevOps and cloud infrastructure patterns.910## how to use1112- `/devops-patterns`13 Apply these infrastructure patterns to all DevOps work in this conversation.1415- `/devops-patterns <context>`16 Review the context against rules below and suggest improvements.1718## when to apply1920Reference these guidelines when:21- writing Terraform modules or managing state22- configuring Kubernetes resources23- writing Dockerfiles or Docker Compose24- setting up CI/CD pipelines (GitHub Actions)25- managing secrets in infrastructure26- configuring monitoring and alerting2728## rule categories by priority2930| priority | category | impact |31|----------|----------|--------|32| 1 | infrastructure as code | critical |33| 2 | container best practices | critical |34| 3 | Kubernetes patterns | high |35| 4 | CI/CD pipelines | high |36| 5 | secrets management | critical |37| 6 | monitoring | medium |3839## quick reference4041### 1. infrastructure as code (critical)4243**Terraform**:44- use modules for reusable components; keep modules small and focused45- remote state with locking (S3 + DynamoDB, Terraform Cloud)46- separate state per environment (dev/staging/prod)47- use `terraform plan` before every `apply`; review changes48- pin provider versions: `required_providers { aws = { version = "~> 5.0" } }`49- use `data` sources to reference existing resources; never hardcode IDs50- tag all resources with: environment, project, owner, managed-by51- use `terraform fmt` and `terraform validate` in CI52- keep sensitive values in `terraform.tfvars` (gitignored) or secrets manager53- use workspaces sparingly; prefer separate state files per environment5455**Structure**:56```57modules/58 <module-name>/59 main.tf60 variables.tf61 outputs.tf62environments/63 dev/64 main.tf # calls modules65 terraform.tfvars66 prod/67 main.tf68 terraform.tfvars69```7071### 2. container best practices (critical)7273- use multi-stage builds to minimize image size74- pin base image versions with SHA digest75- run as non-root user (`USER 1001`)76- one process per container77- use `.dockerignore` to exclude unnecessary files78- order Dockerfile layers for cache efficiency (dependencies before code)79- scan images for vulnerabilities in CI (trivy, snyk)80- set resource limits (memory, CPU)81- use health checks82- prefer COPY over ADD83- never store secrets in images; use runtime injection8485**Multi-stage template**:86```dockerfile87FROM node:20-alpine AS builder88WORKDIR /app89COPY package*.json ./90RUN npm ci --production=false91COPY . .92RUN npm run build9394FROM node:20-alpine95WORKDIR /app96RUN addgroup -g 1001 -S app && adduser -S app -u 100197COPY --from=builder /app/dist ./dist98COPY --from=builder /app/node_modules ./node_modules99USER 1001100EXPOSE 3000101HEALTHCHECK CMD wget -q --spider http://localhost:3000/health || exit 1102CMD ["node", "dist/index.js"]103```104105### 3. Kubernetes patterns (high)106107- always set resource requests AND limits108- use liveness, readiness, and startup probes109- use namespaces for environment separation110- use RBAC with least-privilege service accounts111- store config in ConfigMaps, secrets in Secrets (or external secrets operator)112- use Deployments for stateless, StatefulSets for stateful workloads113- set Pod Disruption Budgets for availability114- use horizontal pod autoscaler (HPA) for scaling115- use network policies to restrict pod-to-pod traffic116- prefer rolling updates; set maxSurge and maxUnavailable117118**Resource template**:119```yaml120resources:121 requests:122 cpu: 100m123 memory: 128Mi124 limits:125 cpu: 500m126 memory: 512Mi127livenessProbe:128 httpGet:129 path: /health130 port: 8080131 initialDelaySeconds: 15132 periodSeconds: 10133readinessProbe:134 httpGet:135 path: /ready136 port: 8080137 initialDelaySeconds: 5138 periodSeconds: 5139```140141### 4. CI/CD pipelines (high)142143**GitHub Actions**:144- pin action versions with SHA: `uses: actions/checkout@<sha>`145- use `concurrency` to cancel outdated runs146- cache dependencies (node_modules, pip cache, Docker layers)147- separate build, test, and deploy jobs148- use environment protection rules for production deploys149- store secrets in GitHub Secrets; never in workflow files150- use matrix builds for multi-version testing151- fail fast on lint/type errors before running tests152- use OIDC for cloud provider authentication (no long-lived keys)153154**Pipeline stages**:1551. Lint + format check1562. Type check1573. Unit tests1584. Build1595. Integration tests1606. Security scan1617. Deploy to staging1628. E2E tests on staging1639. Deploy to production (manual approval)164165### 5. secrets management (critical)166167**Hierarchy** (most to least preferred):1681. Cloud secrets manager (AWS Secrets Manager, GCP Secret Manager)1692. External secrets operator (K8s)1703. CI/CD platform secrets (GitHub Secrets)1714. Encrypted files (SOPS, age)1725. Environment variables (acceptable for non-sensitive config)1736. Hardcoded values (NEVER for secrets)174175- rotate secrets regularly; automate rotation where possible176- audit secret access177- separate secrets by environment178- use short-lived credentials (OIDC, STS) over long-lived keys179180### 6. monitoring (medium)181182- instrument with metrics (Prometheus), logs (structured JSON), and traces (OpenTelemetry)183- define SLIs and SLOs for critical services184- alert on symptoms (error rate, latency), not causes185- use dashboards for context, not primary alerting186- implement health check endpoints for all services187- monitor resource utilization and cost188- set up on-call rotation and escalation policies189190## common fixes191192| problem | fix |193|---------|-----|194| Terraform state drift | `terraform plan` to detect, `terraform import` for unmanaged resources |195| Large Docker image | use multi-stage build, alpine base, .dockerignore |196| Pod CrashLoopBackOff | check logs, verify resource limits, check probes |197| Slow CI pipeline | cache dependencies, parallelize jobs, fail fast |198| Secret in git history | rotate immediately, use git-filter-repo to purge |199| OOM killed pod | increase memory limit or optimize application |200201## CI/CD best practices (from CI/CD handbook patterns)202203### GitHub Actions Advanced Patterns204205**Reusable Workflows**:206```yaml207# .github/workflows/reusable-deploy.yml208on:209 workflow_call:210 inputs:211 environment:212 required: true213 type: string214 secrets:215 AWS_ROLE_ARN:216 required: true217218jobs:219 deploy:220 runs-on: ubuntu-latest221 environment: ${{ inputs.environment }}222 permissions:223 id-token: write # OIDC224 contents: read225 steps:226 - uses: aws-actions/configure-aws-credentials@<sha>227 with:228 role-to-assume: ${{ secrets.AWS_ROLE_ARN }}229```230231**Composite Actions** (reusable steps):232```yaml233# .github/actions/setup-project/action.yml234name: Setup Project235runs:236 using: composite237 steps:238 - uses: actions/setup-python@<sha>239 with:240 python-version: '3.11'241 - run: pip install uv && uv sync242 shell: bash243```244245**Matrix Strategies**:246```yaml247strategy:248 fail-fast: false249 matrix:250 python: ['3.10', '3.11', '3.12']251 os: [ubuntu-latest, macos-latest]252 exclude:253 - python: '3.10'254 os: macos-latest255```256257### Pipeline Optimization Techniques258| Technique | Savings | How |259|-----------|---------|-----|260| Dependency caching | 30-60s | `actions/cache` with hash key |261| Docker layer caching | 1-3min | `docker/build-push-action` with cache |262| Parallel jobs | 40-60% | Split tests, lint independently |263| Conditional runs | Variable | `if: github.event_name == 'push'` |264| Artifact reuse | 30-60s | Build once, deploy to multiple envs |265| Path filters | Variable | Only run when relevant files change |266267## cross-references268269- **security-review** skill: CI/CD security rules270- **DEVOPS_TOOLKIT.md**: Infrastructure tools reference271- **SECURITY_ARSENAL.md**: CI/CD security checklist