如何自动续期 90 天证书?

解读

在国内前端工程化面试中,面试官抛出“自动续期 90 天证书”并非考察 DevOps 全链路,而是验证候选人能否把 Gulp 的自动化哲学延伸到运维场景:用 Node 生态工具把“证书过期”这种定时、易忘、高风险的操作变成可版本化、可回滚、可观测的代码任务。核心考点有三点:

  1. 识别 90 天证书即 Let's Encrypt 等短期免费证书;
  2. 用 Gulp 的任务调度与流式能力封装续期逻辑,而不是手动登录服务器;
  3. 兼顾国内网络痛点(DNS-01 校验、阿里云/腾讯云 API 调用、Webhook 回滚通知)。
    答不到“Gulp 怎么触发”而只讲 certbot 定时器,会被判定为“只懂运维不懂前端构建”。

知识点

  • Gulp 4 系列 API:series、parallel、watch、tree 同步异步编排
  • Node 子进程:spawn 流式输出 certbot 日志,避免 shell 注入
  • 国内 DNS 校验:阿里云 RAM 子账号 AK/SK 调用 DNS-01,绕过 80 端口备案限制
  • 证书热加载:Nginx 的 nginx -s reload 零中断,Node 服务使用 https.createServer(new cert) 无重启
  • 失败重试与回滚:gulp-retry 插件、钉钉/飞书 Webhook 告警、本地备份 /etc/letsencrypt 目录
  • CI 集成:GitHub Actions + 阿里云 OSS 镜像缓存,解决 GitHub 到国内服务器拉取超时
  • 安全合规:AK 加密进 GitHub Secret,gulp 任务运行时通过 process.env 注入,绝不硬编码

答案

  1. 项目根目录安装依赖

    npm i -D gulp@4 gulp-date-retry axios @alicloud/dns-2015-09-11
    
  2. 编写 gulpfile.js

    const { series, parallel } = require('gulp');
    const spawn = require('child_process').spawn;
    const axios = require('axios');
    const dns = require('@alicloud/dns-2015-09-11');
    const fs = require('fs');
    
    // 任务1:调用阿里云 DNS-01 添加 TXT 记录
    function addDnsTxt(cb) {
      const client = new dns({
        accessKeyId: process.env.ALC_AK,
        accessKeySecret: process.env.ALC_SK,
        endpoint: 'https://alidns.cn-hangzhou.aliyuncs.com'
      });
      return client.addDomainRecord({
        DomainName: 'example.cn',
        RR: '_acme-challenge',
        Type: 'TXT',
        Value: process.env.CERTBOT_VALIDATION
      }).then(() => cb()).catch(cb);
    }
    
    // 任务2:执行 certbot 续期
    function certRenew(cb) {
      const cert = spawn('certbot', [
        'certonly',
        '--dns-dns_ali',
        '--dns-dns_ali-credentials', './ali.ini',
        '-d', '*.example.cn',
        '--deploy-hook', 'gulp deployCert'   // 续期成功后触发 Gulp 部署任务
      ], { stdio: 'inherit' });
      cert.on('close', code => code === 0 ? cb() : cb(new Error('certbot 失败')));
    }
    
    // 任务3:部署证书到 Nginx 并热加载
    function deployCert(cb) {
      const dest = '/etc/nginx/ssl/';
      const cmd = `cp /etc/letsencrypt/live/example.cn/fullchain.pem ${dest} && \
                   cp /etc/letsencrypt/live/example.cn/privkey.pem ${dest} && \
                   nginx -s reload`;
      const sh = spawn('bash', ['-c', cmd], { stdio: 'inherit' });
      sh.on('close', code => {
        if (code === 0) {
          axios.post('https://oapi.dingtalk.com/robot/send?access_token=xxx', {
            msgtype: 'text',
            text: { content: '证书已续期并热加载成功' }
          });
          cb();
        } else {
          cb(new Error('Nginx 重载失败'));
        }
      });
    }
    
    // 任务4:定时入口,每天 02:30 检查
    function schedule(cb) {
      require('node-schedule').scheduleJob('30 2 * * *', () => {
        series(addDnsTxt, certRenew, deployCert)(err => {
          if (err) console.error('续期失败', err);
        });
      });
      cb();
    }
    
    exports.renew = series(addDnsTxt, certRenew, deployCert);
    exports.default = schedule;
    
  3. 服务器配置

    • 赋予 certbot 免 sudo 调用权限:visudo 添加 www-data ALL=(ALL) NOPASSWD: /usr/bin/certbot, /bin/systemctl reload nginx
    • 使用 systemd 守护 Gulp:gulp default 作为常驻服务,崩溃自动重启
  4. 本地测试

    gulp renew   // 手动触发一次,确认 DNS、证书、Nginx 全链路 OK
    

至此,90 天证书续期完全代码化,版本库可审计、回滚,符合国内云厂商 DNS API 与备案要求,也体现了 Gulp“把重复动作变成可维护代码”的核心思想。

拓展思考

  • 如果公司采用通配符证书+多云灾备,可把 deployCert 改成并行上传至阿里云 SLB、腾讯云 CLB、又拍云 CDN,用 Gulp parallel 同时更新,失败一个即回滚全部。
  • 针对容器化部署,把证书写入 Kubernetes Secret,通过 gulp-k8s 插件触发 kubectl rollout restart deployment/web,实现“证书更新+Pod 滚动”一键完成。
  • 为了零信任安全,可将 AK/SK 放进阿里云 KMS,Gulp 任务运行时通过 STS 临时凭证访问,过期时间 15 min,即使日志泄露也无法复用。