Jenkins CI/CD 入门实战:从零搭建自动构建流水线

从安装 Jenkins、配置 Gitee 凭据,到用 Webhook + ngrok 实现 push 代码自动构建 Hugo 网站,记录完整的实操踩坑过程。

1. 为什么要用 Jenkins

Jenkins 是开源的持续集成/持续部署(CI/CD)工具。核心作用:代码 push 到 Git 仓库后,自动完成「拉代码 → 编译 → 测试 → 打包 → 部署」等一系列操作。

$$你 push 代码到 Gitee ↓ Jenkins 自动拉取最新代码 ↓ 自动构建(编译 / hugo / 打包) ↓ 自动部署 / 归档产物$$

核心概念

概念说明
Job / Item一个构建任务
Pipeline用 Groovy 脚本定义的构建流水线
Stage流水线里的一个阶段(拉代码→构建→部署)
Step每个阶段里的具体操作
WebhookGit 仓库通知 Jenkins “有新提交了”

2. 安装与启动

前提:Java

Jenkins 是 Java 写的,必须装 Java 17 或 21。太新的版本(如 Java 26)启动会报错:

$$Running with Java 26 ... not yet fully supported. Supported Java versions are: [17, 21]$$

解决: 装 Java 21,用显式路径启动:

wget https://get.jenkins.io/war-stable/latest/jenkins.war -O /tmp/jenkins.war
/opt/jdk-21/bin/java -jar /tmp/jenkins.war --httpPort=9090

推荐:Docker 方式(不污染系统 Java 环境)

docker run -d \
  --name jenkins \
  -p 9090:8080 \
  -v jenkins_home:/var/jenkins_home \
  jenkins/jenkins:lts-jdk21

3. 初始化配置

访问 http://localhost:9090

  1. 输入初始密码(终端启动日志里有,或 cat ~/.jenkins/secrets/initialAdminPassword
  2. 选择插件安装方式(建议跳过推荐插件,按需安装)
  3. 创建管理员账号(记好密码! 忘了很麻烦,见第 8 节)

配置 Jenkins URL

Manage Jenkins → System → Jenkins URL

  • 只用本机测试:http://localhost:9090/
  • 需要 Webhook 自动触发:填 ngrok 公网地址

4. 插件安装

Manage Jenkins → Plugins → Available plugins

必装插件

插件用途
Git从 Git 仓库拉代码
PipelinePipeline 类型任务(没有它只有 Freestyle)
GiteeGitee 仓库集成 + Webhook 触发

踩坑:插件版本兼容

$$Failed to load: ASM API Plugin ... Jenkins (2.504.3) or higher required$$

插件版本要求 Jenkins 版本更新,升级 Jenkins 到最新 LTS 解决:

wget https://get.jenkins.io/war-stable/latest/jenkins.war -O /tmp/jenkins.war

5. 创建构建任务

Pipeline 项目(推荐)

New Item → 名称 → Pipeline → OK

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git url: 'git@gitee.com:你的用户名/仓库名.git',
                    branch: 'master'
            }
        }

        stage('Build') {
            steps {
                sh 'echo 构建中 && ls -la'
            }
        }
    }

    post {
        success { echo '✅ 构建成功' }
        failure { echo '❌ 构建失败' }
    }
}

SaveBuild Now → 看 Console Output。

调试小技巧

先跑纯 Debug 脚本验证 Jenkins 环境正常,再逐步加真实步骤:

pipeline {
    agent any
    stages {
        stage('Debug') {
            steps {
                echo '流水线跑通了!'
                sh 'echo 目录: $(pwd) && echo 用户: $(whoami)'
            }
        }
    }
}

6. Gitee 凭据配置

生成 Gitee 个人访问令牌

打开 https://gitee.com/profile/personal_access_tokens

  • 标题:jenkins
  • 权限:勾选 projects
  • 生成并复制

添加凭据

Manage Jenkins → Credentials → System → Global credentials → Add Credentials

字段填什么
KindUsername with password
UsernameGitee 用户名
Password个人访问令牌(不是登录密码)
IDgitee-git

Pipeline 脚本里使用

git url: 'https://gitee.com/用户名/仓库.git',
    branch: 'master',
    credentialsId: 'gitee-git'

⚠️ 踩坑:凭据类型

  • Gitee API Token 类型(Gitee 插件加的)不能用于 git clone,只能用于 Gitee API
  • git clone 必须用 Username with password 类型
  • 报错 CredentialId "xxx" could not be found = 凭据类型不对或不存在

