Skip to main content
Video tutorial · 2:29

nginx module

Deploys the certificate to nginx over SSH. The module does not need to be told where the files are. It reads nginx's own configuration (nginx -T) to find the ssl_certificate / ssl_certificate_key pairs the instance serves. It replaces the ones that hold this certificate's names, checks the result with nginx itself, reloads nginx and waits for new worker processes. If anything fails after a file was replaced, the previous files are put back.

nginx's configuration itself is never edited.

Every behaviour on this page was measured on nginx 1.18 (Ubuntu 22.04), 1.20 (Rocky Linux 9), 1.22 (Debian 12), 1.24 (Ubuntu 24.04, systemd) and the nginx.org builds 1.28 and 1.31 (Alpine).

Overview​

  • Type and credential: type nginx; credential ssh_private_key or ssh_password (the SSH credentials), slot default.
  • Connection: the target's SSH part — host name, optional IP, port, user — with the same host-key verification as an SSH target.
  • Per deploy:
    1. Find the nginx instance and read its configuration with nginx -T.
    2. Pick the certificate files.
    3. Stage the new files beside them and check them with nginx -t on a scratch configuration.
    4. Replace them (each file is renamed into place).
    5. Run nginx -t on the live configuration.
    6. Reload nginx and wait for new workers.
    7. Ask each changed listener which certificate it serves.
  • Rollback: supported — a rollback deploys the previous retained version to the same files (Rollback). Auto-rollback is available.

What the module deliberately does NOT do​

  • Edit nginx's configuration. It never adds or changes an ssl_certificate directive. For a first install, write the directive once; renewals replace the same files.
  • Encrypted keys. A key file protected with ssl_password_file is not replaced (NGINX_UNSUPPORTED); CertAutoPilot writes unencrypted keys.
  • Keys in an engine or store, inline certificates. engine: / store: keys and data: certificates are listed as not followed.
  • Containers. An nginx that runs only inside a container on the host is refused (NGINX_CONTAINERIZED). A process counts as containerized when its root directory is another filesystem or its cgroup belongs to Docker, containerd, Kubernetes, Podman, LXC or CRI-O; a systemd-nspawn container is caught by the first rule (measured). A systemd service with its own mount namespace (PrivateTmp, BindReadOnlyPaths) or its own process namespace (PrivatePIDs) is not a container. When the master runs as another account and its root directory cannot be read without sudo, whether it runs in a container cannot be told: that is refused too (NGINX_PRIVILEGE — choose sudo, or connect as the account nginx runs as). Use the Kubernetes module, or point a listed placement at the files the container mounts on a target where no nginx runs.
  • Files certbot or acme.sh manage. A file that resolves under /etc/letsencrypt/ or ~/.acme.sh/ is refused (NGINX_FOREIGN_MANAGER) — that tool would overwrite it on its own renewal.
  • Forks other than OpenResty. Angie and Tengine are not supported.
  • Configurations beyond the reader's bounds. nginx -T output is read in time linear to its size. At most 5,000 files, 2,000,000 words a file and 300,000 directives once includes are expanded; wildcard include patterns are compared with the files at most 10,000,000 times (5,000 files against 2,000 different wildcard includes fit). A configuration beyond a bound is refused as a whole (NGINX_UNSUPPORTED), never read in part.

Requirements​

The SSH account must be able to:

  • read nginx's whole configuration and every certificate file it names (nginx -T opens them all);
  • write the certificate files, and create files in their directories;
  • keep each replaced file's owner, mode, SELinux label and ACL;
  • reload nginx.

Its login shell must be a Bourne-style shell (sh, bash, dash, ksh, zsh, busybox ash; fish works too — measured). CertAutoPilot sends each host script as one command of many lines, and csh / tcsh end such a command at its first line and read the rest as their own commands (measured). An account with a csh-style login shell is therefore refused when it connects, before any script is sent (SSH_VALIDATION, naming the shell): give the account another login shell (chsh -s /bin/sh <account>) or connect with another account.

In practice that is root. Choose the privilege:

PrivilegeWhat runsNeeds
Run as the SSH userevery step as the SSH useran account with the rights above (root, or one given them)
sudo -nevery step under sudo -n shNOPASSWD sudo for the account. sudo -n never asks for a password: a sudo that wants one fails at once (NGINX_PRIVILEGE). This is root on the host.

Tools the host must have: a POSIX shell, awk, sed, dd, stat, df, flock (it keeps two deploys apart) and sha256sum (or openssl). These are present on every distribution measured. openssl is also used for the served-certificate check; chcon and getfacl/setfacl are used when present.

Whose nginx it manages​

