Jenkins安装

1440 字
7 分钟
Jenkins安装

[!jenkins文章分为三部分]

第一部分为docker安装Jenkins与常用插件使用,此文章

第二部分为运行pipeline并通过k8s pod打包 [[Jenkins-pipeline使用]]

第三部分为,pipeline高阶使用,如map,共享库,参考 [[Jenkins-pipeline进阶使用]]

1 安装#

[!attention] 这里使用的lts镜像,官网查的版本不准,建议去这里查[Jenkins lts 更新记录](https://www.jenkins.io/changelog-stable/ 把2.492.3换成查到的最新版本,如果需要jdk8就改成lts-jdk8 -如果不需要集成k8s,取消注释,准备好二进制

services:
jenkins:
image: ccr.ccs.tencentyun.com/ccops/all:jenkins-2.492.3-lts-jdk17
user: root
container_name: jenkins
restart: always
environment:
TZ: "Asia/Shanghai"
JENKINS_UC: "https://mirrors.tuna.tsinghua.edu.cn/jenkins/"
JENKINS_UC_DOWNLOAD: "https://mirrors.tuna.tsinghua.edu.cn/jenkins/"
JAVA_OPTS: "-Dhudson.model.DownloadService.noSignatureCheck=true"
# MAVEN_HOME: "/usr/local/maven"
# PATH: "$JAVA_HOME/bin:$MAVEN_HOME/bin:$PATH"
ports:
- "8080:8080"
- "50000:50000"
volumes:
- ./data:/var/jenkins_home
- /etc/localtime:/etc/localtime
# pipeline复用
# - ./script:/var/jenkins_home/script
# - bin/docker:/usr/bin/docker
# - bin/kubectl:/usr/bin/docker
# - bin/apache-maven-3.9.9:/usr/local/maven

1.1 准备国内源,防止插件安装不上#

2.492.1换成对应的版本,我这是2.492.3,但是没有,只能先用这个 如果版本不对应插件可能安装不上

Terminal window
cat data/hudson.model.UpdateCenter.xml
<?xml version='1.1' encoding='UTF-8'?>
<sites>
<site>
<id>default</id>
<url>https://mirrors.huaweicloud.com/jenkins/updates/dynamic-stable-2.492.1/update-center.json</url>
</site>
</sites>

2 登陆#

查看密码

Terminal window
cat data/secrets/initialAdminPassword
4c0418dc42524016beb2aa7a67196693

image.png
image.png

登录后选择自己安装插件,先安装这几个

image.png
image.png

3 插件#

3.1 安装#

http://jenkins:8080/manage/pluginManager/available

名称作用
Pipeline: Stage View展示pipeline步骤
Git通用clone代码插件
Git Parameter能够与 Git 插件结合使用,动态获取 Git 项目中分支信息
Docker Pipeline构建隐藏docker build,账号密码等命令
Rebuilder重复上次构建
AnsiColor扩展 echo -e指令,输出增加颜色。
Config File Provider存储 k8s Deployment 模板等信息
Pipeline Utility Steps操作文件的插件,与Config File Provider结合使用
Kubernetes使用 Kubernetes 集群运行 Jenkins agent
Lark Notice Plugin可选,钉钉,飞书告警插件,不支持在线安装,点击这里安装
Pipeline: Groovy Libraries可选,共享 Pipeline 脚本
Job Configuration Historypipeline回滚功能
Extended Choice Parameter支持多选,但现在有漏洞并且不维护,2025年4月17日
Active Choices更高级的扩展选项,也支持多选,但配置复杂
Publish Over SSH支持远程传输文件与执行命令
Material Theme与Blue Ocean美化页面,但Blue Ocean支持功能比较少,比如不支持Active Choices插件
Kubernetes CLI隐藏 kubeconfig
Generic Webhook Trigger通过解析GitLab Webhook的JSON数据动态触发对应Job

3.2 插件使用#

3.2.1 Git#

pipeline 例子

git(credentialsId: "${GIT_ID}", url: "$GIT_URL", branch: "${BRANCH_NAME}", changelog: true, poll: false)

3.2.2 AnsiColor#

3.2.3 Config File Provider#

http://jenkins:8080/manage/configfiles/

image.png
image.png

3.2.4 Pipeline Utility Steps#

pipeline例子

onfigFileProvider([configFile(fileId: "${KUBERNETES_DEPLOYMENT_ID}", targetLocation: "deployment.yaml")]){
script {
// 替换deployment文件中的变量
deploy = readFile encoding: "UTF-8", file: "deployment.yaml"
deployfile = deploy.replaceAll("#APP_NAME","${APP_NAME}")
.replaceAll("#APP_REPLICAS","${KUBERNETES_APP_REPLICAS}")
.replaceAll("#APP_IMAGE_NAME","${dockerImageName}")
// 生成新的 Kubernetes 部署文件
writeFile encoding: 'UTF-8', file: './deploy.yaml', text: "${deployfile}"
sh "cat deploy.yaml"
}
}

3.2.5 Kubernetes#

3.2.5.1 添加kubeconfig#

image.png
image.png

3.2.5.2 添加集群#

image.png
image.png

选择刚才添加的凭据

image.png
image.png
测试

image.png
image.png

3.2.5.3 Pod模板#

这里建议自己制作镜像,把maven,kubelet什么的放进来,方便维护,用k8s与不用k8s好切换 jdk版本按需选择

cat Dockerfile
FROM jenkins/inbound-agent:latest-jdk17
ADD make/kubectl /usr/bin/kubectl
ADD make/apache-maven-3.9.9 /usr/local/maven
ENV MAVEN_HOME=/usr/local/maven
ENV PATH=$JAVA_HOME/bin:$MAVEN_HOME/bin:$PATH
ENV TZ=Asia/Shanghai
USER root
RUN cp /usr/share/zoneinfo/${TZ} /etc/localtime \
&& echo "${TZ}" > /etc/timezone
USER jenkins

maven配置

cat make/apache-maven-3.9.9/conf/settings.xml
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">
<localRepository>/data/repo</localRepository>
<pluginGroups>
</pluginGroups>
<proxies>
</proxies>
<servers>
</servers>
<mirrors>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<profiles>
<profile>
<id>jdk-17</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>17</jdk>
</activation>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.compilerVersion>17</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
</settings>

pod模板

  • 为了演示这里单独加个docker in docker容器,也可以制作all镜像的时候安装docker
  • 如果加容器了就需要pipeline里添加 container(‘docker’),要不然默认用jnlp容器执行
apiVersion: v1
kind: Pod
metadata:
labels:
app: jenkins-slave
spec:
securityContext:
runAsUser: 0
privileged: true
nodeSelector:
node-role.kubernetes.io/jenkins-slave: "yes"
containers:
- name: jnlp
tty: true
workingDir: /home/jenkins/agent
image: ccr.ccs.tencentyun.com/ccops/all:inbound-jdk17-all
volumeMounts:
- name: data
mountPath: /data/repo
- name: docker
workingDir: /home/jenkins/agent
image: ccr.ccs.tencentyun.com/ccops/all:docker-28.0.4-cli
command: ["cat"]
tty: true
volumeMounts:
- mountPath: /var/run/docker.sock
name: dockersock
readOnly: true
- mountPath: /etc/docker/daemon.json
name: dockerdaemon
readOnly: true
volumes:
- name: data
nfs:
path: /data/nfs_data
server: 192.1.1.1
- name: dockersock
hostPath:
path: /var/run/docker.sock
- name: dockerdaemon
hostPath:
path: /etc/docker/daemon.json

这里添加

image.png
image.png

3.2.6 Lark Notice Plugin#

参考,很简单

3.2.7 Extended Choice Parameter#

支持多选,但有漏洞并且不在维护

pipeline {
......
parameters {
extendedChoice name: 'APP_NAME', type: 'PT_CHECKBOX', description: '请勾选所要发布的项目模块', quoteValue: false, saveJSONParameterToFile: false, value: 'app1,app2', visibleItemCount: 7, multiSelectDelimiter: ',', defaultValue: 'app1'
}
......

3.2.8 Active Choices#

properties([
parameters([
[
$class: 'ChoiceParameter',
choiceType: 'PT_CHECKBOX', // 复选
name: 'APP_NAME',
description: '选择应用',
script: [
$class: 'GroovyScript', // Groovy脚本
script: [
classpath: [],
sandbox: true,
// 要返回的结果,写在一行
script: "return ['app1', 'app2']"
]
]
]
])
])
pipeline {
......
}

3.2.9 Publish Over SSH#

3.2.9.1 添加远程主机#

image.png
image.png

3.2.9.2 Pipeline使用#

[!info]

  • {hostName} 可以写成host-213
  • xecCommand 要执行的命令
  • remoteDirectory 要创建的目录,在/data/app下
  • sourceFiles jenkins上文件路径
  • verbose 是否开启ssh执行日志,debug用
sshPublisher(publishers: [sshPublisherDesc(configName: "${hostName}", transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: """
docker-compose -f /data/app/${appName}/docker-compose.yml up -d
""", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: "${appName}/", remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'docker-compose.yml')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])

3.2.10 Generic Webhook Trigger#

[!info] 我这里的方案是 gitlab push 触发单独 job, 然后通过 webhook 传的变量运行 job 任务

这里 job 任务名称要与 gitlab 仓库名称一样, 不一样需要加判断执行哪个 job

Terminal window
pipeline {
agent any
options {
buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '5'))
timeout(time:12, unit:'HOURS')
skipDefaultCheckout()
}
triggers {
GenericTrigger(
genericVariables: [
// 提取变量
// git仓库名字,与job名称一致
[key: 'REPO_NAME', value: '$.project.name'],
// 分支名称,只有test分支触发
[key: 'BRANCH', value: '$.ref'],
// 提取提交信息,设置提交某些内容部署
[key: 'COMMIT_MSG', value: '$.commits[0].message']
],
// token, 随机生成
token: '119f7f9e9447aa4ff3b12f9542776a6e1b',
// 在构建日志中显示触发原因
causeString: 'Triggered by $REPO_NAME (Branch: $BRANCH, Commit: $COMMIT_MSG)',
// 触发器的过滤条件
regexpFilterText: '$BRANCH $COMMIT_MSG',
// 过滤文本,两个变量拼接内容为refs/heads/test cd*才部署
regexpFilterExpression: '^refs/heads/test\\b' + ' cd.*',
printContributedVariables: false,
printPostContent: false
)
}
stages {
stage('Trigger Target Job') {
steps {
script {
// 双重检查:分支+commit消息前缀
if (env.BRANCH == 'refs/heads/test' && env.COMMIT_MSG?.trim()?.toLowerCase()?.startsWith('cd')) {
// 触发同名任务(REPO_NAME变量值作为任务名)
build job: env.REPO_NAME
} else {
// 构造跳过原因说明
def skipReason = "Skipped: "
if (env.BRANCH != 'refs/heads/test') {
skipReason += "不是test分支. "
}
if (!env.COMMIT_MSG?.trim()?.toLowerCase()?.startsWith('cd')) {
skipReason += "提交内容不是cd开头. "
}
echo skipReason
}
}
}
}
}
}

gitlab 里 webhook 地址配置: http://${jenkins_url}$/generic-webhook-trigger/invoke/invoke?token=119f7f9e9447aa4ff3b12f9542776a6e1b

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Jenkins安装
https://ccops.cc/posts/5d15ec84/
作者
蹦蹦站长
发布于
2025-02-05
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
蹦蹦站长
一个养兔子的运维
公告
感谢你的来访!希望在这里能找到对你有用的内容!
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
81
分类
6
标签
45
总字数
88,456
运行时长
0
最后活动
0 天前
站点信息
构建平台
Local
博客版本
Firefly v6.12.1
文章许可
CC BY-NC-SA 4.0

文章目录