ci: k8s部署

This commit is contained in:
zhangjialin
2022-03-09 17:36:11 +08:00
parent 186c234c62
commit d7a776d626
4 changed files with 227 additions and 0 deletions

111
devops/K8sJenkinsFile Normal file
View File

@@ -0,0 +1,111 @@
pipeline { // 直接上k8s用k8s来管理docker
agent {
node {
label "nodejs"
}
}
parameters {
choice(
description: "你需要选择哪条分支进行构建?",
name: "branch_name",
choices: ["master", "develop_youlai_k8s_deploy"]
)
}
environment {
// 自建harbor仓库的namespace
docker_hub_namespace = "youlai"
// docker_hub_namespace = "youlaiwuhui"
web_app_name = "youlai-web-vue3"
// 自建镜像仓库地址
docker_hub = "k8s-harbor:30002"
// docker_hub = "https://registry.cn-hangzhou.aliyuncs.com"
// 在jenknis或kubesphere上面的凭证
docker_hub_id = "youlai-zhangjialin-myself-harbor-account"
// docker_hub_id = "zhangjialin-aliyun-pingzheng"
// k8s 上面的 namespace
k8s_namespace = "youlai-mall"
GIT_COMMIT_ID = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
// BUILD_NUMBER 这个变量从jenkins传递过来
current_build_number = "${BUILD_NUMBER}"
// 在k8s上面配置的id
KUBECONFIG_CREDENTIAL_ID = "youlai-kubeconfig"
}
stages {
stage ("打印相关变量") {
steps{
echo "docker_hub_namespace信息为: ${docker_hub_namespace}"
// 获取commit信息用于后面打tag
echo "commit信息为${env.GIT_COMMIT_ID}"
echo "current_build_number信息为${env.current_build_number}"
script {
// 本端tag名
env.local_tag = "frontend:${current_build_number}_${GIT_COMMIT_ID}"
// 远端tag名必须以这种方式命令才能push到远端
env.remote_tag = "${docker_hub}/${docker_hub_namespace}/${local_tag}"
echo "local_tag信息为${env.local_tag}"
echo "remote_tag信息为${env.remote_tag}"
}
}
}
stage("checkout代码") {
steps {
//git branch: "${branch_name}", credentialsId: 'zhangjialin-youlai-mall-pingzheng', url: 'https://gitee.com/youlaitech/youlai-mall.git'
//checkout([
//$class: 'GitSCM',
//branches: [[name: "${branch_name}"]],
//extensions: [[$class: 'CloneOption', depth: 1, noTags: false, reference: '', shallow: true]],
//userRemoteConfigs: [[credentialsId: 'zhangjialin-youlai-mall-pingzheng', url: 'https://gitee.com/youlaitech/youlai-mall.git']]])
sh "du -h --max-depth=1"
}
}
stage('构建') {
agent none
steps {
container('nodejs') {
script {
sh 'yarn config set registry https://registry.npm.taobao.org'
sh 'npm config set registry https://registry.npm.taobao.org'
sh 'ls -al $WORKSPACE/src/components/TreeSelect'
sh 'yarn install --force'
sh 'yarn build:prod'
}
}
}
}
stage('构建镜像') {
agent none
steps {
script {
container('nodejs') {
sh "pwd && ls -al"
sh "docker build -t ${env.local_tag} -f devops/Dockerfile ."
withCredentials([usernamePassword(credentialsId: "${docker_hub_id}",
passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {
sh 'echo "$DOCKER_PASSWORD" | docker login http://k8s-harbor:30002 -u "$DOCKER_USERNAME" --password-stdin'
sh "docker tag ${env.local_tag} ${env.remote_tag}"
sh "docker push ${env.remote_tag}"
}
}
}
}
}
stage("自动部署至k8s") {
agent none
steps {
container ("nodejs") {
// 这种方式启k8s是官方推荐的
sh 'envsubst < devops/deploy.yaml | kubectl apply -f -'
}
}
}
}
}