Let's Encrypt 免费证书使用
1、环境介绍
操作系统:龙蜥OS 8.9
中间件:nginx
证书:Let’s Encrypt
https://letsencrypt.org/zh-cn/
证书部署工具:acme.sh
域名托管厂商:阿里云
2、安装acme.sh
curl https://get.acme.sh | sh
source ~/.bashrc
3、创建阿里云RAM用户
登录阿里云 RAM 控制台,创建用户 & AccessKey
访问:https://ram.console.aliyun.com/users
创建 AccessKey,记住 ID 和 Secret
echo 'export Ali_Key="你的AccessKeyId"' >> ~/.bashrc
echo 'export Ali_Secret="你的AccessKeySecret"' >> ~/.bashrc
source ~/.bashrc
这里需要授权AliyunDNSFullAccess
4、申请证书
acme.sh --issue --dns dns_ali -d gubeisz.net -d '*.gubeisz.net' --server letsencrypt
阿里云这里也会生成txt记录
计划任务里会自动更新证书
5、使用ansible 自动分发证书
ansible 服务器免登录
ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.99.99.120
代理到证书服务器免认证
ssh-keygen -t rsa -b 4096 -C "proxy-to-cert" -N "" -f ~/.ssh/id_rsa
ssh-copy-id root@10.99.50.11
playbook
- name: 分发 TLS 证书到 Nginx 服务器
hosts: proxy
gather_facts: false
vars:
ansible_python_interpreter: /opt/python/install/bin/python3
# 证书服务器信息
cert_server_host: 10.99.50.11
cert_remote_path: /root/.acme.sh/gubeisz.net_ecc
cert_files:
- fullchain.cer
- gubeisz.net.key
# 目标服务器 Nginx 安装信息
nginx_cert_dir: /usr/local/nginx/conf/cert/gubeisz.net
nginx_reload_cmd: /usr/local/nginx/sbin/nginx -s reload
# SSH 连接用账号(如有 sudo 权限)
ansible_ssh_user: root
ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
tasks:
- name: 创建 Nginx 证书目录
file:
path: "{{ nginx_cert_dir }}"
state: directory
owner: root
group: root
mode: '0755'
- name: 从 cert-server 拉取证书文件
ansible.builtin.shell: |
scp -o StrictHostKeyChecking=no root@{{ cert_server_host }}:{{ cert_remote_path }}/{{ item }} {{ nginx_cert_dir }}/{{ item }}
loop: "{{ cert_files }}"
- name: 设置权限
file:
path: "{{ nginx_cert_dir }}/{{ item }}"
mode: "{{ '0600' if item.endswith('.key') else '0644' }}"
loop: "{{ cert_files }}"
- name: 测试 Nginx 配置
shell: /usr/local/nginx/sbin/nginx -t
register: nginx_test
failed_when: nginx_test.rc != 0
changed_when: false
- name: 重载 Nginx
shell: "{{ nginx_reload_cmd }}"