CertAutoPilot acts as root on the host, so it only ever runs a program — and only ever parses a configuration — whose owner it may trust.

  • Root's nginx is managed as before. Without sudo, the SSH account's own nginx is.
  • A process of any other account that calls itself an nginx master is ignored: its program is not run, its command line is not followed, and it does not count as an instance. It is reported with the warning NGINX_MASTER_IGNORED (deploy, dry run, health check). Any account can start a program and title it "nginx: master process".
  • An nginx a service account runs is managed when the target lists that account under Accounts it runs as besides root (run_as_accounts, names or numeric uids, at most 8; needs sudo -n). CertAutoPilot then runs that nginx's own program (nginx -V, -T, -t) as that account, never as root, with su -s /bin/sh <account> — the account's login may be closed (nologin). Files are still written by root and keep their owner. The host needs su; an account without a name on the host, or one su refuses, is NGINX_UNSUPPORTED.
  • The program that is run must belong to root or to the account running it, with no write permission for anyone else, in directories no other account can change. Otherwise nothing is run (NGINX_PRIVILEGE, naming the file). The nginx binary field follows the same rule, and the program must answer -V like nginx before anything else is asked of it (NGINX_NOT_FOUND otherwise).
  • A configuration no running nginx uses (nginx is stopped and the target names the file) is parsed only when it belongs to root or the account the steps run as: nginx loads the modules a configuration names (NGINX_PERMISSION otherwise).

Directories it writes into​

A certificate and its key are written only into directories no other account can change. Each directory a file is written into, and every directory above it (the path as written and as the links resolve), must:

  • belong to root, to the account the deploy runs as, to the account nginx's workers run as, or to the account a file holding the private key belongs to (it gets the key anyway) — a directory that receives only a certificate file may also belong to that file's owner, one that receives the key may not;
  • not be writable by its group or by others — a POSIX ACL that lets another account write shows up the same way. Above the file's own directory, a directory with the sticky bit (/tmp) is fine.

Every symbolic link on the path as written must belong to one of those accounts too: another account could point its own link elsewhere between two steps (in /tmp it may replace its link).

Otherwise nothing is written (NGINX_PERMISSION, naming the directory). The reason: a shell cannot hold a directory open, so in a directory another account can write, the name of the file being written could be replaced by a link or a pipe between two steps, and the key would reach that account. The preview and the dry run show the same refusal. The work directory follows the same rule and is made private (mode 0700, owned by the account the deploy runs as); one another account owns, a link, or a lock file that is not a regular file is refused — before anything in it is created or changed.

Target configuration​

FieldMeaning
SSH host / IP / port / useras for an SSH target
PrivilegeRun as the SSH user or sudo -n (above)
nginx instance (config_path)the main configuration file of the master to manage. Empty = the only nginx running. Required when several nginx instances run (the error lists them).
Which certificate filesFind by certificate names (default) or Listed files (below)
ReloadAutomatic (systemctl reload <unit> when the master runs in a systemd service whose unit has a reload command, else a HUP to the master), systemctl reload (refused before anything is written for a unit without a reload command, CanReload=no), or HUP. systemctl reload is bounded by the reload wait.
Reload waithow long to wait for new workers, 5–300 s (default 30)
nginx binaryempty = the running master's own executable, else nginx on PATH
Work directoryjournal and backups, made private (mode 0700, see Directories it writes into). Empty = /var/lib/certautopilot with sudo, ~/.certautopilot without.
Check served certificateask each changed listener on the host which certificate it serves after the reload (default on)
Accounts it runs as besides root (run_as_accounts)empty = root's nginx only. See Whose nginx it manages.
Reload despite pending changessee Unapplied configuration changes (default off)

The nginx instance, the nginx binary and the work directory are plain absolute paths: ASCII letters, digits and . _ - + = @ % only. A path with a space, a quote, $ or another character is refused when the target is saved (and again before anything runs on the host).

Find by certificate names​

