This is for anyone who has to put purchased certificates on many servers that do not look alike: nginx on one, Apache on another, a service that only reads its certificate when it starts, another that wants the key and certificate in one file. At the end you will have an Ansible role that refuses to touch a host until the key, chain, dates and names check out, replaces files atomically, validates and reloads each service, connects to the live port to confirm what is being served, and rolls itself back when any step fails. It assumes you can SSH to the servers with sudo and know what a certificate and a private key are. You need no Ansible experience beyond running a playbook.
Every guard in the role exists because I hit the failure it prevents. Those failures are in the Troubleshooting section, written the way you would search for them.
Last verified: December 2026. Versions used: ansible-core 2.22.1 (released November 30, 2026; the control node needs Python 3.13 or newer, managed hosts Python 3.9 or newer), community.crypto 3.6.0, OpenSSL 3.0 on the control node. The playbook was run with ansible-core 2.22.1 and community.crypto 3.6.0 on a scratch machine against test TLS services and a throwaway CA, with a stand-in for systemd, not against real nginx or Apache. The OpenSSL commands and the cross-signing behavior were tested the same way.
What Happened
I run a mixed fleet of roughly 46 servers, and wildcard certificates from a commercial CA cover much of it. The CA delivers a zip of files, and every server wants them in a different shape. I wrote an Ansible project to push them, with a role for each shape: Apache with separate certificate and key files, Apache with symlinks, nginx with the certificate and chain in one file, a websockify proxy that wants the key first in a single PEM, a PBX with its own file names and ownership, and a bespoke TLS service with hardcoded paths.
Building it went wrong in instructive ways. A dry run that was not a dry run deployed the wrong domain’s certificate. A deploy for one domain broke two others. --diff printed a private key to my terminal. A restart handler took down a service that then needed someone to start it by hand. Each of those became a guard.
In November 2026 I renewed and deployed 31 certificates with this system. Several of the failures in the Troubleshooting section below happened during that run. The hardest problem was the chain. The CA had moved issuance to a new root, and some older client devices failed to connect to a server whose chain ended only at that new root. I rolled that server back to the previous certificate, then served a cross-signed chain that also leads to the old root. That fixed the old clients, and they have stayed fixed, so I deployed the cross chain fleet-wide. The lesson I took from it: after any root change, test old clients against the chain the server actually serves (Step 5). The post-deploy check in the role below validates every served chain against the old root as well as the new one.
How It Works
Why Manual Renewal Stops Working
The CA/Browser Forum writes the rules that public CAs follow. Its ballot SC-081, passed in April 2025, shortens the maximum lifetime of a public TLS certificate in steps. Since March 15, 2026 the maximum is 200 days. On March 15, 2027 it drops to 100 days, and on March 15, 2029 to 47 days. The same ballot shortens how long a CA may reuse a domain validation: 200 days now, 100 days in 2027 and 10 days in 2029. By then you prove control of the domain for nearly every certificate.
At 47 days, a certificate renewed a couple of weeks before expiry gets replaced about once a month. By hand, on dozens of servers, that is a permanent chore, and every manual copy is another chance to put the wrong file in the wrong place.
ACME or a Pushed Certificate
ACME is the protocol Let’s Encrypt and many commercial CAs use to issue certificates to software, with no human in the loop. Where a host can run an ACME client and prove control of its name, use ACME and let the host renew itself. That covers most single web servers. Self-Hosting: Why in The Fuck Did I Not Learn This in School? walks through certbot and Let’s Encrypt on one server.
A certificate obtained once and pushed by configuration management still makes sense where ACME does not fit:
- Appliances and vendor software that only accept an uploaded file.
- Legacy services with hardcoded file names, unusual formats or no way to reload.
- Hosts with no route to the CA, no inbound port 80 for the HTTP-01 challenge, and no DNS API credentials you are willing to store on them. A wildcard from Let’s Encrypt requires the DNS-01 challenge, which means DNS API access.
- Many hosts sharing one wildcard, where issuing once in one place and distributing is simpler than running a client everywhere.
Reasonable engineers draw this line in different places. My opinion: as lifetimes shrink, obtain certificates with ACME wherever you can, including the central wildcard if your CA offers ACME, and keep configuration management for distribution. The role below does the distribution, however the files were obtained.
The Pipeline
Every alias passes the same gates. A failure before the backup stops the run with nothing changed; a failure after it triggers a rollback.
The pre-flight runs on the control node (the machine you run Ansible from) and changes nothing on any server. After the backup, install, validate, reload and check run inside a block with a rescue section: any failure restores the backup, reactivates the service and marks that alias failed. With max_fail_percentage: 0, one failed alias stops the next batch.
Chains and Cross-Signing
A server sends its own certificate (the leaf) plus the intermediate certificates that connect it to a root. The client builds a path from the leaf to a root certificate already in its trust store. The root is not normally sent; the client must already have it.
When a CA starts issuing under a new root, clients whose trust stores predate that root cannot finish the path. They fail with unable to get local issuer certificate or send an unknown ca alert, even though the certificate itself is fine. Embedded devices and operating systems that no longer get trust store updates are typical victims.
A cross certificate bridges the gap. It carries the new root’s name and public key but is signed by the old root. Serve it after the intermediate and the client has two possible paths:
A client that trusts the new root stops there. A client that only trusts the old root follows the cross certificate.
OpenSSL looks for each issuer in the trust store before it looks in the certificates the server sent, and has done so by default since 1.1.0, so a client that has the new root never uses the cross certificate. A client that lacks it walks on to the old root. Other TLS libraries build paths in their own ways, which is why you test real old clients (Step 5) rather than trusting the theory.
My case was GlobalSign’s AlphaSSL. GlobalSign’s AlphaSSL page lists GlobalSign GCC R46 AlphaSSL CA 2025 as the default intermediate, and the R6-based intermediate only for certificates issued before July 27, 2026. GlobalSign describes Root R46 (valid until March 20, 2046) as the replacement for Root R6 (valid until December 10, 2034) when R6 expires, and publishes a cross certificate, “R46 signed by R6”, valid until December 10, 2034. Serving the leaf, the R46 AlphaSSL intermediate and that cross certificate gives old clients a path to Root R6. The price is one more certificate in every handshake.
Prerequisites
- A Linux control node with Python 3.13 or newer (required by ansible-core 2.22; check with
python3 --version, since an older Python makes pip report no matching distribution) and OpenSSL 3.0 or newer (for the-no-CAstoreoption). The helper script and one troubleshooting command use GNUsedanddate, which macOS does not ship. - SSH key access and sudo on every managed host, Python 3.9 or newer on them, and systemd managing the services.
- From your CA: the new leaf certificate, its private key, the intermediates, and the root certificate of every trust store you must support, for example the CA’s current root and its previous root.
- For each server: the paths the service reads, the systemd unit name, whether the service can reload, the TLS port, and one name clients use for it, such as
www.example.com. - A staging server where you can serve the new chain before production.
Step 1: Install ansible-core and community.crypto
Install Ansible into a virtual environment on the control node so it does not fight your distribution’s packages (on Debian and Ubuntu, python3 -m venv needs the python3-venv package). The cryptography library is needed by the community.crypto modules, which this role runs on the control node.
python3 -m venv ~/venvs/ansible
. ~/venvs/ansible/bin/activate
pip install 'ansible-core>=2.22,<2.23' cryptography
ansible --version | head -n 1
Expected output, with your patch version:
ansible [core 2.22.1]
Then create requirements.yml in your project directory (Step 2) and install the collection from it:
---
collections:
- name: community.crypto
version: ">=3.6.0,<4.0.0"
ansible-galaxy collection install -r requirements.yml
Step 2: Lay Out the Project
tls-deploy/
├── ansible.cfg
├── requirements.yml
├── deploy-certs.yml
├── rollback.yml
├── prep_certs.sh
├── inventory/hosts.yml
├── group_vars/
│ ├── all.yml
│ ├── wildcard_example_com.yml
│ └── wildcard_example_net.yml
├── files/
│ ├── certs/<domain>/{cert.pem,chain.pem,privkey.pem}
│ └── roots/{current-root.pem,legacy-root.pem}
└── roles/tls_deploy/
├── defaults/main.yml
└── tasks/{main,preflight,backup,install,activate,postcheck,rollback}.yml
Create each file below with vim, for example vim ansible.cfg (press i to insert, Esc then :wq to save and quit). ansible.cfg points at the inventory and keeps diffs off unless you ask:
[defaults]
inventory = inventory/hosts.yml
[diff]
# Never print diffs unless asked. A diff of a key file is the key.
always = False
If the project lives in Git, keep unencrypted keys out of it. Add a .gitignore:
*.key
*.p12
*.pfx
Step 3: Write the Inventory: One Alias per Certificate per Machine
Each inventory entry is one certificate on one machine. A machine that serves two domains appears twice, under two names (aliases), with the same ansible_host. Each alias belongs to exactly one wildcard_* group, and that group sets the domain.
---
# One inventory host per certificate per machine. Two domains on one machine
# are two aliases with the same ansible_host, so their variables never merge.
all:
children:
wildcard_example_com:
hosts:
web2-example-com:
ansible_host: 192.0.2.11
tls_server_name: shop.example.com
tls_service: apache2
tls_cert_path: /etc/apache2/tls/example.com.fullchain.pem
tls_key_path: /etc/apache2/tls/example.com.key
tls_validate_cmd: [apachectl, configtest]
web1-example-com:
ansible_host: 192.0.2.10
tls_server_name: www.example.com
tls_service: nginx
tls_cert_path: /etc/nginx/tls/example.com.fullchain.pem
tls_key_path: /etc/nginx/tls/example.com.key
tls_validate_cmd: [nginx, -t]
app1-example-com:
ansible_host: 192.0.2.13
tls_server_name: api.example.com
tls_service: example-tls-app
tls_layout: split
tls_cert_path: /opt/example-app/tls/example.com.crt
tls_chain_path: /opt/example-app/tls/example.com.chain.crt
tls_key_path: /opt/example-app/tls/example.com.key
tls_owner: exampleapp
tls_group: exampleapp
tls_reload_mode: restart
tls_port: 8443
wildcard_example_net:
hosts:
web2-example-net:
ansible_host: 192.0.2.11 # same machine as web2-example-com
tls_server_name: www.example.net
tls_service: apache2
tls_cert_path: /etc/apache2/tls/example.net.fullchain.pem
tls_key_path: /etc/apache2/tls/example.net.key
tls_validate_cmd: [apachectl, configtest]
group_vars/wildcard_example_com.yml:
---
tls_domain: example.com
group_vars/wildcard_example_net.yml:
---
tls_domain: example.net
group_vars/all.yml says where the prepared files and the trust anchors (the root certificates a chain must validate against) live:
---
# Prepared files for each domain, on the controller (see prep_certs.sh).
tls_src_dir: "{{ playbook_dir }}/files/certs/{{ tls_domain }}"
# Every trust store the served chain must satisfy. The post-deploy check
# validates against each file on its own, so the old root counts too.
tls_trust_anchors:
- "{{ playbook_dir }}/files/roots/current-root.pem"
- "{{ playbook_dir }}/files/roots/legacy-root.pem"
Put the roots you downloaded from your CA in files/roots/. List every trust store you must support; drop legacy-root.pem from a domain’s group vars if no old clients reach it. Check what each alias resolves to before going further:
ansible-inventory --host web2-example-net | grep -E '"(ansible_host|tls_domain|tls_cert_path)"'
"ansible_host": "192.0.2.11",
"tls_cert_path": "/etc/apache2/tls/example.net.fullchain.pem",
"tls_domain": "example.net",
Step 4: Prepare the Files and Encrypt the Key
CA downloads arrive in whatever shape the CA likes. This script normalizes them, refuses a key that does not match the certificate, and stores the key encrypted with Ansible Vault. Vault encrypts files with a password you supply at run time; ansible.builtin.copy and the file lookup decrypt vaulted files automatically.
#!/usr/bin/env bash
# Usage: ./prep_certs.sh <domain> <private.key> <leaf.crt> <intermediate.crt> [<cross.crt> ...]
# Writes files/certs/<domain>/{cert.pem,chain.pem,privkey.pem}; the key is vault-encrypted.
set -euo pipefail
domain=$1 key=$2 leaf=$3
shift 3
out="files/certs/$domain"
mkdir -p "$out"
# Strip a UTF-8 byte-order mark and carriage returns, and make sure the file ends in a newline.
clean() { sed '1s/^\xEF\xBB\xBF//' "$1" | tr -d '\r' | sed '$a\'; }
clean "$leaf" > "$out/cert.pem"
: > "$out/chain.pem"
for f in "$@"; do clean "$f" >> "$out/chain.pem"; done
# Refuse to continue if the key and certificate do not belong together.
cert_pub=$(openssl x509 -in "$out/cert.pem" -noout -pubkey | openssl sha256)
# Set KEYPASS in the environment if the key has a passphrase, or openssl will prompt.
key_pub=$(openssl pkey -in "$key" ${KEYPASS:+-passin env:KEYPASS} -pubout | openssl sha256)
if [ "$cert_pub" != "$key_pub" ]; then
echo "key does not match certificate" >&2
exit 1
fi
ansible-vault encrypt --output "$out/privkey.pem" "$key"
echo "wrote $out/cert.pem, $out/chain.pem and vault-encrypted $out/privkey.pem"
Run it from the project directory. Pass the cross certificate after the intermediate if you serve one:
chmod +x prep_certs.sh
./prep_certs.sh example.com ~/secure/example.com.key ~/Downloads/example.com.crt ~/Downloads/intermediate.crt
If the key has a passphrase, put it in the environment for that one command (KEYPASS='<PASSPHRASE>' ./prep_certs.sh ...), or openssl stops and waits for it. Then confirm that no key in the project is stored in plain text. This prints any key file that is not vault-encrypted, and nothing if all are:
grep -L '^\$ANSIBLE_VAULT' files/certs/*/privkey.pem
Rules for keys that the role enforces or relies on:
- The key exists in plain text only on the control node while you prepare it, and on the servers that use it. Keep the original wherever you keep secrets, or in a secrets manager. A lookup plugin for your secrets manager can replace the
filelookup in the role. - Every task that handles key material has
no_log: true(hides the task’s arguments and results from output and logs) anddiff: false. - Key files are written with mode
0600by default (tls_key_mode), owned by the account that reads them. ansible-vaultasks for a new vault password on every run of the script. Use the same one for every domain, because a playbook run takes one password. Pass it with--ask-vault-pass, or with--vault-password-filepointing at a file outside the repository with mode0600. Never commit a password file.
Step 5: Test the Chain Against an Old Trust Store
Do this before any production deploy, whenever the CA’s intermediate or root changes. First, verify the files against each root on its own. -no-CApath -no-CAstore stops OpenSSL from also consulting the system trust store, which would hide a missing link.
d=files/certs/example.com
openssl verify -no-CApath -no-CAstore -CAfile files/roots/legacy-root.pem -untrusted $d/chain.pem $d/cert.pem
openssl verify -no-CApath -no-CAstore -CAfile files/roots/current-root.pem -untrusted $d/chain.pem $d/cert.pem
Both must print files/certs/example.com/cert.pem: OK. With only the new intermediate in chain.pem, the legacy check fails like this, which is what an old client experiences:
CN = Example Issuing CA
error 20 at 1 depth lookup: unable to get local issuer certificate
error files/certs/example.com/cert.pem: verification failed
Then serve the chain from staging and look at it from the client side. -showcerts prints the certificates exactly as the server sent them, not a verified path:
openssl s_client -connect <STAGING_IP>:443 -servername www.example.com -showcerts </dev/null 2>/dev/null | grep -E '^ *[0-9]+ s:|^ +i:'
With the cross chain you should see three certificates, the last one issued by the old root (names here are from my throwaway CA):
0 s:CN = *.example.com
i:CN = Example Issuing CA
1 s:CN = Example Issuing CA
i:CN = Example New Root
2 s:CN = Example New Root
i:CN = Example Old Root
Now connect as a client that only trusts the old root:
openssl s_client -connect <STAGING_IP>:443 -servername www.example.com -no-CApath -no-CAstore -CAfile files/roots/legacy-root.pem -verify_return_error </dev/null 2>&1 | grep 'Verify return code'
Expect Verify return code: 0 (ok). Finally, point one real old client at staging. OpenSSL proves the chain is buildable; only the device proves its TLS library and trust store agree.
Step 6: Write the Pre-Flight Guards
Role defaults first. Anything an inventory entry does not set comes from here.
---
tls_layout: fullchain # fullchain | split | combined
tls_owner: root
tls_group: root
tls_cert_mode: "0644"
tls_key_mode: "0600" # also used for the combined layout, which holds the key
tls_reload_mode: reload # reload | restart
tls_validate_cmd: [] # for example [nginx, -t]
tls_port: 443
tls_postcheck: true
tls_min_days_left: 30
tls_drain_timeout: 120
tls_backup_root: /var/backups/tls-deploy
# Every file this alias writes. Used by the guards, the backup and the rollback.
tls_dest_paths: "{{ [tls_cert_path, tls_key_path | default(''), tls_chain_path | default('')] | select | list }}"
The pre-flight runs entirely on the control node (delegate_to: localhost) with become: false, so it never tries sudo on your workstation. It changes nothing.
---
- name: Check the inventory entry for this alias
ansible.builtin.assert:
that:
- ansible_host is defined
- group_names | select('match', 'wildcard_') | list | length == 1
- tls_domain is defined
- tls_server_name is defined
- tls_service is defined
- tls_cert_path is defined
- tls_layout in ['fullchain', 'split', 'combined']
- (tls_layout == 'combined') == (tls_key_path is not defined)
- (tls_layout == 'split') == (tls_chain_path is defined)
- tls_reload_mode in ['reload', 'restart']
- tls_dest_paths | unique | length == tls_dest_paths | length
- tls_dest_paths | map('basename') | reject('search', tls_domain | regex_escape) | list | length == 0
fail_msg: >-
Inventory entry for {{ inventory_hostname }} is incomplete or unsafe. Each alias
must be in exactly one wildcard_* group, and every file name must contain its domain.
- name: Refuse to run two aliases of the same machine in one batch
ansible.builtin.assert:
that:
- ansible_play_batch | map('extract', hostvars, 'ansible_host') | unique | length == ansible_play_batch | length
fail_msg: Two aliases in this batch share a machine. Move one further down the inventory or lower serial.
run_once: true
- name: Inspect the new files on the controller
delegate_to: localhost
become: false
block:
- name: Read the new certificate and chain
ansible.builtin.set_fact:
tls_new_leaf: "{{ lookup('ansible.builtin.file', tls_src_dir ~ '/cert.pem') }}"
tls_new_chain: "{{ lookup('ansible.builtin.file', tls_src_dir ~ '/chain.pem') }}"
- name: Reject a byte-order mark, CRLF line endings or a bundle in cert.pem
ansible.builtin.assert:
that:
- tls_new_leaf is match('-----BEGIN CERTIFICATE-----')
- tls_new_chain is match('-----BEGIN CERTIFICATE-----')
- tls_new_leaf is not search('\r')
- tls_new_chain is not search('\r')
- tls_new_leaf | regex_findall('-----BEGIN CERTIFICATE-----') | length == 1
fail_msg: The files in {{ tls_src_dir }} are not clean PEM. Run prep_certs.sh again.
- name: Inspect the new leaf certificate
community.crypto.x509_certificate_info:
content: "{{ tls_new_leaf }}"
valid_at:
now: "+0s"
margin: "+{{ tls_min_days_left }}d"
register: tls_new_info
- name: Inspect the new private key
community.crypto.openssl_privatekey_info:
content: "{{ lookup('ansible.builtin.file', tls_src_dir ~ '/privkey.pem') }}"
passphrase: "{{ tls_key_passphrase | default(omit) }}"
register: tls_key_info
no_log: true
- name: Check key match, dates and names before touching the host
ansible.builtin.assert:
that:
- tls_key_info.public_key_fingerprints.sha256 == tls_new_info.public_key_fingerprints.sha256
- tls_new_info.valid_at.now
- tls_new_info.valid_at.margin
- >-
('DNS:' ~ tls_server_name) in tls_new_info.subject_alt_name
or ('DNS:*.' ~ tls_server_name.split('.', 1)[1]) in tls_new_info.subject_alt_name
fail_msg: >-
The key does not match the certificate, the certificate is not yet valid or
expires within {{ tls_min_days_left }} days, or it does not cover {{ tls_server_name }}.
- name: Verify the chain against each trust anchor
ansible.builtin.command:
argv:
- openssl
- verify
- -no-CApath
- -no-CAstore
- -CAfile
- "{{ item }}"
- -untrusted
- "{{ tls_src_dir }}/chain.pem"
- "{{ tls_src_dir }}/cert.pem"
loop: "{{ tls_trust_anchors }}"
changed_when: false
check_mode: false # read-only, so run it in --check dry runs too
- name: Count the certificates the server should send
ansible.builtin.set_fact:
tls_expected_served: "{{ 1 + tls_new_chain | regex_findall('-----BEGIN CERTIFICATE-----') | length }}"
What each guard catches:
- One
wildcard_*group per alias and the domain in every file name stop wrong-domain deploys and shared chain files (Troubleshooting has both stories). - Two aliases of one machine in a batch would validate and reload the same web server while the other alias is half-installed. The check runs once per batch. If it trips, move one alias further down the inventory or lower
serial. - Clean PEM rejects a byte-order mark, Windows line endings, and a
cert.pemthat is secretly a bundle. - Key match compares the SHA-256 fingerprint of the public key inside the private key with the one in the certificate.
valid_atconfirms the certificate is valid now (not issued in the future relative to your clock) and still validtls_min_days_leftdays from now, so you never push an old file by mistake.- Name coverage confirms the certificate covers the name clients use, either exactly or through a one-label wildcard.
openssl verifyruns against each trust anchor, withcheck_mode: falseso it also runs during--checkdry runs.
Step 7: Back Up and Install Atomically
The backup goes into a fresh directory per alias per run, so the next deploy cannot overwrite it.
---
- name: Pick a backup directory for this run
ansible.builtin.set_fact:
tls_backup_dir: "{{ tls_backup_root }}/{{ inventory_hostname }}/{{ now(utc=true, fmt='%Y%m%dT%H%M%SZ') }}"
- name: Look at the files that will be replaced
ansible.builtin.stat:
path: "{{ item }}"
get_checksum: false
loop: "{{ tls_dest_paths }}"
register: tls_current
- name: Refuse to replace a symlink with a regular file
ansible.builtin.assert:
that:
- not (item.stat.islnk | default(false))
fail_msg: "{{ item.item }} is a symlink. Point the inventory at the real file."
loop: "{{ tls_current.results }}"
loop_control:
label: "{{ item.item }}"
- name: Create the backup directory
ansible.builtin.file:
path: "{{ tls_backup_dir }}"
state: directory
owner: root
group: root
mode: "0700"
- name: Back up the current files
ansible.builtin.copy:
src: "{{ item.item }}"
dest: "{{ tls_backup_dir }}/{{ item.item | basename }}"
remote_src: true
mode: preserve
loop: "{{ tls_current.results }}"
loop_control:
label: "{{ item.item }}"
when: item.stat.exists and not ansible_check_mode # --check does not create the directory
diff: false
ansible.builtin.copy writes to a temporary file and renames it over the destination, so a service never reads a half-written certificate. Two consequences matter here. With the default follow: false, a destination that is a symlink becomes a regular file, which silently breaks a symlinked layout; the backup step refuses symlinks so you fix the inventory to point at the real file. And when a destination does not exist yet, the new file is created with the default umask before the mode is set, so keep key directories closed to other users.
---
- name: Install the certificate followed by the chain (fullchain layout)
ansible.builtin.copy:
content: |
{{ tls_new_leaf }}
{{ tls_new_chain }}
dest: "{{ tls_cert_path }}"
owner: "{{ tls_owner }}"
group: "{{ tls_group }}"
mode: "{{ tls_cert_mode }}"
when: tls_layout == 'fullchain'
- name: Install the certificate on its own (split layout)
ansible.builtin.copy:
content: |
{{ tls_new_leaf }}
dest: "{{ tls_cert_path }}"
owner: "{{ tls_owner }}"
group: "{{ tls_group }}"
mode: "{{ tls_cert_mode }}"
when: tls_layout == 'split'
- name: Install the chain file (split layout)
ansible.builtin.copy:
content: |
{{ tls_new_chain }}
dest: "{{ tls_chain_path }}"
owner: "{{ tls_owner }}"
group: "{{ tls_group }}"
mode: "{{ tls_cert_mode }}"
when: tls_layout == 'split'
- name: Install the private key (decrypted from the vault on the way)
ansible.builtin.copy:
src: "{{ tls_src_dir }}/privkey.pem"
dest: "{{ tls_key_path }}"
owner: "{{ tls_owner }}"
group: "{{ tls_group }}"
mode: "{{ tls_key_mode }}"
when: tls_layout in ['fullchain', 'split']
diff: false
no_log: true
- name: Install the key, certificate and chain as one file (combined layout)
ansible.builtin.copy:
content: |
{{ lookup('ansible.builtin.file', tls_src_dir ~ '/privkey.pem') }}
{{ tls_new_leaf }}
{{ tls_new_chain }}
dest: "{{ tls_cert_path }}"
owner: "{{ tls_owner }}"
group: "{{ tls_group }}"
mode: "{{ tls_key_mode }}"
when: tls_layout == 'combined'
diff: false
no_log: true
The certificate goes first and the chain after it, leaf to root. nginx requires that order: with the chain first it reports key values mismatch because it pairs the key with the wrong certificate. Apache 2.4.8 and later reads intermediates from the SSLCertificateFile itself, and the documentation calls SSLCertificateChainFile obsolete, so the fullchain layout serves both. The combined layout puts the key first, which is what my websockify proxy expected; check what your service wants. To use it, set tls_layout: combined, leave out tls_key_path, and point tls_cert_path at the single file.
Step 8: Validate, Then Reload or Restart
---
- name: Validate the service configuration
ansible.builtin.command:
argv: "{{ tls_validate_cmd }}"
changed_when: false
when: tls_validate_cmd | length > 0
- name: Reload the service
ansible.builtin.systemd_service:
name: "{{ tls_service }}"
state: reloaded
when: tls_reload_mode == 'reload'
- name: Restart a service that cannot reload
when: tls_reload_mode == 'restart'
block:
- name: Stop the service
ansible.builtin.systemd_service:
name: "{{ tls_service }}"
state: stopped
- name: Wait until no connection holds the port
ansible.builtin.wait_for:
host: 0.0.0.0
port: "{{ tls_port }}"
state: drained
timeout: "{{ tls_drain_timeout }}"
always:
- name: Start the service, even if the wait timed out
ansible.builtin.systemd_service:
name: "{{ tls_service }}"
state: started
Validation runs before any reload. A failed nginx -t or apachectl configtest triggers the rescue and the old files come back before the running service ever sees the bad config. Apache’s documentation notes that a passing syntax check does not guarantee a successful restart, which is why the key-match guard runs earlier.
state: reloaded runs the unit’s ExecReload= command. Check what that is with systemctl cat nginx or systemctl cat apache2. For nginx it should send the master process HUP: nginx re-reads its config and certificates, starts new workers, lets old workers finish their clients, and keeps the old config if the new one fails to load. For Apache it should be a graceful restart, which lets children finish their current requests.
Some services cannot reload, so tls_reload_mode: restart stops the service, waits until no TCP connection on the port is in an active state (by default that includes TIME_WAIT), and only then starts it again. That ordering is the fix for the Errno 98 failure in Troubleshooting. The start sits in always, so if the wait times out the service is still started and the alias fails into its rollback; without it, a timeout during the rollback would leave the service stopped. A port with recent clients holds TIME_WAIT entries for about a minute on Linux, so keep tls_drain_timeout above that.
Step 9: Check the Live Port
---
- name: Check the live port from the controller
delegate_to: localhost
become: false
block:
- name: Fetch the served certificate, validating against each trust anchor
community.crypto.get_certificate:
host: "{{ ansible_host }}"
port: "{{ tls_port }}"
server_name: "{{ tls_server_name }}"
ca_cert: "{{ item }}"
get_certificate_chain: true
loop: "{{ tls_trust_anchors }}"
register: tls_served
retries: 10
delay: 3
until: tls_served is succeeded
- name: Parse the served leaf certificate
community.crypto.x509_certificate_info:
content: "{{ tls_served.results[0].cert }}"
register: tls_served_info
- name: Compare the served certificate with the one just installed
ansible.builtin.assert:
that:
- tls_served_info.fingerprints.sha256 == tls_new_info.fingerprints.sha256
- tls_served_info.not_after == tls_new_info.not_after
- tls_served.results[0].unverified_chain | length == tls_expected_served | int
fail_msg: >-
{{ tls_server_name }}:{{ tls_port }} serves {{ tls_served_info.fingerprints.sha256 }}
(expires {{ tls_served_info.not_after }}) with
{{ tls_served.results[0].unverified_chain | length }} certificates. Expected
{{ tls_new_info.fingerprints.sha256 }} with {{ tls_expected_served }}.
This connects from the control node to each alias’s real address and port, the way a client would, once per trust anchor. ca_cert makes the module validate the served chain against that one root file only (it does not check the hostname, which the pre-flight already did). It then compares the served leaf’s fingerprint and expiry with the file just installed, and the number of certificates served with the number expected.
A service that loads its certificate only at start keeps serving the old one after the files change. Without this check, you find out when the old certificate expires. With it, the alias fails within seconds and rolls back, which is your signal that its reload mode is wrong. get_certificate_chain needs Python 3.10 or newer, which ansible-core 2.22 already requires. For a service that does not speak TLS directly on a port, set tls_postcheck: false and check it another way.
Step 10: Wire Up Rollback and Batches
The rollback restores whatever was backed up, reactivates the service, and waits for the port to answer:
---
- name: Look for backed-up copies of each file
ansible.builtin.stat:
path: "{{ tls_backup_dir }}/{{ item | basename }}"
get_checksum: false
loop: "{{ tls_dest_paths }}"
register: tls_backups
- name: Restore the backed-up files
ansible.builtin.copy:
src: "{{ tls_backup_dir }}/{{ item.item | basename }}"
dest: "{{ item.item }}"
remote_src: true
owner: "{{ tls_owner }}"
group: "{{ tls_group }}"
mode: preserve
loop: "{{ tls_backups.results }}"
loop_control:
label: "{{ item.item }}"
when: item.stat.exists
diff: false
- name: Reactivate the service on the restored files
ansible.builtin.import_tasks: activate.yml
- name: Confirm the port answers again
ansible.builtin.wait_for:
host: "{{ ansible_host }}"
port: "{{ tls_port }}"
timeout: 60
delegate_to: localhost
become: false
main.yml ties the pieces together:
---
- name: Pre-flight checks (nothing on the host changes)
ansible.builtin.import_tasks: preflight.yml
- name: Back up the files this alias will replace
ansible.builtin.import_tasks: backup.yml
- name: Install, activate and verify, rolling back on any failure
block:
- name: Install the new files
ansible.builtin.import_tasks: install.yml
- name: Validate and reload or restart the service
ansible.builtin.import_tasks: activate.yml
- name: Check what the live port serves
ansible.builtin.import_tasks: postcheck.yml
when: tls_postcheck | bool and not ansible_check_mode
rescue:
- name: Record the failed step
ansible.builtin.set_fact:
tls_failed_step: "{{ ansible_failed_task.name }}"
- name: Restore the previous files and reactivate
ansible.builtin.import_tasks: rollback.yml
# A rescued host does not count toward max_fail_percentage, so fail it here,
# after every host in the batch has finished its own deploy or rollback.
- name: Fail this alias if it was rolled back
ansible.builtin.fail:
msg: >-
Rolled back after "{{ tls_failed_step }}" failed.
Previous files restored from {{ tls_backup_dir }}.
when: tls_failed_step is defined
The final fail sits outside the block on purpose. Ansible’s documentation says a rescued task does not count toward max_fail_percentage, so a host that rolled back successfully would otherwise look healthy and the next batch would proceed. Failing it after the block also means every other host in the batch has finished its own deploy or rollback before the run stops. Unreachable hosts never enter rescue, so a host that drops off the network mid-deploy needs the manual rollback below.
The playbook runs one canary alias first, then three at a time:
---
- name: Deploy TLS certificates
hosts: all
become: true
gather_facts: false
serial: [1, 3] # one canary host, then three at a time
max_fail_percentage: 0 # any failed host stops the next batch
roles:
- tls_deploy
And a manual rollback for one alias, using a backup directory the deploy printed or that you find under /var/backups/tls-deploy/<alias>/:
---
# Manual rollback of one alias to a backup taken by deploy-certs.yml:
# ansible-playbook rollback.yml --limit web1-example-com \
# -e tls_backup_dir=/var/backups/tls-deploy/web1-example-com/20261123T161500Z
- name: Roll back TLS files from a backup
hosts: all
become: true
gather_facts: false
serial: 1
tasks:
- name: Require an explicit backup directory and a single host
ansible.builtin.assert:
that:
- tls_backup_dir is defined
- ansible_play_hosts_all | length == 1
fail_msg: Pass -e tls_backup_dir=... and --limit one alias.
- name: Restore and reactivate
ansible.builtin.include_role:
name: tls_deploy
tasks_from: rollback.yml
Step 11: Dry-Run a Canary, Then Deploy
Check the syntax, then do a --check run against one alias. In check mode the pre-flight and the chain verification run for real, the backup is skipped, and the install and reload steps only report what they would change.
ansible-playbook deploy-certs.yml --syntax-check
ansible-playbook deploy-certs.yml --ask-vault-pass --check --limit web1-example-com
The syntax check prints playbook: deploy-certs.yml. Then deploy, one alias first if you like:
ansible-playbook deploy-certs.yml --ask-vault-pass --limit web1-example-com
ansible-playbook deploy-certs.yml --ask-vault-pass
PLAY RECAP should show failed=0 for every alias. rescued=1 on an alias means it rolled back, and its fail task says which step failed.
Verify
Check every name from outside, independent of Ansible. Run from any machine that can reach the servers:
for name in www.example.com shop.example.com api.example.com:8443 www.example.net; do
host=${name%%:*}; port=${name#*:}; [ "$port" = "$name" ] && port=443
echo "== $name"
openssl s_client -connect "$host:$port" -servername "$host" </dev/null 2>/dev/null \
| openssl x509 -noout -fingerprint -sha256 -enddate
done
Each name should show the new certificate’s fingerprint and notAfter date. Compare with the file:
openssl x509 -in files/certs/example.com/cert.pem -noout -fingerprint -sha256 -enddate
On a server, confirm the key’s mode and owner and that a backup exists:
sudo stat -c '%a %U:%G %n' /etc/nginx/tls/example.com.key
sudo ls /var/backups/tls-deploy/web1-example-com/
Expect 600 root:root /etc/nginx/tls/example.com.key and one timestamped directory per run.
Troubleshooting
A dry run deployed the wrong domain’s certificate, and it was not a dry run: One machine sat in four domain groups, each setting the same variables. Ansible merges groups at the same level in alphabetical order and the last one wins, so one domain’s values overrode the others.
--limitfilters hosts, not variables, so limiting to one group did not help, and I had left off--check. Fix: one alias per domain per machine (Step 3),ansible-inventory --host <alias>to confirm what each alias resolves to, and the pre-flight check that each alias is in exactly onewildcard_*group.Deploying one domain broke chain verification on two others: Several virtual hosts on one Apache server pointed at a single shared intermediate file. Deploying one domain’s new intermediate over it changed the chain for the other domains, which were still on the old one. Fix: bundle the chain into each domain’s certificate file (Apache 2.4.8 and later supports this) and enforce the domain name in every destination file name, which the pre-flight does.
Unsupported parameters for (ansible.legacy.copy) module: diff:diff: falsewas indented as a parameter ofcopy. It is a task keyword and belongs at the same level ascopy:andname:. Before I added it at all,--diffprinted an old unencrypted private key to my terminal; that key was being retired, and I flagged its certificate for revocation. Fix:diff: falseandno_log: trueat task level on every task that touches key material, plusalways = Falseunder[diff]inansible.cfg.A host was left half-deployed: new certificate, old key: In that same failed run, the certificate task succeeded and the key task failed. Apache was still serving from memory, but a restart would have paired the new certificate with the old key, failed, and taken down every site on the machine. Fix: verify the key against the certificate before touching anything, and put install, validate and reload in a block whose rescue restores the backup.
The re-run would have overwritten the backup: My first version backed up into one shared
Old/directory, so re-running a deploy, or deploying another domain, copies the new files over the only copy of the old ones. I had to copy the originals aside by hand before re-running. Fix: a new backup directory per alias per run.nginx rejected the CA’s files: The downloaded certificates started with a UTF-8 byte-order mark (bytes
EF BB BF). In my fleet that broke nginx. On a test machine with OpenSSL 3.0.13 a BOM alone parsed fine, but a PEM file without a trailing newline, concatenated with the next one, made OpenSSL find no certificates at all. Fix:prep_certs.shstrips the BOM and carriage returns and guarantees a trailing newline; the pre-flight rejects files that do not start with-----BEGIN CERTIFICATE-----.A restart handler took the remote-desktop proxy down: The old handler ran
pkill websockifyand assumed something would start it again. Nothing did. Fix: run the service under a systemd unit withRestart=on-failure, and usereloadeverywhere a service supports it, since a restart drops every open connection.A service failed to start after a restart with
Errno 98(address already in use): Its log showed the old process crashing on stop and systemd starting the new one within a second, before the old socket was released. Fix: stop, wait until nothing holds the port, then start. That istls_reload_mode: restartin Step 8.The prep script hung: The key was passphrase-protected, and
opensslsat waiting for a passphrase at a prompt nobody saw. Fix:KEYPASSin the environment for that command (-passin env:KEYPASS), andtls_key_passphrase(vault-encrypted) for the pre-flight. If Apache must keep the key encrypted on disk,SSLPassPhraseDialog exec:/path/to/programmakes it ask a program for the passphrase at startup instead of a terminal.Ad-hoc commands kept failing on nested quotes:
ansible <host> -m shell -a '...'with quotes inside quotes broke repeatedly. Fix: write the commands to a script and run it withansible <host> -m ansible.builtin.script -a ./check.sh, which copies the script over and runs it.Domain validation failed with “challenge not found in node”, then “quorum requirements not met”: This happened for one zone through my reseller, although the DNS records were correct and a sibling zone at the same registrar validated. My reading is that it came from multi-perspective validation, where the CA checks DNS from several network locations and only a limited number may disagree; I did not confirm the cause. Email validation got the certificate issued in time. With validation reuse shrinking toward 10 days, start renewals early and keep a second validation method ready.
A Java appliance would not import the wildcard key: Its bundled
keytoolrejected the key with a PKCS#8 parsing error. I restored the keystore from backup and left that appliance on a self-signed certificate; this one is unresolved. Back up any keystore before touching it, and try imports on a copy.The files changed but the service still serves the old certificate: The service loads its certificate only at start, so a reload does nothing. The post-check catches it because the served fingerprint differs. Switch that alias to
tls_reload_mode: restart.Old clients fail after a renewal with
unable to get local issuer certificateorunknown ca: The CA moved to a new root that those clients do not have. Serve the CA’s cross certificate after the intermediate, keep the old root intls_trust_anchors, and test as in Step 5.Clients reject a brand-new certificate that verifies fine on your machine: Check the client’s clock. A certificate is invalid before its
notBeforetime, and a device whose clock is behind sees a certificate issued this morning as not yet valid. Reproduce it with-attime(seconds since the epoch):openssl verify -attime $(date -d '2 days ago' +%s) -CAfile <ROOT> -untrusted chain.pem cert.pemreportscertificate is not yet valid.Two aliases in this batch share a machine: The pre-flight found two aliases with the sameansible_hostin one batch. Move one further down the inventory, or setserial: 1.
Sources and further reading
- CA/Browser Forum Baseline Requirements (version 2.3.1): the validity schedule (200, 100 and 47 days) and validation reuse periods in section 1.2.2; multi-perspective issuance corroboration in section 3.2.2.9.
- Ballot SC-081v3: the ballot that set the schedule and its April 2025 vote.
- GlobalSign: AlphaSSL Root and Intermediate Certificates: the R46 AlphaSSL intermediate as default and the R6 intermediate for certificates issued before July 27, 2026.
- GlobalSign: Cross Certificates: the “R46 signed by R6” cross certificate and its validity.
- GlobalSign: Root Certificates: validity of Root R6 and Root R46 and R46’s role as R6’s replacement.
- Let’s Encrypt: Challenge Types: wildcards need DNS-01; HTTP-01 uses port 80.
- ansible-core on PyPI: current release and Python requirement.
- Ansible: Error handling in playbooks:
max_fail_percentageper batch, and the percentage must be exceeded. - Ansible: Blocks: rescued tasks and
max_fail_percentage,ansible_failed_task, unreachable hosts. - Ansible: How to build your inventory: alphabetical group variable merging, aliases with
ansible_host. - Ansible: Playbook keywords:
diff,no_log,serial,delegate_toand where each is allowed. - ansible.builtin.copy source and atomic_move:
follow,backup,mode, and the temporary file and rename. - community.crypto collection:
x509_certificate_info,openssl_privatekey_infoandget_certificateoptions and return values (3.6.0). - OpenSSL verification options and openssl-s_client:
-no-CApath,-no-CAstore,-untrusted, trusted-first path building,-attime, and-showcertsshowing the chain as sent. - Apache mod_ssl:
SSLCertificateFilewith intermediates since 2.4.8,SSLCertificateChainFileobsolete,SSLPassPhraseDialog exec:. - Apache: Stopping and Restarting: graceful restart and its limits.
- nginx: Configuring HTTPS servers and nginx: Controlling nginx: certificate before chain,
key values mismatch, and whatHUPdoes. - Python ssl.create_default_context: with a
cafile, only that file is trusted, which is how the post-check tests one root at a time.