Skip to content
Cloud Native

External Secrets Operator: getting credentials out of Git for good

external secrets operator — blue steel door under white clouds during daytime

Six months ago, our high-frequency market-making service choked during a period of extreme volatility. The root cause wasn’t a memory leak or a race condition—it was a API key rotation gone horribly wrong.

Someone had committed an encrypted Ansible vault containing our broker API credentials to a private Git repository. During an emergency key rotation, a merge conflict resulted in half our Kubernetes microservices pulling a stale key while the other half pulled the new one. The trading engine hit rate limits due to mismatched authentication, and we got disconnected from the execution venue for 14 minutes during peak volume.

That was the day I decided to scrub every single credential out of our Git history and eliminate Kubernetes Secret manifests from our GitOps pipelines entirely.

Base64 encoding inside a Secret manifest isn’t encryption. Storing encrypted blobs in Git via SealedSecrets or SOPS works until you need real-time rotations, fine-grained access audits, or centralized access revocation across multiple Kubernetes clusters. We needed a true external source of truth—AWS Secrets Manager—and a reliable, automated bridge to project those credentials into Native Kubernetes Secrets without touching our Git repos.

That bridge is the External Secrets Operator (ESO). Here is how I implemented it, the exact production code we deployed, the hidden traps that broke our staging environment, and the final operational patterns we now use across all our trading clusters.


The Architecture: How ESO Syncs Credentials

Before diving into manifests, let’s establish how External Secrets Operator integrates into a cluster. ESO runs as a controller inside Kubernetes. It introduces custom resource definitions (CRDs)—primarily SecretStore (or ClusterSecretStore) and ExternalSecret—that define where the secrets live externally and how they should be synced locally.

flowchart LR
 appPod["Application Pod"]
 k8sSecret["Kubernetes Secret"]
 esoCtrl["ESO Controller"]
 secretStore["ClusterSecretStore"]
 extSecret["ExternalSecret Manifest"]
 awsSM["AWS Secrets Manager"]

 extSecret -->|"References"| secretStore
 esoCtrl -->|"Watches"| extSecret
 esoCtrl -->|"Fetches Key"| awsSM
 esoCtrl -->|"Creates/Updates"| k8sSecret
 appPod -->|"Mounts or Reads"| k8sSecret

The flow is asynchronous and continuous:
1. You deploy an ExternalSecret manifest alongside your application via ArgoCD or Flux.
2. The ESO Controller intercepts the custom resource, resolves authentication via the referenced ClusterSecretStore using AWS IAM Roles for Service Accounts (IRSA).
3. ESO fetches the secret payload directly from AWS Secrets Manager via the AWS SDK.
4. ESO creates a standard Kubernetes Secret object in the same namespace.
5. Your application pod consumes the native Secret via environment variables or volume mounts.

Git contains zero credential data. It only holds the declarative instruction: “Fetch secret path X from AWS and map key Y to Kubernetes Secret Z.”


Step 1: Configuring Identity-Based Authentication (IRSA)

The biggest mistake I see teams make with ESO is hardcoding static AWS IAM user credentials inside a root Kubernetes secret to authenticate ESO against AWS. Doing that just shifts the secret management problem down one layer.

We use AWS IAM Roles for Service Accounts (IRSA). The ESO pod assumes an IAM role dynamically using an OpenID Connect (OIDC) identity provider token injected by the Kubernetes API server.

Here is the Terraform code to provision the restricted IAM role and policy:

# main.tf – IAM Setup for External Secrets Operator IRSA

data “aws_caller_identity” “current” {}
data “aws_region” “current” {}

