Skip to content
Cloud Native

cert-manager and Let’s Encrypt: TLS automation and the renewal that silently failed

cert-manager — A large stack of containers sitting on top of each other

It was 02:15 UTC on a Tuesday when our production FIX gateway edge proxies began dropping TLS handshakes. Institutional clients executing high-frequency order flows started flooding our pager rotation with handshake_failure alerts.

I jumped onto the primary Kubernetes cluster to inspect the ingress layer. The TLS certificate serving our gateway endpoint had expired 12 minutes prior.

We had been using cert-manager alongside Let’s Encrypt for TLS automation for over a year. The core promise of cloud-native certificate management is that once configured, you never think about expiration dates again. Yet there I was, staring at an expired X.509 certificate while active trading sessions collapsed around us.

The failure was insidious: cert-manager had attempted to renew the certificate 30 days prior, encountered an edge-case configuration bug, failed silently without firing alert manager triggers, and left the stale certificate serving live traffic until the hard expiration date.

Here is the post-mortem of how our TLS automation broke, how to debug cert-manager deep in the Kubernetes control plane, the code required to fix it, and how to build absolute observability around your Let’s Encrypt renewals.


The Root Cause: ACME HTTP-01, Ingress Paths, and Silent Loops

Our architecture relied on cert-manager executing an ACME HTTP-01 challenge against Let’s Encrypt. When a renewal triggers, cert-manager creates a temporary solver Pod and an Ingress rule to route .well-known/acme-challenge/<TOKEN> traffic to that solver.

Here is how the automated validation flow was supposed to execute versus where it broke:

flowchart TD
 CM["cert-manager Operator"]
 CR["Certificate CustomResource"]
 SOLV["ACME Solver Pod"]
 ING["Nginx Ingress Controller"]
 LE["Lets Encrypt CA"]

 CM -->|"1. Watches CR"| CR
 CM -->|"2. Provisions"| SOLV
 CM -->|"3. Modifies"| ING
 LE -->|"4. Queries HTTP-01"| ING
 ING -->|"5. Fails to Route"| SOLV

The underlying issue stemmed from an interaction between our Nginx Ingress annotation overrides and how cert-manager injects the solver path.

We enforced strict path matching (path-type: Exact) and a custom snippet for mutual TLS (mTLS) optional passthrough on our primary ingress manifest. When cert-manager automatically generated the challenge Ingress resource, it merged annotations from the parent Ingress. The mTLS snippet forced the incoming Let’s Encrypt validation probe to present a client certificate—which Let’s Encrypt servers obviously do not do.

Let’s Encrypt received a 403 Forbidden on every validation attempt.

Because the Certificate resource status continuously cycled between Pending and Retrying, it never entered a Failed terminal state. Our Prometheus rules were watching for certmanager_certificate_expiration_timestamp_seconds, but due to a metrics cardinality reset during a cluster upgrade three weeks prior, the alert rule query target was detached. The renewal was silently failing in a continuous backoff loop for 30 days straight.


Technical Reconstruction and Debugging

To diagnose why cert-manager was failing to solve the challenge, I had to dump the state of the custom resources: Certificate, CertificateRequest, Order, and Challenge.

First, I checked the high-level certificate status:

kubectl get certificate fix-gateway-tls -n trading –output yaml
yaml
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: fix-gateway-tls
namespace: trading
status:
conditions:
– lastTransitionTime: “2024-01-15T02:00:00Z”
message: Certificate is up to date and valid
reason: Ready
status: “False”
type: Ready
renewalTime: “2024-02-14T02:00:00Z”

The resource indicated it was not ready, but to see why, we must trace down to the Challenge layer. Cert-manager abstracts ACME into orders and challenges:

kubectl get challenges -n trading -o wide
text
NAME STATE DOMAIN AGE
fix-gateway-tls-1-39201948-28391048 pending fix.prod.example.com 29d

Inspecting the challenge resource directly revealed the exact HTTP status code returned by our edge proxy to the Let’s Encrypt validation engine:

kubectl describe challenge fix-gateway-tls-1-39201948-28391048 -n trading
text
Status:
Presented: true
Processing: true
Reason: Waiting for HTTP-01 challenge propagation: wrong status code ‘403’ received when querying http://fix.prod.example.com/.well-known/acme-challenge/7a8f9b1c2d3e4f5
Events:
Type Reason Age From Message
—- —— —- —- ——-
Normal Started 29d cert-manager Created challenge solver pod
Warning SelfCheckFailed 29d (x4120 over 29d) cert-manager Failed to perform self check GET request: got 403 status code

