Systemd unit hangs systemd-shutdown when TLS cert-rotation script runs in ExecStop on Ubuntu 22.04
Environment
Ubuntu Server 22.04 LTS running a custom service 'app-refresh.service' which manages an application and performs TLS certificate rotation in ExecStop via a bash script that calls certbot and a remote Vault API. Observed on VM and one physical host.
Symptoms
When rebooting or powering off, shutdown stalls for several minutes with message 'A stop job is running for app-refresh.service' and systemctl list-jobs shows the unit in stopping state. On some reboots, the system eventually forces stop after 90s; on others, it remains stuck indefinitely requiring a hard power cycle.
Observations
Journalctl shows ExecStop running a bash script that attempts to contact Vault over HTTPS; DNS lookups and TLS handshakes succeed but the script waits for external responses. No explicit timeout in the script. systemd logs indicate the StopTimeoutSec default is hit intermittently. The same script when executed manually stops quickly. Killing the process in systemd-shutdown sometimes doesn't clean up child processes spawned by the script.
Already attempted
Added TimeoutStopSec=120 to the service file — system stops after 120s but cert rotation may be incomplete. Modified the script to run non-blocking background upload (appending &), but systemd then reports failure because ExecStop exits immediately without confirming rotation. Rewrote script to trap signals and ensure child PIDs are reaped, but the unit still occasionally hangs when network is flaky during shutdown.
Question
How should certificate rotation that requires network access be safely integrated into systemd unit stop behavior so shutdown does not hang or rely on long blocking network calls? What service file patterns prevent systemd-shutdown from getting stuck while ensuring rotation completes or is retried later?
Verified community troubleshooting
No answers yet..
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags