This repository has been archived on 2025-02-14. You can view files and clone it, but cannot push or open issues or pull requests.
esh/esh_letsencrypt/recipes/certs.rb
2025-02-15 01:05:58 +09:00

84 lines
2.5 KiB
Ruby

#
# Cookbook:: esh_letsencrypt
# Recipe:: certs
#
# Copyright:: 2022, https://easyself.host
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
email = node['esh']['letsencrypt']['certs']['email']
certs_list = node['esh']['letsencrypt']['certs']['list']
certs_list.each do |domains|
if match = domains.match(/-d\s+(\S+)/)
first_domain = match[1]
end
execute "certbot certonly #{domains}" do
command <<~EOT
certbot certonly \
--standalone \
--non-interactive \
--agree-tos \
--email #{email} \
--key-type ecdsa \
--elliptic-curve secp384r1 \
--http-01-port=8899 \
#{domains}
EOT
not_if { ::File.directory?("/etc/letsencrypt/live/#{first_domain}") }
action :run
end
end
certs_list.each do |domains|
if match = domains.match(/-d\s+(\S+)/)
first_domain = match[1]
end
execute "certbot renew #{domains}" do
command <<~EOT
certbot renew \
--cert-name #{first_domain} \
--http-01-port=8899
EOT
only_if <<~EOT
cert_status=$(certbot certificates #{domains} 2>/dev/null)
valid_days=$(echo "$cert_status" | grep 'Expiry Date' | sed 's/.*VALID: \\([0-9]*\\) days.*/\\1/')
test $valid_days -le 30
EOT
action :run
end
end
# Copy certificates for HAProxy (if present)
certs_list.each do |domains|
if match = domains.match(/-d\s+(\S+)/)
first_domain = match[1]
end
execute "copy certificate #{first_domain} for HAproxy" do
command <<~EOT
cat /etc/letsencrypt/live/#{first_domain}/fullchain.pem \
/etc/letsencrypt/live/#{first_domain}/privkey.pem \
> /etc/haproxy/crt/#{first_domain}.pem
EOT
only_if { File.directory?('/etc/haproxy/crt') }
only_if <<~EOT
test -f /etc/haproxy/crt/#{first_domain}.pem || exit 0
grep -qvFf \
/etc/letsencrypt/live/#{first_domain}/fullchain.pem \
-f /etc/letsencrypt/live/#{first_domain}/privkey.pem \
/etc/haproxy/crt/#{first_domain}.pem
EOT
notifies :reload, 'service[haproxy]', :delayed
action :run
end
end