Secrets Scanning Automation

Production-grade guide to secrets scanning automation covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Secrets Scanning Automation is the continuous, automated process of discovering, validating, and securing sensitive credentials—API keys, database passwords, encryption keys, service account tokens—across codebases, containers, infrastructure-as-code, and runtime environments. It matters when secrets leak into version control, configuration files, or deployment manifests, and when changes to infrastructure or applications introduce new secrets without auditing or rotation.

Discovering Secrets in Source Code

Automated secrets scanning begins with scanning source code repositories for hardcoded credentials. This task is most effective when triggered on every pull request and on every commit to main.

Use git grep with a curated list of secret patterns and a custom script to extract candidate secrets from code files.


git grep -l -E '([A-Za-z0-9_]+[ \t]*=|"[A-Za-z0-9_]+")[ \t]*[[:space:]]*["\'][^"\']*["\'][ \t]*[[:space:]]*[[:alnum:]]+["\'][ \t]*' \
  --include="*.py" --include="*.json" --include="*.yaml" --include="*.yml" --include="*.env" --include="*.tf" \
  --files-with-matches

The output includes paths to files containing potential secrets. These files are then passed to a scanning tool that applies regular expressions and context-aware logic.

A common failure is missing secrets that appear in comment blocks or within multi-line strings. To detect these, use rg (ripgrep) with a pattern that matches key-value pairs across line boundaries:

rg -l --multiline --pcre2 \
  '(["''])([A-Za-z0-9_]+)\1\s*[:=]\s*(["''])([^"\n]*?)(["''])' \
  --type=python --type=json --type=yaml --type=env --type=tf

The --multiline flag enables matching across newlines, while --pcre2 supports Perl-compatible regex syntax, allowing for more expressive patterns.

After extraction, the tool generates a structured output in JSON:

{
  "scans": [
    {
      "file": "src/config.py",
      "line": 42,
      "key": "DATABASE_PASSWORD",
      "value": "s3cr3t_p@ssw0rd",
      "context": "DATABASE_PASSWORD = \"s3cr3t_p@ssw0rd\" # from AWS RDS",
      "confidence": 0.92,
      "type": "hardcoded"
    }
  ]
}

Each scan result includes confidence scores derived from pattern matching, value entropy, and context clues.

Validating Secrets in Configuration Files

Once extracted, secrets must be validated against known formats and patterns. The most common validation is checking for known secret types: AWS credentials, Google Cloud service account keys, SSH private keys, and JWT tokens.

Use jq to process and validate JSON configuration files:

jq -r '
  . | 
  [paths | select(. | type == "string" and . == "AWS_ACCESS_KEY_ID" or . == "AWS_SECRET_ACCESS_KEY")] |
  . as $keys |
  [range(0; length) | . as $i | $keys[$i] | {
    key: .,
    value: . | getpath(.),
    type: select(. == "AWS_ACCESS_KEY_ID") | "aws-access-key",
    format: if . == "AWS_ACCESS_KEY_ID" then "string" else "string" end
  ] |
  . | map(select(.value | length > 8 and . | test("^[A-Z0-9]{12,16}$"))) |
  . | sort_by(.key)
' config.json

This pipeline identifies all keys that match AWS credential patterns and filters for values with at least 12 characters, all uppercase letters and digits. It outputs a list of validated secrets with metadata.

For YAML files, use yq (https://mikefarah.gitbook.io/yq) to extract and validate secrets:

yq -r '
  . | 
  to_entries | 
  map(select(.key | test("^[A-Z_]+") and .value | type == "string")) |
  map(select(.value | length > 10 and .value | test("[A-Z][a-z]+") and .value | test("\\d+"))) |
  map({
    key: .key,
    value: .value,
    type: if .key | test("AWS") then "aws" elif .key | test("GCP") then "gcp" else "generic" end,
    length: .value | length,
    has_digits: .value | test("\\d+"),
    has_uppercase: .value | test("[A-Z]+")
  }) |
  . | sort_by(.key)
' config.yaml

A common failure mode is validating secrets in deeply nested structures. The tool must traverse nested objects and arrays, and report the full path to the secret.

Scanning Runtime Environments

Secrets are not only in code but also in running systems. Scanning runtime environments involves reading secrets from environment variables, configuration files, and secrets stores.

Use kubectl to extract secrets from Kubernetes clusters:

kubectl get secrets -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.data}{"\n"}{end}'

This command outputs a tab-separated list of namespace, secret name, and base64-encoded data. The data can be decoded and parsed:

kubectl get secrets -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.data}{"\n"}{end}' |
  while IFS=$'\t' read -r namespace name data; do
    echo "Namespace: $namespace"
    echo "Secret: $name"
    echo "$data" | base64 -d | jq -r 'to_entries[] | .key as $key | .value as $value | {
      key: $key,
      value: $value,
      length: $value | length,
      is_jwt: $value | test("^[A-Za-z0-9_]+\\.[A-Za-z0-9_]+\\.[A-Za-z0-9_]+$")
    }'
  done

This pipeline validates JWT tokens, extracts secret values, and reports their length and format.

For Docker containers, use docker inspect and docker exec to retrieve secrets from running containers:

docker inspect --format='{{range $k, $v := .Config.Env}}{{$k}}: {{$v}}\n{{end}}' <container-id>

To validate secrets within the container filesystem:

docker exec <container-id> find /etc/secrets -type f -exec cat {} \; | grep -E '([A-Za-z0-9_]+[ \t]*=|"[A-Za-z0-9_]+")[ \t]*[[:space:]]*["\'][^"\']*["\'][ \t]*[[:alnum:]]+["\'][ \t]*'

The scanning process fails silently when a container is not running or when secrets are stored in non-standard directories.

Automating Secret Rotation and Alerts

After scanning, secrets must be rotated and alerts raised when new or sensitive secrets are detected.

Use a CI/CD pipeline with git, curl, and jq to automate rotation.

When a new secret is detected, create a pull request with a rotation plan:

#!/bin/bash
# generate-rotation-pr.sh
set -euo pipefail

NEW_SECRET=$(cat << EOF
{
  "key": "SLACK_WEBHOOK_URL",
  "value": "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
  "source": "src/config.py:42",
  "type": "webhook",
  "age_days": 180,
  "rotation_required": true
}
EOF
)

# Create a PR title and body
PR_TITLE="Secret: $NEW_SECRET | SLACK_WEBHOOK_URL"
PR_BODY=$(cat << EOF
## New Secret Detected

- **Key**: SLACK_WEBHOOK_URL
- **Value**: $(echo "$NEW_SECRET" | jq -r '.value')
- **Source**: $(echo "$NEW_SECRET" | jq -r '.source')
- **Age**: $(echo "$NEW_SECRET" | jq -r '.age_days') days
- **Type**: $(echo "$NEW_SECRET" | jq -r '.type')

### Rotation Plan

1. Generate a new webhook URL in Slack.
2. Update the value in `src/config.py`.
3. Deploy the change.
4. Validate in staging.
5. Promote to production.

### Required Actions

- [ ] Update secret in AWS Secrets Manager
- [ ] Update secret in Kubernetes
- [ ] Notify team via Slack
- [ ] Log in audit system
EOF
)

# Use GitHub API to create pull request
curl -X POST \
  -H "Authorization: Bearer $GITHUB_TOKEN" \
  -H "Accept: application/vnd.github.v3+json" \
  -d "{
    \"title\": \"$PR_TITLE\",
    \"body\": \"$PR_BODY\",
    \"head\": \"secret-rotation\",
    \"base\": \"main\",
    \"labels\": [\"secret\", \"rotation\"]
  }" \
  https://api.github.com/repos/organization/project/pulls

This script creates a pull request with a detailed plan and checklist, ensuring consistency across teams.

When a secret is rotated, update all known locations:

# Update secret in AWS Secrets Manager
aws secretsmanager put-secret-value \
  --secret-id "app/staging/slack-webhook" \
  --secret-string "{\"SLACK_WEBHOOK_URL\": \"https://hooks.slack.com/services/T00000000/B00000000/YYYYYYYYYYYYYYYYYYYYYYYY\"}" \
  --region us-east-1

# Update in Kubernetes
kubectl create secret generic slack-webhook \
  --from-literal=SLACK_WEBHOOK_URL="https://hooks.slack.com/services/T00000000/B00000000/YYYYYYYYYYYYYYYYYYYYYYYY" \
  --namespace staging \
  --dry-run=client -o yaml | kubectl apply -f -

The most common failure is missing secrets in the secret-string field of AWS Secrets Manager. The put-secret-value command expects a JSON string, not a raw key-value map, and fails silently when the JSON is malformed.

Detecting Secrets in Infrastructure-as-Code

Infra-as-code files often contain secrets that are not versioned or rotated. Scanning these files is essential.

Use terraform and jq to extract secrets from .tf files:

terraform show -json -module-depth 2 | jq -r '
  .values.root_module.resources[] |
  select(.type == "aws_s3_bucket" or .type == "aws_lambda_function") |
  .values | to_entries[] |
  select(.key | test("^[A-Z_]+") and .value | type == "string") |
  select(.value | length > 10 and .value | test("\\d+")) |
  {
    resource: .parent.type,
    attribute: .key,
    value: .value,
    source: .parent.provider,
    length: .value | length
  }
'

This extracts all string values from S3 buckets and Lambda functions, filters for long, digit-containing values, and outputs a list of secrets with their context.

For docker-compose.yml, use yq to extract secrets:

yq -r '
  .services | to_entries[] | 
  .value.env_file as $env_files |
  .value.environment as $env_vars |
  ([$env_files[], $env_vars[]] | flatten) |
  map(select(. | type == "string" and . | test("^[A-Z_]+"))) |
  map({
    service: .key,
    variable: .value,
    value: .value,
    source: if .value | test("^[A-Z_]+") then "env_file" else "environment" end
  })
' docker-compose.yml

A common failure is missing secrets that are defined in env_file but not included in the docker-compose.yml file. The scanner must resolve relative paths and read the actual files.

Summary of Failure Modes

Secrets scanning automation is not a one-off task. It is a continuous, multi-stage process that requires attention to detail, validation, and feedback. Its success depends on a consistent pipeline that discovers, validates, rotates, and alerts on secrets across every layer of the software stack.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.