resource “aws_iam_role” “eso_role” {
name = “eso-secrets-manager-role”

assume_role_policy = jsonencode({
Version = “2012-10-17”
Statement = [
{
Effect = “Allow”
Principal = {
Federated = “arn:aws:iam::${data.aws_caller_identity.current.account_id}:oidc-provider/oidc.eks.${data.aws_region.current.name}.amazonaws.com/id/EXAMPLED3B7651C0”
}
Action = “sts:AssumeRoleWithWebIdentity”
Condition = {
StringEquals = {
“oidc.eks.${data.aws_region.current.name}.amazonaws.com/id/EXAMPLED3B7651C0:sub” : “system:serviceaccount:external-secrets:external-secrets”
}
}
}
]
})
}

resource “aws_iam_policy” “eso_policy” {
name = “eso-secrets-manager-policy”
description = “Allows ESO to fetch secrets from AWS Secrets Manager for production environments”

policy = jsonencode({
Version = “2012-10-17”
Statement = [
{
Effect = [
“Allow”
]
Action = [
“secretsmanager:GetSecretValue”,
“secretsmanager:DescribeSecret”
]
Resource = [
“arn:aws:secretsmanager:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:secret:prod/trading/*”
]
}
]
})
}

resource “aws_iam_role_policy_attachment” “eso_attach” {
role = aws_iam_role.eso_role.name
policy_arn = aws_iam_policy.eso_policy.arn
}

Notice the Resource block in the IAM policy. We lock down the operator so it can only read secrets starting with the path prod/trading/. If a developer attempts to sync a secret outside this prefix, AWS rejects the request at the API level.


Step 2: Deploying the ClusterSecretStore

Next, we define the ClusterSecretStore. This cluster-scoped resource instructs ESO how to reach AWS Secrets Manager using the service account linked to the IAM role created above.

# cluster-secret-store.yaml
apiVersion: external-secrets.io/v1beta1
kind: ClusterSecretStore
metadata:
name: aws-secretsmanager
spec:
provider:
aws:
service: SecretsManager
region: us-east-1
auth:
jwt:
serviceAccountRef:
name: external-secrets
namespace: external-secrets

Apply this manifest to your cluster:

kubectl apply -f cluster-secret-store.yaml

Verify that the store is active and healthy:

kubectl get clustersecretstore aws-secretsmanager -o wide
text
NAME AGE STATUS READY
aws-secretsmanager 42s Valid True

If READY reads False, check your OIDC issuer URL and ensure the service account name matches your IAM assume-role policy condition exactly.


Step 3: Defining the ExternalSecret Resource

Now, we create the secret definition. We store our database URI and market-data API credentials inside AWS Secrets Manager as a single JSON string under the key prod/trading/execution-engine:

{
“DB_PASSWORD”: “mypassword123!”,
“API_KEY”: “fix-prod-883920192-x9”,
“API_SECRET”: “c8091f1b2d43e5e4129a0021”
}

Here is the ExternalSecret manifest that lives inside our application code repository.

# external-secret.yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: execution-engine-credentials
namespace: trading
spec:
refreshInterval: “1h”
secretStoreRef:
name: aws-secretsmanager
kind: ClusterSecretStore
target:
name: execution-engine-secrets
creationPolicy: Owner
deletionPolicy: Retain
dataFrom:
– extract:
key: prod/trading/execution-engine

Let’s break down key parameters in this file:
– refreshInterval: ESO polls AWS Secrets Manager every 1 hour to look for updated key versions.
– creationPolicy: Owner: The generated Kubernetes Secret is bound to the lifecycle of this ExternalSecret. If you delete the ExternalSecret, the underlying native Kubernetes Secret is cleaned up.
– deletionPolicy: Retain: If the secret is deleted in AWS Secrets Manager, ESO will not immediately destroy the native Kubernetes secret. This prevents immediate cascading application failures if someone accidentally deletes a remote key.
– dataFrom.extract: Instructs ESO to parse the remote JSON string and map each key-value pair directly into the Kubernetes Secret data keys.

Deploy the manifest and observe the operator’s execution:

kubectl apply -f external-secret.yaml -n trading

To verify the sync:

kubectl get externalsecret execution-engine-credentials -n trading
text
NAME STORE REFRESH INTERVAL STATUS READY
execution-engine-credentials aws-secretsmanager 1h SecretSynced True

Inspect the generated target Kubernetes Secret:

kubectl get secret execution-engine-secrets -n trading -o yaml
yaml
apiVersion: v1
data:
API_KEY: Zml4LXByb2QtODgzOTIwMTkyLXg5
API_SECRET: YzgwOTFmMWIyZDQzZTVlNDEyOWEwMDIx
DB_PASSWORD: bXlwYXNzd29yZDEyMyE=
kind: Secret
metadata:
creationTimestamp: “2024-10-12T14:22:18Z”
name: execution-engine-secrets
namespace: trading
type: Opaque

Automated Key Rotation with Kubernetes Pod Invalidation

Getting secrets into Kubernetes safely is only half the battle. What happens when you rotate an API key in AWS Secrets Manager?

ESO will fetch the new secret during its refreshInterval loop and update the native target Secret resource in Kubernetes. However, Kubernetes environment variables mounted from secrets do not update in running container processes automatically. Volume-mounted secrets update eventually (due to kubelet sync loops), but application runtimes rarely watch file systems for change events.

If you don’t handle pod reloading, your application will happily keep using stale credentials until the next pod restart.

We solved this by pairing ESO with Reloader, an open-source controller that watches for changes in Kubernetes Secret objects and triggers a rolling update on dependent Deployments or StatefulSets.

Here is a complete, production-ready application deployment manifest using this pattern:

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: execution-engine
namespace: trading
annotations:
secret.reloader.stakater.com/reload: “execution-engine-secrets”
spec:
replicas: 3
selector:
matchLabels:
app: execution-engine
template:
metadata:
labels:
app: execution-engine
spec:
containers:
– name: engine
image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/trading/engine:v2.4.1
envFrom:
– secretRef:
name: execution-engine-secrets
resources:
limits:
cpu: “2”
memory: “4Gi”
requests:
cpu: “1”
memory: “2Gi”

When ESO fetches a rotated credential from AWS, it updates execution-engine-secrets. Reloader detects the resourceVersion mutation on the target secret, sees the annotation on the Deployment, and performs a zero-downtime rolling release of the execution-engine pods.


Programmatic Verification: A Custom Secret Health Checker

To prevent silent sync failures in production, we written a Python script running as an in-cluster monitoring CronJob. It uses the official Kubernetes Python Client to continuously scan all ExternalSecret custom resources, flags unsynced secrets, and outputs Prometheus metrics.

# secret_health_checker.py
import sys
import logging
from kubernetes import client, config

logging.basicConfig(level=logging.INFO, format=“%(asctime)s [%(levelname)s] %(message)s”)

def check_external_secrets():
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()

custom_api = client.CustomObjectsApi()

group = “external-secrets.io”
version = “v1beta1”
plural = “externalsecrets”

logging.info(“Scanning cluster for ExternalSecret resources…”)

try:
secrets = custom_api.list_cluster_custom_object(
group=group,
version=version,
plural=plural
)
except client.exceptions.ApiException as e:
logging.error(f”Failed to query ExternalSecrets API: {e}”)
sys.exit(1)

unready_count = 0
total_count = len(secrets.get(“items”, []))

for item in secrets.get(“items”, []):
name = item[“metadata”][“name”]
namespace = item[“metadata”][“namespace”]
status = item.get(“status”, {})
conditions = status.get(“conditions”, [])

is_ready = False
for cond in conditions:
if cond.get(“type”) == “Ready” and cond.get(“status”) == “True”:
is_ready = True
break

if not is_ready:
logging.error(f”UNHEALTHY SECRET: Namespace='{namespace}’, Name='{name}’ is not in Ready state.”)
unready_count += 1
else:
logging.info(f”HEALTHY: Namespace='{namespace}’, Name='{name}’ is synchronized.”)

logging.info(f”Scan complete. Total: {total_count}, Unhealthy: {unready_count}”)

if unready_count > 0:
sys.exit(1)

if __name__ == “__main__”:
check_external_secrets()

When executed inside our clusters, the script generates output like this:

2024-10-12 15:01:02,112 [INFO] Scanning cluster for ExternalSecret resources…
2024-10-12 15:01:02,145 [INFO] HEALTHY: Namespace=’trading’, Name=’execution-engine-credentials’ is synchronized.
2024-10-12 15:01:02,152 [INFO] HEALTHY: Namespace=’risk’, Name=’risk-model-db-pass’ is synchronized.
2024-10-12 15:01:02,158 [ERROR] UNHEALTHY SECRET: Namespace=’analytics’, Name=’clickhouse-auth’ is not in Ready state.
2024-10-12 15:01:02,159 [INFO] Scan complete. Total: 3, Unhealthy: 1

If the process exits with status code 1, our alert manager routes a page to the on-call engineer before an unready secret breaks a downstream service deployment.


Real-World Edge Cases and Dead Ends

Migrating dozens of microservices away from Git-stored credentials to ESO was not without friction. We ran into three major failures during the transition.

1. The Rate-Limiting Wall (AWS API Throttling)

In our early test environment, we set refreshInterval on 120 ExternalSecret manifests to 10s. Within minutes, AWS Secrets Manager hit us with ThrottlingException errors. AWS limits GetSecretValue requests to 10,000 requests per second, but AWS KMS (which decrypts the secret value) has much tighter regional limits depending on your tier.

The Fix: Increase the refreshInterval to at least 1h for standard credentials. If you need instantaneous secret updates during emergency rotations, use webhooks or manually trigger an ESO refresh via annotation rather than aggressive polling:

kubectl annotate es execution-engine-credentials force-sync=“$(date +%s)“ –overwrite -n trading

2. Multi-line Key Formats in JSON Payloads

When storing SSH private keys or TLS certificates in AWS Secrets Manager, newline characters (\n) frequently get escaped incorrectly when converted from string to JSON. When ESO synced the JSON object to a native Kubernetes secret, applications choked because the mounted RSA key had literal \n characters instead of actual carriage returns.

The Fix: Use the template engine built into ESO. Rather than directly extracting raw keys, instruct ESO to re-render the field:

spec:
target:
name: tls-keys-secret
template:
engineVersion: v2
data:
server.crt: “{{ .raw_cert | replace \”\\n\” \”\n\” }}”

3. Namespace Isolation Creep

We initially configured a single global ClusterSecretStore that had permissions to fetch any path in AWS Secrets Manager. This created a major security vulnerability: a developer with access to apply an ExternalSecret manifest in a sandbox namespace could simply point the key field to prod/trading/execution-engine and read production secrets directly.

The Fix: Switch from a permissive global ClusterSecretStore to namespace-scoped SecretStore manifests combined with strict IAM boundaries mapped to Kubernetes service accounts.


Results and Final Lessons

Moving credential delivery entirely to External Secrets Operator fundamentally changed our posture:

  1. Clean Git Repos: We ran git-filter-repo to purge historical encrypted blobs across all engineering repositories. Our CI/CD pipelines no longer carry master encryption keys or decryption binaries (SOPS/Ansible Vault).
  2. Deterministic Rotations: Credential rotation time dropped from a manual, multi-step 30-minute process to under 20 seconds. Updating the secret in AWS Secrets Manager now triggers an instant target secret rewrite and a rolling deployment restart via Reloader.
  3. Audit Trail Consolidation: Security teams no longer ask who had access to encrypted repository files. They monitor AWS CloudTrail for GetSecretValue events executed by the single EKS IRSA role ARN.

External Secrets Operator turns secret management in Kubernetes from a brittle manual chore into stable, self-healing infrastructure. Decouple your code from your secrets entirely: let Git manage your state, let your cloud provider manage your keys, and let ESO bridge the gap.

Join the conversation

Your email address will not be published. Required fields are marked *