The self-check loop was stuck. Cert-manager will not notify Let’s Encrypt to validate the token until its internal pre-flight self-check succeeds. Because our Ingress annotations enforced client-cert verification across all subpaths, cert-manager’s own self-check received a 403 Forbidden from Nginx, hanging the pipeline indefinitely.


The Fix: Decoupling ACME Challenges and Enforcing DNS-01

Relying on HTTP-01 challenges on sensitive, custom-annotated edge Ingress resources creates an architectural coupling vulnerability. If your Ingress rules change, your TLS renewal mechanism can break.

We made two concrete changes:
1. Switched our production issuing strategy from HTTP-01 to DNS-01 using AWS Route53. This completely bypasses the Ingress layer, Nginx annotations, and public HTTP routing.
2. Implemented explicit resource isolation via dedicated ClusterIssuer objects and robust fallback monitoring.

1. Production ClusterIssuer Manifest (DNS-01 via IAM Roles for Service Accounts)

Using IAM Roles for Service Accounts (IRSA) on EKS eliminates the need for long-lived AWS API keys inside Kubernetes secrets.

apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod-dns01
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: [email protected]
privateKeySecretRef:
name: letsencrypt-prod-account-key
solvers:
– dns01:
route53:
region: us-east-1
hostedZoneID: Z01928374829374928374
role: arn:aws:iam::123456789012:role/cert-manager-route53-issuer

2. Upgraded Certificate Custom Resource

We updated the Certificate specification to use the new issuer and explicitly defined duration and renewBefore parameters to allow a wider window for failure resolution.

apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: fix-gateway-tls
namespace: trading
spec:
secretName: fix-gateway-tls-secret
duration: 2160h # 90 days
renewBefore: 720h # 30 days
subject:
organizations:
– Trading Infrastructure Group
commonName: fix.prod.example.com
dnsNames:
– fix.prod.example.com
issuerRef:
name: letsencrypt-prod-dns01
kind: ClusterIssuer
group: cert-manager.io

Solving the Observability Gap

To ensure we never suffer another silent failure, relying on cert-manager’s internal metrics is insufficient. We constructed a two-tier monitoring mechanism:

  1. Prometheus Rules targeting certmanager_certificate_expiration_timestamp_seconds.
  2. A custom Python controller running out-of-band that parses active TLS sockets on the network boundary and asserts expiration delta against live endpoints.

Prometheus Alerting Rules

Deploy this PrometheusRule to fire alerts long before a certificate reaches its expiration window, specifically catching certificates trapped in broken renewal loops.

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: cert-manager-alerts
namespace: monitoring
spec:
groups:
– name: cert-manager.rules
rules:
– alert: CertManagerCertificateExpirationEndingSoon
expr: |
(certmanager_certificate_expiration_timestamp_seconds – time()) / 86400 < 14
for: 1h
labels:
severity: critical
tier: platform
annotations:
summary: “Certificate {{ $labels.name }} expires in less than 14 days”
description: “Certificate {{ $labels.name }} in namespace {{ $labels.namespace }} is expiring in {{ $value | printf \”%.2f\” }} days.”

– alert: CertManagerRenewalStuck
expr: |
certmanager_certificate_ready_status{condition=”False”} == 1
for: 4h
labels:
severity: warning
tier: platform
annotations:
summary: “Certificate {{ $labels.name }} renewal is stuck”
description: “Certificate {{ $labels.name }} in namespace {{ $labels.namespace }} has been in a non-Ready state for over 4 hours.”

Out-of-Band TLS Probe Script

This lightweight Python script runs as a CronJob inside our cluster. It bypasses Kubernetes control plane metadata entirely, making direct socket connections to target endpoints to measure the actual presented server certificate.

#!/usr/bin/env python3
import datetime
import os
import ssl
import sys
import socket
from typing import NamedTuple

class CertStatus(NamedTuple):
domain: str
days_left: int
expired: bool

def check_tls_expiration(hostname: str, port: int = 443, timeout_sec: float = 5.0) -> CertStatus:
context = ssl.create_default_context()
conn = socket.create_connection((hostname, port), timeout=timeout_sec)

with context.wrap_socket(conn, server_hostname=hostname) as sock:
cert = sock.getpeercert()

