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:14 AM on a Tuesday when our secondary execution gateway stopped accepting fix-over-TLS connections from two of our key liquidity providers. The alert wasn’t triggered by our Kubernetes cluster monitoring, nor by cert-manager. It came from an external synthetic probe monitoring our API edge.

When I checked the ingress gateway, the issue was immediately obvious: an expired TLS certificate.

* Server certificate:
* subject: CN=fix.gateway.infra.trading.internal
* start date: Nov 14 18:22:04 2023 GMT
* expire date: Feb 12 18:22:03 2024 GMT
* issuer: C=US; O=Let’s Encrypt; CN=R3
* SSL certificate verify result: certificate has expired (60)

We had deployed cert-manager precisely to prevent this failure mode. TLS automation with Let’s Encrypt was supposed to handle 90-day certificate lifecycles without human intervention. Yet, the certificate sat expired while cert-manager’s custom resources claimed everything was operating within normal parameters.

Here is an post-mortem of how our automated renewal workflow silently degraded, how we diagnosed the underlying HTTP-01 challenge failure inside a zero-trust network topology, and the production-grade configuration we implemented to guarantee auto-remediation.


The Failure Mode: Why Auto-Renewal Stalled

cert-manager uses a Custom Resource Definition (CRD) hierarchy to manage state: Certificate resources define desired state, which generate CertificateRequest objects, which in turn spin up Order and Challenge resources when interfacing with an ACME server like Let’s Encrypt.

When I ran kubectl get certificate, the output was deceptively positive:

$ kubectl get certificate -n execution-ingress
NAME READY SECRET AGE
fix-gateway-tls-cert True fix-gateway-tls-secret 89d

The READY column displayed True because it reflected the state of the existing secret in the cluster—which was valid until a few hours prior—not the success of the background renewal process.

Drilling into the CertificateRequest and Challenge CRDs revealed where the pipeline had actually choked:

$ kubectl get challengerequests,challenges -n execution-ingress
NAME ACCORDING TO AGE
challenge.acme.cert-manager.io/fix-gateway-tls-cert-xz9ql-1 pending 29d

Checking the detailed description of the stuck challenge exposed the silent loop:

$ kubectl describe challenge challenge.acme.cert-manager.io/fix-gateway-tls-cert-xz9ql-1 -n execution-ingress
yaml
Status:
State: pending
Reason: Waiting for HTTP-01 challenge propagation
Processing: true
Presented: true
Events:
Type Reason Age From Message
—- —— —- —- ——-
Normal Started 29d cert-manager Challenge process started
Warning SelfCheck 2m (x4120 over 29d) cert-manager Self check failed to retrieve response from http://fix.gateway.infra.trading.internal/.well-known/acme-challenge/L9A8z…: got status 403, expected 200

For 29 days, cert-manager had been attempting to complete the HTTP-01 challenge. However, three distinct architectural decisions conspired to silently block it:

  1. Strict NetworkPolicies: The ephemeral ACME solver pod created by cert-manager did not inherit the ingress controller’s network labels, blocking inbound traffic from the external ingress to the solver pod.
  2. Istio Sidecar Injection: Auto-injection was enabled on the namespace. The Istio sidecar inside the transient pod required mTLS initialization before passing traffic, causing the HTTP-01 self-check probe to hit an uninitialized proxy and return HTTP 403/503 errors.
  3. Alerting Blindspot: Prometheus metrics were scraping certmanager_certificate_expiration_timestamp_seconds, but our PrometheusRule query was written against the certmanager_certificate_ready_status vector, which stayed anchored at 1 until the old certificate actually expired.

Topology and Architecture

To resolve this permanently, we abandoned HTTP-01 challenges for edge services in favor of DNS-01 challenges validated via Cloudflare, bypassing internal routing rules and ingress sidecars altogether.

Here is the data flow for our hardened TLS automation pipeline:

