Part 6 ยท Chapter 21

Security & Secrets: Locking the Doors

HashiCorp Vault, Trivy container scanning, and DevSecOps โ€” security baked in at every stage, not bolted on at the end.

What you'll learn in this chapter

  • Why secrets management is the most critical security discipline in DevOps
  • HashiCorp Vault โ€” storing, accessing, and rotating secrets
  • Vault in Kubernetes with the Agent Injector
  • Trivy โ€” scanning container images for vulnerabilities
  • SAST (Static Application Security Testing) in CI pipelines
  • The OWASP Top 10 for DevOps engineers
  • Network security best practices

The Castle with Many Walls

A medieval castle's defences weren't just a single wall โ€” it had a moat, a drawbridge, outer walls, inner walls, a keep, and guards checking identity at each gate. If one layer failed, the next one caught the attacker. This is defence in depth.

Modern software security works the same way. DevSecOps means "Development + Security + Operations" โ€” security is not the security team's job alone. Developers write secure code. CI pipelines scan for vulnerabilities. Production systems are monitored for threats. Every layer assumes the others might fail.

The Secrets Crisis โ€” The #1 Real-World Breach

The most common path to a production breach is embarrassingly simple: a developer commits a secret to a public Git repository.

  • A password hardcoded in source code โ†’ committed โ†’ pushed โ†’ GitHub โ†’ found by a scanner โ†’ credentials compromised
  • AWS keys in a .env file accidentally committed โ†’ found by a bot in minutes โ†’ $50,000 AWS bill (this happens regularly)
  • An API key in a shell script โ†’ leaked via the CI logs โ†’ used to exfiltrate data
โš ๏ธ The Golden Rule of Secrets

A secret that has ever been committed to Git must be considered compromised. Even if you delete it in the next commit, it's in the git history. Even if the repo is private, it may have been cloned or forked. Rotate it immediately.

HashiCorp Vault โ€” The Secret Keeper

Vault is the industry-standard secrets management tool. Think of it as a bank vault for your app's sensitive data. It:

  • Stores secrets encrypted at rest (AES-256)
  • Provides fine-grained access control (Service A can read DB passwords, not API keys)
  • Generates dynamic secrets โ€” temporary database credentials that expire
  • Audits every secret access (who accessed what, when, from where)
  • Automatically rotates secrets on a schedule

Core Concepts

  • Secret Engine: a plugin for a secret type (KV store, database credentials, AWS IAM, PKI certificates)
  • Auth Method: how a client proves identity to Vault (Kubernetes service account, AWS IAM, GitHub token, AppRole)
  • Policy: a document defining what a client can do after authenticating
  • Lease: time-limited access to a dynamic secret โ€” auto-revoked on expiry

Basic Vault CLI Usage

# Start a dev server (testing only โ€” data not persisted)
vault server -dev

# Set environment
export VAULT_ADDR='http://127.0.0.1:8200'
export VAULT_TOKEN='root'

# Write a secret (KV v2 engine)
vault kv put secret/myapp/production \
  DB_PASSWORD="supersecret" \
  API_KEY="sk-abc123"

# Read the secret
vault kv get secret/myapp/production

# Read a single field
vault kv get -field=DB_PASSWORD secret/myapp/production

# List secrets under a path
vault kv list secret/myapp/

# Delete a secret version
vault kv delete secret/myapp/production

Dynamic Database Credentials

Dynamic secrets are Vault's superpower. Instead of sharing a long-lived database password with every service, Vault creates a temporary database user on-demand with a 1-hour expiry. When the lease expires, Vault revokes the credentials automatically.

# Enable the database secrets engine
vault secrets enable database

# Configure the PostgreSQL connection
vault write database/config/postgres \
  plugin_name=postgresql-database-plugin \
  connection_url="postgresql://{{username}}:{{password}}@postgres:5432/mydb" \
  allowed_roles="my-role" \
  username="vault-admin" \
  password="vault-admin-pass"

# Create a role that generates temporary users
vault write database/roles/my-role \
  db_name=postgres \
  creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';" \
  default_ttl="1h" \
  max_ttl="24h"

# Get dynamic credentials (creates a temporary DB user)
vault read database/creds/my-role
# username: v-my-role-AbcDeFg...
# password: A1b2C3d4...
# lease_duration: 1h0m0s

Vault in Kubernetes โ€” Agent Injector

The Vault Agent Injector automatically injects secrets as files into your pods via annotations. No changes to your app code โ€” it just reads files at startup.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  template:
    metadata:
      annotations:
        vault.hashicorp.com/agent-inject: "true"
        vault.hashicorp.com/role: "my-app-role"
        vault.hashicorp.com/agent-inject-secret-config: "secret/myapp/production"
        vault.hashicorp.com/agent-inject-template-config: |
          {{- with secret "secret/myapp/production" -}}
          export DB_PASSWORD="{{ .Data.data.DB_PASSWORD }}"
          export API_KEY="{{ .Data.data.API_KEY }}"
          {{- end }}
    spec:
      containers:
        - name: app
          image: myapp:1.0
          command: ["/bin/sh", "-c"]
          args: ["source /vault/secrets/config && node server.js"]

