解释一个为k8s环境部署的jenkinsfile
首先见具体的文档
# 这里的部分是配置变量
# pod 的标签名
def label = "slave-${UUID.randomUUID().toString()}"
# 推送到harbor时和之后容器拉取时镜像的tag
def imageTag = "${BUILD_NUMBER}"
# harbor镜像 url
def dockerRegistryUrl = "10.169.136.38:30002"
# harbor镜像 地址
def imageEndpoint = "other-test/test-jenkins-hook"
# 项目完整镜像地址
def image = "${dockerRegistryUrl}/${imageEndpoint}"
podTemplate(label: label, containers: [
# jenkins 专用的docker容器镜像生成pod ,默认会自动生成,这里应该是因为内网环境加了harbor
containerTemplate(name: 'jnlp', image: '10.169.136.38:30002/public/jenkins/inbound-agent:4.11-1', args: '${computer.jnlpmac} ${computer.name}'),
# nodejs环境pod
containerTemplate(name: 'node', image: '10.169.136.38:30002/public/node:17.1.0', command: 'cat', ttyEnabled: true),
# docker 容器环境,用来将镜像推harbor
containerTemplate(name: 'docker', image: '10.169.136.38:30002/public/docker:20.10.10', command: 'cat', ttyEnabled: true),
# kbs环境的镜像,用来执行kubectl命令,进行项目部署
containerTemplate(name: 'kubectl', image: '10.169.136.38:30002/public/cnych/kubectl:latest', command: 'cat', ttyEnabled: true)
]
# 配置jenkins-slave pod挂载的卷,当云环境里面配置pod模板后,挂载卷以云环境配置为准
, volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock')
]){
node(label) {
# 几个git命令
def myRepo = checkout scm
def gitCommit = myRepo.GIT_COMMIT
def gitBranch = myRepo.GIT_BRANCH
# node 编译打包,因为内网环境有问题,node编译部分去掉了
stage('代码编译打包') {
# 从jenkins 的凭据中心 获取nexus账号信息
withCredentials([string(credentialsId: "Nexus", variable: "NEXUS_AUTH_TOKEN")]){
container('node') {
sh """
echo $PATH
node -v
npm -v
"""
}
}
}
# 进行dockers传镜像传到harbor
stage('构建 Docker 镜像') {
# 从jenkins 的凭据中心 获取Harbor账号信息,并将账号信息赋给变量
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'Harbor',
usernameVariable: 'DOCKER_HUB_USER',
passwordVariable: 'DOCKER_HUB_PASSWORD']]) {
container('docker') {
sh """
# docker账号登入
docker login ${dockerRegistryUrl} -u ${DOCKER_HUB_USER} -p ${DOCKER_HUB_PASSWORD}
# 进行docker 镜像构建
docker build -t ${image}:${imageTag} ./
docker push ${image}:${imageTag}
"""
}
}
}
stage('Kubectl 部署') {
container('kubectl') {
# 从jenkins 的凭据中心 获取k8s-admin账号信息
withKubeConfig([credentialsId: "k8s-admin", serverUrl: "https://kubernetes.default"]) {
sh """
# 将yaml文件中的需要替换的变量进行替换,变成对应的参数
sed -i "s#<IMAGE>#${image}#" deploy/deployment_test.yml
sed -i "s#<IMAGE_TAG>#${imageTag}#" deploy/deployment_test.yml
# 开始构建pod
kubectl apply -f deploy/deployment_test.yml
"""
}
}
}
}
}
参考文档
jenkins官方pipeline 文档- https://www.jenkins.io/zh/doc/book/pipeline/
pipeline构建项目实践-编写podTemplate实现和k8s对接- https://blog.csdn.net/weixin_38320674/article/details/108162684
Kubernetes之标签与Pod控制器详解- https://blog.csdn.net/weixin_45186298/article/details/103975384