# Example format: ‘May 15 12:00:00 2024 GMT’
not_after_str = cert[‘notAfter’]
expires_at = datetime.datetime.strptime(not_after_str, “%b %d %H:%M:%S %Y %Z”)
expires_at = expires_at.replace(tzinfo=datetime.timezone.utc)

now = datetime.datetime.now(datetime.timezone.utc)
delta = expires_at – now

return CertStatus(
domain=hostname,
days_left=delta.days,
expired=delta.days <= 0
)

def main():
targets = os.getenv(“TARGET_HOSTS”, “fix.prod.example.com,api.prod.example.com”).split(“,”)
failure = False

print(f”Starting TLS verification sweep at {datetime.datetime.now(datetime.timezone.utc)}”)
print(“-“ * 60)

for host in targets:
host = host.strip()
try:
status = check_tls_expiration(host)
print(f”HOST: {status.domain:<30} DAYS REMAINING: {status.days_left:<5}”)

if status.days_left < 15:
print(f”[ERROR] Certificate for {host} expires within threshold! ({status.days_left} days)”)
failure = True
except Exception as e:
print(f”[CRITICAL] Failed to probe {host}: {str(e)}”)
failure = True

if failure:
sys.exit(1)

print(“-“ * 60)
print(“All endpoints verified successfully.”)
sys.exit(0)

if __name__ == “__main__”:
main()


Verifying Resolution and Results

After migrating our infrastructure from HTTP-01 to DNS-01 via Route53 and deploying the updated ClusterIssuer, we forced an immediate renewal to verify the entire pipeline end-to-end:

cmctl renew fix-gateway-tls -n trading

Output trace from cert-manager logs showing successful DNS-01 record insertion and validation:

I0215 03:12:44.102948 1 sync.py:128] cert-manager/certificates-trigger “msg”=”Certificate scheduled for immediate renewal” key=”trading/fix-gateway-tls”
I0215 03:12:44.204812 1 dns.py:94] cert-manager/challenges/acme/dns01/route53 “msg”=”Presenting DNS-01 challenge record” zoneID=”Z01928374829374928374″ record=”_acme-challenge.fix.prod.example.com”
I0215 03:12:58.840192 1 dns.py:120] cert-manager/challenges/acme/dns01/route53 “msg”=”Successfully verified DNS-01 record propagation via self-check”
I0215 03:13:01.492019 1 orders.py:210] cert-manager/orders “msg”=”ACME Order completed successfully” resource_name=”fix-gateway-tls-1-39201948″

We executed a zero-downtime secret rotation check. The Nginx Ingress Controller picked up the refreshed secret instantly:

kubectl get secret fix-gateway-tls-secret -n trading -o jsonpath=‘{.data.tls\.crt}’ | base64 -d | openssl x509 -noout -dates
text
notBefore=Feb 15 03:00:00 2024 GMT
notAfter=May 15 03:00:00 2024 GMT

Infrastructure Recovery Summary

Metric Before Fix (HTTP-01) After Fix (DNS-01 + Monitoring)
Renewal Success Rate 0% (Stuck in 403 loop) 100%
Validation Mechanism Ingress Path Matching Route53 TXT Record Injection
Time to Validate Challenge Timeout (>30 days pending) 17.3 seconds
Alert Visibility Silent Failure Multi-tier (Prometheus + Socket Probe)

Lessons Learned

  1. HTTP-01 Challenges are fragile for complex edge routing. If your Ingress rules contain custom annotations, mTLS requirements, global redirects, or strict regex pathing, HTTP-01 challenges will eventually fail when your routing rules evolve. Use DNS-01 for production environments.
  2. Alert on resource status, not just metrics thresholds. Monitoring certmanager_certificate_expiration_timestamp_seconds is insufficient because a stuck certificate doesn’t update its expiration metric—it simply stops updating. Alert explicitly on certmanager_certificate_ready_status{condition="False"} == 1.
  3. Control plane metrics lie when pods restart. Always validate live TLS endpoints from out-of-band systems. A CronJob running a network-level TLS handshake probe provides absolute ground truth regardless of state bugs in Kubernetes custom controllers.
  4. Decouple IAM permissions using IRSA. Avoid dynamic secret mounts for cloud provider API credentials. Using IAM Roles for Service Accounts allows cert-manager to perform DNS-01 TXT record creation cleanly and securely without static credential rotation risk.

Join the conversation

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