flowchart TD
 cert["cert-manager Controller"] -->|"1. Creates DNS-01 Order"| acme["Let's Encrypt ACME API"]
 cert -->|"2. Present TXT Record"| cf["Cloudflare DNS API"]
 acme -->|"3. Query TXT Record"| dns["Public DNS Infrastructure"]
 acme -->|"4. Issue Signed Cert"| cert
 cert -->|"5. Sync TLS Keypair"| secret["Kubernetes Secret"]
 secret -->|"6. Hot Reload Secret"| envoy["Envoy Ingress Gateway"]

By decoupling certificate issuance from the application’s data plane, network policies, ingress controllers, and service meshes no longer interfere with renewal challenges.


Implementation: Production Configuration

Below is the complete infrastructure-as-code layout using standard Kubernetes manifests.

1. ClusterIssuer with Rate-Limited DNS-01 Provider

We configure a ClusterIssuer utilizing a scoped API token stored securely in a Kubernetes Secret.

apiVersion: v1
kind: Secret
metadata:
name: cloudflare-api-token-secret
namespace: cert-manager
type: Opaque
stringData:
api-token: “a8f9c7d1e3b54029a1b8c7d6e5f4a3b2c1d0e9f8”
—
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:
cloudflare:
apiTokenSecretRef:
name: cloudflare-api-token-secret
key: api-token

2. Standardized Certificate Resource

The Certificate manifest enforces proactive renewal timelines. By setting renewBefore to 30d (720 hours before expiration), we give our engineering teams a 30-day buffer to react if an issuance pipeline breaks.

apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: fix-gateway-tls-cert
namespace: execution-ingress
spec:
secretName: fix-gateway-tls-secret
duration: 2160h # 90 days
renewBefore: 720h # 30 days
subject:
organizations:
– High Frequency Trading Group
commonName: fix.gateway.infra.trading.internal
dnsNames:
– fix.gateway.infra.trading.internal
issuerRef:
name: letsencrypt-prod-dns01
kind: ClusterIssuer
group: cert-manager.io
privateKey:
algorithm: RSA
encoding: PKCS1
size: 4096

3. Automated Monitoring and Alerting (PrometheusRules)

To ensure silent failures never cause outages again, we created specific alerting rules. We monitor both the expiration timestamp directly and failed renewal attempts.

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: cert-manager-alerts
namespace: cert-manager
labels:
role: alert-rules
spec:
groups:
– name: cert-manager-operational
rules:
– alert: CertManagerCertExpiringSoon
expr: |
(
certmanager_certificate_expiration_timestamp_seconds – time()
) < (30 * 86400)
for: 1h
labels:
severity: critical
tier: infrastructure
annotations:
summary: “Certificate {{ $labels.name }} expires in less than 30 days”
description: “Certificate {{ $labels.name }} in namespace {{ $labels.namespace }} has a validity window under 30 days. Current automated renewal may be failing.”

– alert: CertManagerRenewalStuck
expr: |
certmanager_certificate_renewal_status{status=”True”} == 0
and
(certmanager_certificate_expiration_timestamp_seconds – time()) < (60 * 86400)
for: 4h
labels:
severity: warning
tier: infrastructure
annotations:
summary: “Certificate {{ $labels.name }} renewal failure”
description: “The cert-manager controller has been unable to renew {{ $labels.name }} in {{ $labels.namespace }} for over 4 hours.”


Python Diagnostic Script for Cluster State Verification

When diagnosing certificate sync failures across environments, relying on kubectl manually for every namespace is inefficient. I wrote this script using the official Python Kubernetes Client to run in our CI/CD post-deployment validation steps. It parses internal TLS secrets directly, calculates raw remaining validity days, and checks cert-manager conditions.

#!/usr/bin/env python3
import sys
import datetime
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from kubernetes import client, config

def check_cluster_certificates(max_allowed_days_left=30):
“””
Parses all TLS secrets across namespaces and alerts on impending expiration.
Compares observed TLS secret validity against cert-manager metadata.
“””
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()

v1_core = client.CoreV1Api()
custom_api = client.CustomObjectsApi()

issues_found = 0
print(f”[*] Scanning cluster for TLS secrets…”)

# Fetch secrets containing TLS data
secrets = v1_core.list_secret_for_all_namespaces(
field_selector=“type=kubernetes.io/tls”
)

now = datetime.datetime.now(datetime.timezone.utc)