省事方案:SSH 地址

本机已配好 Gitee SSH 密钥时,直接用 SSH 地址不需要任何凭据

$$git@gitee.com:用户名/仓库.git$$

7. 自动触发(Webhook + ngrok)

问题:Gitee 访问不到本地 Jenkins

Gitee 服务器在外网,访问不了 localhost:9090,需要内网穿透:

./ngrok config add-authtoken 你的token
./ngrok http 9090

启动后得到公网地址,如:https://despise-siamese-errand.ngrok-free.dev

配置步骤

  1. Jenkins URL 改为 ngrok 地址(Manage Jenkins → System)
  2. 任务 → ConfigureBuild Triggers → 勾选 Gitee webhook trigger
  3. 页面会显示 Webhook URL(新版插件路径带参数,以页面显示为准),复制它
  4. Gitee 仓库 → 管理WebHooks添加 WebHook
    • URL:上一步复制的地址
    • 触发事件:勾选 Push

验证

改仓库内容 → push → Jenkins 自动开始构建。

替代方案:定时轮询

不想搞 Webhook 的话,Build Triggers → Poll SCM

$$H/10 * * * *$$

每 10 分钟检查一次仓库变更。

8. 常见问题排查

8.1 No valid crumb(403)

Jenkins 的 CSRF 防护拦截了 Webhook/API 请求。

解决(测试环境): 删除 ~/.jenkins/config.xml 里的:

<crumbIssuer class="hudson.security.csrf.DefaultCrumbIssuer"/>

重启 Jenkins。

8.2 忘掉管理员密码

方案一:删密码哈希

停 Jenkins → 编辑 ~/.jenkins/users/admin/config.xml → 删除整段:

<hudson.security.HudsonPrivateSecurityRealm_-Details>
  <passwordHash>...</passwordHash>
</hudson.security.HudsonPrivateSecurityRealm_-Details>

重启后登录输任意密码即可重设。

方案二:直接替换密码哈希

python3 -c "
import bcrypt
print(bcrypt.hashpw(b'admin123', bcrypt.gensalt(10, prefix=b'2a')).decode())
"

替换 config.xml 里的 passwordHash 值(保留 #jbcrypt: 前缀)。

方案三:禁用安全验证重建账户

  • 停 Jenkins
  • ~/.jenkins/config.xml<useSecurity>true</useSecurity> 改为 false
  • 重启 → 免登录 → Manage Jenkins → Users → 新建账户
  • 再改回 true 重启

8.3 Git clone 认证失败

$$Authentication failed for 'https://gitee.com/...'$$

解决: 仓库私有 → 配置凭据(第 6 节);或换 SSH 地址。

8.4 Git URL 格式错误

$$❌ https:///gitee.com:用户名/仓库.git (HTTPS 和 SSH 格式混了) ✅ https://gitee.com/用户名/仓库.git ✅ git@gitee.com:用户名/仓库.git$$

8.5 Hugo 构建找不到配置

$$ERROR Unable to locate config file or config directory$$

原因: Jenkins 拉错仓库了。确认 git url 指向正确的 Hugo 网站仓库。

9. 完整示例:Hugo 网站自动构建部署

场景

migelan-touch 是 Hugo 网站仓库,public/ 目录提交到 Gitee。目标:push 源码 → 自动 hugo 构建 → 自动提交 public/。

Pipeline 脚本

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git url: 'git@gitee.com:用户名/migelan-touch.git',
                    branch: 'master'
            }
        }

        stage('构建 Hugo') {
            steps {
                sh 'hugo'
            }
        }

        stage('提交构建产物') {
            steps {
                sh '''
                    git add public/
                    git commit -m "auto build: $(date)" || echo "无变更跳过"
                    git push origin master
                '''
            }
        }
    }

    post {
        success { echo '✅ 网站已自动更新' }
        failure { echo '❌ 构建失败' }
    }
}

配套:Webhook 自动触发

按第 7 节配置 Gitee Webhook,push 源码后全自动。

10. 常用命令速查

# 启动 / 停止 Jenkins
/opt/jdk-21/bin/java -jar /tmp/jenkins.war --httpPort=9090
pkill -f jenkins.war

# 查看初始密码
cat ~/.jenkins/secrets/initialAdminPassword

# 查看日志
tail -100 ~/.jenkins/logs/jenkins.log

# 重新加载配置(不重启)
curl http://localhost:9090/reload

# ngrok 启动 + 查看公网地址
./ngrok http 9090
curl -s http://localhost:4040/api/tunnels | grep public_url