总结基于Hugo的静态博客搭建过程:将GitHub作为托管Markdown文件的仓库,文件修改后触发基于GitHub Actions 的CI/CD的流程,部署至远程服务器目录,使用Nginx对外提供服务。

目标节点

安装Nginx为静态站点提供http服务

  1. sudo apt install nginx
  2. 配置nginx,进行地址、静态文件目录等配置,使用sudo nginx -s reload更新ngingx服务

使用Let’s Encrypt配置https

使用免费的Let’s Encrypt 来配置Nginx的https证书,使用certbot进行自动化配置及定时证书更新,参考Ubuntu下的cerbot安装指引。

CI/CD

实现效果:主分支有更新时,触发编译及部署,hugo编译出的静态文件通过scp部署在目标节点上;其他分支发起的PR会触发编译检查。

依托GitHub Actions实现,分为build与deploy两个阶段,在.github/workflows目录下分别建立ci.ymlpr.yml两个文件,ci.yml针对master分支进行编译和部署;pr.yml为针对Pull Request情况,仅进行编译。

ci.yml示例如下:

name: Build and Deploy
on:
  workflow_dispatch:
  push:
    branches:
      - main
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: true  # Fetch Hugo themes (true OR recursive)
          fetch-depth: 0    # Fetch all history for .GitInfo and .Lastmod

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: '0.98.0'
          # extended: true

      - name: Build
        run: hugo --minify
        
      - name: Deploy
        run: |
          which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y  )
          eval $(ssh-agent -s)
          ssh-add <(echo "$SSH_PRIVATE_KEY" )
          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          ssh-keyscan $DEPLOY_IP >> ~/.ssh/known_hosts
          chmod 644 ~/.ssh/known_hosts
          scp -r public/* $DEPLOY_ACCOUNT@$DEPLOY_IP:$DEPLOY_LOCATION          
        env:
          SSH_PRIVATE_KEY: ${{secrets.SSH_KEY}}
          DEPLOY_IP: ${{secrets.SERVER_IP}}
          DEPLOY_ACCOUNT: bot
          DEPLOY_LOCATION: /var/www/blog

其中build环境借助hugo-setup 这个第三方workflow实现hugo环境的快速建立。而部署阶段安全起见,使用脚本借助scp直接将生产的文件复制到服务器指定目录下。注意要在GitHub Actions的配置里,将所需的secret信息SSH_KEY, SERVER_IP单独配置。

参考