Trivy โ€” Container Security Scanning

Trivy is an open-source security scanner for container images, filesystems, and Git repositories. It checks for:

  • OS packages with known CVEs (e.g., old OpenSSL with a public exploit)
  • Language packages (npm, pip, Maven, Cargo) with known vulnerabilities
  • Misconfigurations in Dockerfiles and Kubernetes manifests
  • Secrets accidentally committed to repositories
# Install Trivy
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh \
  | sh -s -- -b /usr/local/bin

# Scan a container image
trivy image myapp:1.0

# Fail CI if CRITICAL vulnerabilities found
trivy image --exit-code 1 --severity CRITICAL myapp:1.0

# Scan all severities, ignore unfixable
trivy image --ignore-unfixed --severity HIGH,CRITICAL myapp:1.0

# Scan filesystem (your source code + dependencies)
trivy fs .

# Scan Kubernetes manifests for misconfigs
trivy config ./k8s/

# Output JSON for CI integration
trivy image --format json --output trivy-results.json myapp:1.0

Trivy in GitHub Actions

- name: Scan image for vulnerabilities
  uses: aquasecurity/trivy-action@master
  with:
    image-ref: 'myapp:${{ github.sha }}'
    format: 'sarif'
    output: 'trivy-results.sarif'
    severity: 'CRITICAL,HIGH'
    exit-code: '1'

- name: Upload results to GitHub Security tab
  uses: github/codeql-action/upload-sarif@v3
  if: always()   # upload even if scan failed
  with:
    sarif_file: 'trivy-results.sarif'

SAST โ€” Static Application Security Testing

SAST tools analyse your source code for security issues before deployment. No running app required โ€” they read the code like a security-focused code reviewer.

  • Semgrep: open source, extremely fast, highly customisable rule sets. semgrep --config p/owasp-top-ten .
  • SonarQube: comprehensive, tracks technical debt and security hotspots over time
  • Snyk: developer-friendly, integrates with GitHub/GitLab, scans code and dependencies
  • GitHub Advanced Security: CodeQL for deep semantic analysis, built into GitHub

The OWASP Top 10

The Open Web Application Security Project publishes the 10 most critical web application security risks. A DevOps engineer must know these because they affect architecture, deployment, and pipeline decisions:

  1. Broken Access Control โ€” users doing things they shouldn't (most common finding)
  2. Cryptographic Failures โ€” weak or missing encryption at rest or in transit
  3. Injection โ€” SQL injection, command injection, LDAP injection
  4. Insecure Design โ€” fundamental architectural flaws that patches can't fix
  5. Security Misconfiguration โ€” default passwords, overly permissive security groups, exposed admin panels
  6. Vulnerable & Outdated Components โ€” using libraries with known CVEs
  7. Identification & Authentication Failures โ€” weak session management, no MFA
  8. Software & Data Integrity Failures โ€” unverified updates, unsafe CI pipeline dependencies
  9. Security Logging & Monitoring Failures โ€” not knowing you've been breached
  10. Server-Side Request Forgery (SSRF) โ€” server makes requests on behalf of an attacker

Network Security Best Practices

  • Only open ports that are needed. Close everything else in security groups and firewalls.
  • Never expose databases to the public internet. Place them in private subnets.
  • Restrict SSH access to specific IP addresses, or use AWS Systems Manager Session Manager (no open port 22).
  • Use VPN or AWS VPC Peering for internal service-to-service communication across accounts.
  • Enable AWS CloudTrail and GuardDuty โ€” audit logs and threat detection.
  • Rotate SSH keys, API keys, and database passwords regularly.
  • Enable MFA on all cloud accounts, especially root/admin accounts.
๐ŸŽ‰ The Reality of Breaches

The most common real-world breaches come from misconfigurations (public S3 buckets, wide-open security groups) and hardcoded credentials โ€” not sophisticated zero-day exploits. Basic hygiene prevents the vast majority of incidents. Security doesn't have to be complex to be effective at the first, most important layer.

Chapter Summary

  • Never hardcode secrets โ€” use Vault, AWS Secrets Manager, or GitHub Secrets
  • A secret committed to Git is compromised โ€” rotate it immediately
  • Vault provides dynamic secrets (temporary, auto-expiring credentials) โ€” the safest model
  • Trivy scans container images and source code for known CVEs and misconfigurations
  • Add Trivy to CI and fail the build on CRITICAL findings
  • SAST tools (Semgrep, Snyk) catch security bugs in source code before deployment
  • Know the OWASP Top 10 โ€” they represent the most common real-world attack vectors