pcm-openstack/pcm-openstack.Jenkinsfile

70 lines
3.1 KiB
Plaintext

def JOB_NAME = "${env.JOB_NAME}"
def BUILD_NUMBER = "${env.BUILD_NUMBER}"
def label = "jenkins-${JOB_NAME}-${BUILD_NUMBER}-${UUID.randomUUID().toString()}"
def code_path = "./"
def project_name = "pcm-openstack"
podTemplate(label: label, containers: [
containerTemplate(name: 'golang', image: 'golang:1.20.2-alpine3.17', command: 'cat', ttyEnabled: true),
containerTemplate(name: 'docker', image: 'docker:latest', command: 'cat', ttyEnabled: true),
containerTemplate(name: 'kubectl', image: 'jcce/kubectl:1.23.7', command: 'cat', ttyEnabled: true)
], serviceAccount: 'jenkins', volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock')
]) {
node(label) {
def imageEndpoint = "jcce/${project_name}"
stage('拉取代码') {
checkout scmGit(branches: [[name: "*/${branches}"]], extensions: [], userRemoteConfigs: [[credentialsId: 'gitlink-zj', url: 'https://gitlink.org.cn/JointCloud/pcm-openstack.git']])
echo "获取commit_id 作为镜像标签"
script {
env.imageTag = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
env.image = "${registryUrl}/${imageEndpoint}:${imageTag}"
env.imageLatest = "${registryUrl}/${imageEndpoint}:latest"
}
}
stage('构建 Docker 镜像') {
withCredentials([[
$class: 'UsernamePasswordMultiBinding',
credentialsId: 'docker-auth',
usernameVariable: 'DOCKER_USER',
passwordVariable: 'DOCKER_PASSWORD'
]]) {
container('docker') {
echo "构建 Docker 镜像阶段"
sh """
docker login ${registryUrl} -u ${DOCKER_USER} -p ${DOCKER_PASSWORD}
docker build -t ${image} -t ${imageLatest} -f ${code_path}/Dockerfile .
docker push ${image}
docker push ${imageLatest}
docker rmi -f ${image} ${imageLatest}
"""
}
}
}
stage('运行 Kubectl 部署到k8s平台') {
withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
container('kubectl') {
echo "部署应用"
sh """
mkdir -p ~/.kube && cp ${KUBECONFIG} ~/.kube/config
cd ${code_path}
sed -i 's#image_name#${image}#' ${project_name}.yaml
sed -i 's#secret_name#${secret_name}#' ${project_name}.yaml
sed -i 's#nacos_host#${nacos_host}#' ${project_name}.yaml
cat ${project_name}.yaml
kubectl apply -f ${project_name}.yaml
"""
}
}
}
stage('清理镜像') {
container('docker') {
sh """
docker rmi -f ${image} ${imageLatest}
"""
// cleanWs notFailBuild: true
}
}
}
}