Every TLS server block of the http, stream and mail contexts is read. A server that names neither ssl_certificate nor ssl_certificate_key inherits the context's pair. nginx inherits the two separately, so a server that names only one of them uses the context's other one; such a split pair is listed and never written (replacing the context's file would change the servers using it with the other half). A server whose listen line has no ssl is TLS too when another server opens the same address and port with ssl: the flag belongs to the socket, and nginx then serves that server's own pair (measured on nginx 1.31). A certificate pair is updated when:

  • the certificate it holds now is covered by the deployed certificate — every one of its names (a wildcard covers one label); or
  • an earlier deploy of this certificate wrote it. This keeps a rollback to a version with fewer names working.

A pair holding another certificate is left alone. A pair another CertAutoPilot certificate wrote stops the deploy (NGINX_CONFLICT).

The first time a pair is taken over because the deployed certificate covers the one it holds, the result carries the warning NGINX_ADOPTED. When a server that uses a written pair has a server_name the deployed certificate does not cover, the result carries NGINX_NAMES_NOT_COVERED and the job log names the server name; the pair is still written.

Whose files. A pair found by its names is taken over only when the files and their directory belong to root or to an account nginx runs as. A pair in another account's directory is left alone and reported (NGINX_OWNER_SKIPPED): writing a certificate that covers more names there — a wildcard, for example — would hand that account its key. Name the pair under Listed files to write it on purpose. A pair this certificate already wrote stays its own.

Optional filters narrow the search to servers with some server_name values, some ports, or some contexts (http, stream, mail). A port is a whole number from 1 to 65535, at most 32 of them; the form refuses anything else.

Relative paths are resolved against the directory of nginx's main configuration file, as nginx does.

Listed files​

Pairs of absolute paths — certificate file and key file. Give the same path twice for a file that holds both. A path must not contain $: nginx reads it as a variable, so it is not one fixed file (refused when the target or the override is saved).

  • A listed file that holds a certificate this one does not cover is refused (NGINX_CONFLICT), not overwritten.
  • A missing file is created: certificate mode 0644, key mode 0600. Its directory must exist.
  • A listed file no ssl_certificate names yet is written but not served (NGINX_NOT_BOUND, no reload). Add the directive once.

RSA and ECDSA pairs​

nginx serves one certificate per key type in a server. When a server has an RSA pair and an ECDSA pair with the same names, only the pair of the deployed certificate's key type is replaced. The other keeps its certificate and its own expiry (NGINX_OTHER_KEY_TYPE_KEPT).

A server with a single pair can change key type in place.

Variable paths​

  • $ssl_server_name: a path like /etc/nginx/certs/$ssl_server_name.crt is followed. The module writes one file per name of the certificate; missing files are created with the key at mode 0640 for nginx's worker group, because workers open these files at each handshake.
    • A wildcard name cannot be written (nginx looks the file up by the name the client sends): NGINX_WILDCARD_FILE_SKIPPED.
    • A certificate name that is not a host name (letters, digits, hyphens, underscores and dots — an imported certificate can carry anything) is never put into a file name; that file is listed as skipped.
  • A path in the configuration that holds a control character is listed and skipped, never written.
    • Measured: between the certificate file and the key file being replaced there is a moment where a new handshake for that name fails. The two renames run back to back.
  • Other variables or a map: the binding is listed and skipped (NGINX_DYNAMIC_PATH_SKIPPED). Name its files in a listed placement.
  • ssl_certificate_cache (1.27.4+): keeps a variable file's old content until its valid time ends. The module reloads nginx after writing any file, which empties the cache (measured).

How a deploy runs​

  1. Discover. Find the nginx masters from /proc, read the chosen master's command line (-c / -p / -g are repeated for every nginx -t / -T), run nginx -V and nginx -T.

    • nginx's current configuration must pass its own test; otherwise nothing is changed (NGINX_CONFIG_INVALID). When no nginx runs, nginx's own message about the configuration file the target names is not shown (it could quote any file on the host): run nginx -t on the host to see it.
  2. Plan. Inspect every candidate file: whether it exists, what it resolves to, its owner, mode, SHA-256 and the certificate it holds. A key's content is never read back, only its first line and hash. Then decide each pair.

  3. Refuse before writing on:

    • a conflict, a foreign manager or an encrypted key;
    • an unreadable file or a missing directory;
    • a directory another account can change (Directories it writes into);
    • too little free space next to a file (room for a staged copy and a backup);
    • too little free space in the work directory: the deploy asks for 512 KB plus twice the size of the files it writes there (its journal, its answer and the backups) and stops with NGINX_NO_SPACE before anything is staged;
    • unapplied configuration changes.
  4. Stage. Each file is written as <file>.captmp.<run id> in its own directory, so the later rename is atomic for that file. The name carries the run: two deploys that do not share a work directory can never take each other's copy. Steps:

    1. Read exactly its byte count from the SSH session's standard input; secrets are never on a command line.
    2. Check its SHA-256.
    3. Give it the replaced file's owner, mode, SELinux label and ACL. A new key file gets the group nginx runs its workers with (the second word of user, else the group named like the user).
    4. nginx -t loads the staged pairs in a scratch configuration with the host's own nginx and OpenSSL. A pair it refuses stops the deploy with nothing replaced (NGINX_STAGE_REFUSED).
  5. Swap. Per file:

    1. The file must still have the hash the plan read; otherwise someone changed it (NGINX_CHANGED_DURING_DEPLOY).
    2. It is copied to the backup directory.
    3. The staged file is renamed over it.

    Files are replaced one by one; nginx reads static files only when it reloads, so the running nginx never sees a half-replaced set.

  6. Check. nginx -t on the live configuration. nginx -T must also read as it did when planned (otherwise the configuration changed during the deploy).

  7. Reload and wait for a worker process that was not there before. A reload nginx refuses keeps the old workers: the files are put back and the deploy fails (NGINX_RELOAD_FAILED). The end of nginx's error log is quoted when it is a regular file — the files go back first, and a log that is a pipe or a device is not read (measured: reading a FIFO with a live writer never returns).

    • The master's pid is checked again first: a process that took the number since is never signalled.
    • The systemd unit is used only when its main process is the nginx master. nginx started by another service (supervisord, a launcher) runs in that service's unit, and reloading it would restart the service: Automatic then sends the HUP instead, and a target set to systemctl reload is refused with the files put back.
  8. Verify. For every listener of a changed server, openssl s_client on the host (at most 10 seconds each, where timeout is installed) asks for the certificate with the deployed certificate's key type and a name it covers. A listener still serving another certificate makes the target partial (NGINX_SERVED_MISMATCH). When the check cannot run — openssl is not installed on the host, or a listener does not answer it — the target succeeds with the warning NGINX_SERVED_UNVERIFIED. The check covers the host itself; a load balancer in front is checked by validation endpoints.

  9. Commit. The backups are deleted. The target's state records which files the certificate wrote.

When nginx is not running, the files are written and checked with nginx -t, nothing is reloaded, and nginx serves them when it starts (NGINX_NOT_RUNNING).

Recovery​

  • Any failure after a file was replaced puts every replaced file back from the backups and checks their hashes. A file another writer changed after the swap (an operator, another tool) is left as it is: the deploy fails with NGINX_RECOVERY_FAILED and names it.
  • A restore that cannot finish fails the deploy with NGINX_RECOVERY_FAILED. The message names the files and the backup directory, which stays until you remove it; fix by hand.
  • When the SSH session or the CertAutoPilot worker dies in the middle, the script on the host ignores the hang-up: it finishes (or restores) on its own. Its journal stays in <work dir>/nginx/txn-<id>/. The next run reads the files as they are.
    • Files already holding this certificate are not written again.
    • nginx is reloaded only if it was not reloaded for them. Measured: an SSH session cut while nginx was reloading; the host finished the deploy and the next run changed nothing.
  • Two deploys to one host never overlap:
    • CertAutoPilot runs one deploy per host at a time.
    • A host-side lock (flock) answers a second one with NGINX_IN_PROGRESS (retried). A host without flock is refused before anything is written (NGINX_UNSUPPORTED).
  • A work directory that fills up while the deploy runs never loses the result. A failed run puts the files back and answers with its code; a run that finished answers NGINX_SCRIPT ("the deploy finished on the host, but its answer could not be kept"), and the next run finds the files current and changes nothing. Measured before these checks: a full work directory ended the run with no answer, left the staged copy of the key beside the live key, and once replaced the certificate without its key.
  • Two installations (or two work directories) writing the same files at the same time do not share the host lock. The first to swap wins; the other finds the files changed and stops with NGINX_CHANGED_DURING_DEPLOY, nothing replaced. Use one work directory per host.
  • Leftovers: journals older than two days are deleted by the next deploy. Staged copies a killed run left beside the live files are removed by the next deploy of the same work directory (it reads the killed run's own notes; a file whose name does not carry that run's id is never touched).

Unapplied configuration changes​

A reload applies everything in nginx's configuration — also changes someone saved but has not reloaded yet. When a configuration file is newer than the newest nginx worker (the last reload), the deploy is refused before anything is written (NGINX_PENDING_CHANGES), naming the files.

Reload nginx yourself, or turn on Reload despite pending changes on the target. If the time of the last reload cannot be read, the deploy goes on with NGINX_PENDING_UNKNOWN.

Live pickers and preview​

On a saved target:

  • the instance picker lists the nginx masters on the host;
  • the listed-file picker lists every TLS certificate pair nginx's configuration names;
  • Preview certificate files answers what a deploy would do, from the deploy's own plan. Each pair shows the certificate it holds now, the servers that use it, and whether it would be replaced, kept or refused, plus the reload method and any pending configuration change.

A distribution's override row offers the same preview for its certificate. All of them only read.

A picker or preview that names another instance's configuration file, or listed files the saved target does not name, needs a project admin (403 for an operator): it reads those paths on the host with the target's privilege, the same choice that needs the Admin role when it is saved as an override. An operator can preview the saved target as it is, filter by names, ports and contexts, and run a dry run of a saved distribution.

Per-distribution overrides​

An override row can choose, for one distribution:

  • the nginx instance (config_path, the main configuration file of the master to manage) — useful when several nginx run on the host and the target names none, or this certificate belongs to another instance. The first row that names one wins (the target's own row, its group's row, then the Default row), else the target's own. On a target row the picker lists the instances running on the host.
  • the placement (find by names, with its filters, or listed files). The first row that sets a placement replaces the target's placement as a whole.

The two are decided separately: a row that names only the instance leaves the placement to the next row or the target (Overrides).

A find-by-names row carries its own filters — server names, ports and contexts. The target's filters do not apply to the distribution once a row sets a placement, and the row's summary names the filters it has.

Setting or changing the instance or a listed file in an override needs the Admin role; for an operator whose change does not go through approval, the drawer says so on those inputs and the save is refused (403).

Runs over many servers​

  • Hosts at once. One run works on up to five hosts at a time (the module configuration's concurrency, 1–50); the targets of one host run one after another. The SSH Max Concurrency setting (Settings → General) is a ceiling on it — it never raises the module's own value — and with Parallel Execution off a run takes one host at a time.
  • A time budget per target. A target that takes the login and then stops answering is given up after 4 minutes plus twice its reload wait (5 minutes with the default 30 s). It fails with NGINX_SCRIPT, and the other hosts go on. The script on the host ignores a cut session and finishes on its own; the next run reads what it did.
  • A partial run is run again. When some targets succeeded and others did not, the distribution sweep runs the distribution again for the targets that failed, were not reached, or failed their post-deploy check — up to three times per certificate version, one scheduler cycle apart (hourly by default). The targets that hold the version are not contacted; the job log says what a re-run covers, and the distribution's result always describes every target. A run started by hand covers every target. After the third attempt the distribution stays partial until it is run by hand. This is the rule of a distribution that runs in one job; one large enough to fan out retries inside its batches instead (transient failures and targets not reached, three waves), and its final partial is not run again.
  • Auto-rollback. A host the run could not connect to was sent nothing: with auto-rollback on it does not roll the other hosts back — it is run again like any failed target. Refusals made before anything is written do not roll back either. A lost answer, a failed reload or a failed restore still does (Rollback).
  • Fan-out. Batches are sized from the targets' time budgets, and a target a batch did not reach before its time ended is retried together with the transient failures (Fan-out).

Identity, idempotency and state​

Per certificate the target records the files it wrote — the name nginx uses and the file it resolved to — the deployed leaf and the version nginx was last reloaded for. A name that now resolves to another file (a link pointed elsewhere) is judged by the names its certificate holds again; a file another certificate recorded is refused under any name (NGINX_CONFLICT). Files already holding exactly what would be written are not written again. When the target is pointed at another machine (another host name or IP, or port), this certificate's record no longer counts: the files there are judged by their names again and its reload marks are not reused. Another certificate's record on the target still claims its files, whatever the address — it deploys through the same target. A host name written in other letter case or with a trailing dot is the same machine. A crash between writing and reloading is caught by the reload marker and by comparing the files' time with the workers' start. The record is saved as each target finishes, so a run that is interrupted keeps the records of the targets it finished.

Health check​

Connects, runs sudo -n when chosen, finds the instance and runs nginx -T. Reports the nginx version, the configuration file, the master and nginx's TLS library. It warns when nginx is not running, when the configuration changed after the last reload, or when openssl is missing.

Error codes​

See Error codes → nginx. A certificate or a target that cannot be used as given is NGINX_VALIDATION (not retried): an expired certificate, a key that does not belong to it, several nginx instances without an instance on the target, a missing directory, a path on the target that is not a plain path, or an nginx that only an account the target does not list runs. A connection that cannot be made uses the SSH codes (SSH_CONNECT, SSH_AUTH, SSH_HOST_KEY_CHANGED, SSH_HOST_KEY_ALGO, CREDENTIAL_MISSING; SSH_VALIDATION for a csh-style login shell). A connection lost after it was up — while a script ran — is NGINX_SCRIPT (retried). A job an operator cancelled carries no code and is not retried.

Video tutorial

Short, hands-on videos showing this feature working for real. English audio, English and Turkish subtitles. All video tutorials →

Deploy Certificates to nginx Without Typing a PathYouTube ↗