r/lego-nginx: Configure LEGO for nginx

The *lego-nginx* role automates obtaining certificates for *nginx* via
ACME using `lego`.  It generates a shell script with the appropriate
arguments for `lego run`, runs it once to obtain a certificate
initially, then schedules it to run periodically via a systemd timer
unit. Using `lego`'s "hook" capability, the script signals the `nginx`
server process to reload.  This uses `doas` for now, but could be
adapted easily to use `sudo`, if the need ever arises.
This commit is contained in:
2025-07-08 11:29:36 -05:00
parent 0393f074a4
commit 6d1442faf0
11 changed files with 194 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
# vim: set ft=yaml.jinja :
- name: ensure lego webroot exists
file:
path: /var/www/lego
owner: lego
group: lego
mode: u=rwx,go=rx
setype: httpd_sys_content_t
state: directory
tags:
- webroot
- name: ensure lego is allowed to reload nginx
lineinfile:
dest: /etc/doas.conf
line: permit nopass lego cmd /usr/sbin/nginx args -s reload
tags:
- doas
- name: ensure lego renew script exists
copy:
content: >+
lego
--path /var/lib/lego
--accept-tos
{% if lego_acme_server %}
--server {{ lego_acme_server }}
{% endif %}
--http --http.webroot /var/www/lego
{% for domain in lego_domains %}
--domains {{ domain }}
{% endfor %}
--email {{ lego_acme_email }}
run
--run-hook 'doas /usr/sbin/nginx -s reload'
dest: /var/lib/lego/renew.sh
owner: lego
group: lego
mode: u=rwx,go=rx
tags:
- lego-renew
- name: ensure server certificate exists
become: true
become_user: lego
command: /bin/sh /var/lib/lego/renew.sh
args:
creates: /var/lib/lego/certificates/{{ lego_domains[0] }}.json
tags:
- cert

View File

@@ -0,0 +1,8 @@
- import_tasks: nginx.yml
tags:
- nginx
- lego-nginx
- import_tasks: cert.yml
tags:
- lego-nginx

View File

@@ -0,0 +1,37 @@
- name: ensure nginx is installed
package:
name: nginx
state: present
tags:
- install
- name: ensure nginx is running
service:
name: nginx
state: started
tags:
- service
- name: ensure nginx is configured for lego
copy:
src: lego.nginx.conf
dest: /etc/nginx/default.d/lego.conf
owner: root
group: root
mode: u=rw,go=r
notify:
- reload nginx
tags:
- nginx-config
- name: ensure firewall allows http acme challenges
firewalld:
service: http
state: enabled
immediate: true
when: host_uses_firewalld|d(true)
tags:
- firewalld
- name: flush handlers
meta: flush_handlers