for sec in secrets.items:
ns = sec.metadata.namespace
name = sec.metadata.name

if “tls.crt” not in sec.data:
continue

crt_bytes = client.ApiClient().sanitize_for_serialization(sec.data[“tls.crt”])
import base64
cert_pem = base64.b64decode(crt_bytes)

try:
cert = x509.load_pem_x509_certificate(cert_pem, default_backend())
not_after = cert.not_valid_after_utc
time_left = not_after – now
days_left = time_left.days

if days_left < max_allowed_days_left:
print(f”[CRITICAL] Namespace: {ns} | Secret: {name} | Days Remaining: {days_left}”)

# Query corresponding Cert-Manager custom resource
try:
cm_obj = custom_api.get_namespaced_custom_object(
group=“cert-manager.io”,
version=“v1”,
namespace=ns,
plural=“certificates”,
name=name
)
conditions = cm_obj.get(“status”, {}).get(“conditions”, [])
print(f” -> Cert-Manager Conditions: {conditions}”)
except client.exceptions.ApiException:
print(f” -> WARNING: No direct cert-manager object mapping found for secret {name}”)

issues_found += 1
else:
print(f”[OK] Namespace: {ns} | Secret: {name} | Days Remaining: {days_left}”)

except Exception as e:
print(f”[ERROR] Failed to parse cert for secret {name} in namespace {ns}: {str(e)}”)
issues_found += 1

return issues_found

if __name__ == “__main__”:
failures = check_cluster_certificates(max_allowed_days_left=25)
if failures > 0:
print(f”\nScan completed with {failures} alert conditions.”)
sys.exit(1)
else:
print(“\nAll cluster certificates are healthy.”)
sys.exit(0)


Results and Execution Validation

After migrating our ingress controllers to the DNS-01 flow and deploying our Prometheus metrics rules, we manually forced a renewal loop to test end-to-end execution.

We executed a forced renewal using the cmctl CLI tool:

$ cmctl renew fix-gateway-tls-cert -n execution-ingress
Manually triggering renewal of Certificate execution-ingress/fix-gateway-tls-cert

Checking the cert-manager logs showed clean propagation and issue lifecycle completion:

I0213 03:01:12.802194 1 controller.go:161] cert-manager/certificates-trigger “msg”=”Certificate requires renewal” key=”execution-ingress/fix-gateway-tls-cert”
I0213 03:01:13.119042 1 dns.go:145] cert-manager/challenges/Present “msg”=”Presenting DNS01 challenge” resource_name=”fix-gateway-tls-cert-abcd1-1″
I0213 03:01:18.941011 1 dns.go:160] cert-manager/challenges/SelfCheck “msg”=”DNS record successfully verified” resource_name=”fix-gateway-tls-cert-abcd1-1″
I0213 03:01:21.011843 1 setup.go:310] cert-manager/certificates-issuing “msg”=”Certificate issued successfully” key=”execution-ingress/fix-gateway-tls-cert”

We verified certificate expiration extended via OpenSSL:

$ echo | openssl s_client -connect fix.gateway.infra.trading.internal:443 -servername fix.gateway.infra.trading.internal 2>/dev/null | openssl x509 -noout -dates
notBefore=Feb 13 03:01:20 2024 GMT
notAfter=May 13 03:01:19 2024 GMT

The issue was fully resolved.


Key Lessons Learned

  1. HTTP-01 is risky in Zero-Trust Environments: HTTP-01 relies heavily on pod lifecycle, routing rules, network policies, and mesh proxies. DNS-01 challenges execute completely out-of-band via your cloud provider API, eliminating network routing failure points.
  2. READY=True is a Trap: Never write alerts targeting certmanager_certificate_ready_status alone. That status reflects the existing secret on disk, not the progress of background ACME challenges. Alert on certmanager_certificate_expiration_timestamp_seconds directly.
  3. Decouple Issuance Buffer from CA Expiration: Set renewBefore to at least 30 days. Let’s Encrypt certificates last 90 days. A 30-day buffer gives your engineering teams time to discover and fix broken API tokens, network policy regressions, or rate-limiting issues before an actual outage occurs.

Join the conversation

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