pipeline { environment { DOCKER_REPOSITORY_CREDENTIAL_ID = "7cc63152-c727-40fc-b177-d8397396f1ba" HARBOR_HOST = "registry.cn-hangzhou.aliyuncs.com" NAMESPACE_NAME = "newrain_wang" REPOSITORY_NAME = "my-web-app" TAG = "v1.0" REPLICAS = 4 YAML_PATH = "k8s" } agent { kubernetes { cloud "kubernetes" yaml """ apiVersion: v1 kind: Pod spec: containers: - name: jnlp image: jenkins/inbound-agent:3107.v665000b_51092-15 args: ['\$(JENKINS_SECRET)', '\$(JENKINS_NAME)'] imagePullPolicy: IfNotPresent volumeMounts: - mountPath: "/etc/localtime" name: "volume-2" readOnly: false - name: kubectl image: bitnami/kubectl:1.22.0 imagePullPolicy: IfNotPresent tty: true command: ["cat"] volumeMounts: - mountPath: "/etc/localtime" name: "volume-2" readOnly: false - mountPath: "/var/run/docker.sock" name: "volume-docker" readOnly: false - mountPath: "/.kube/config" subPath: config name: "kubeconfig" readOnly: false - name: docker image: docker:19.03.15-git command: ['cat'] tty: true volumeMounts: - mountPath: "/var/run/docker.sock" name: "volume-docker" readOnly: false volumes: - name: volume-2 hostPath: path: "/usr/share/zoneinfo/Asia/Shanghai" - name: volume-docker hostPath: path: "/var/run/docker.sock" - name: kubeconfig secret: secretName: kubeconfig items: - key: config path: config """ } } stages { stage('构建镜像') { steps { withCredentials([usernamePassword(credentialsId: env.DOCKER_REPOSITORY_CREDENTIAL_ID, passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME')]) { container('docker') { sh """ docker build -t ${env.HARBOR_HOST}/${env.NAMESPACE_NAME}/${env.REPOSITORY_NAME}:${env.TAG} . docker login ${env.HARBOR_HOST} --username ${env.USERNAME} --password ${env.PASSWORD} docker push ${env.HARBOR_HOST}/${env.NAMESPACE_NAME}/${env.REPOSITORY_NAME}:${env.TAG} """ } } } } stage('部署到kubernetes') { steps { container('kubectl') { sh """ sed -i "s/REPLICAS/${env.REPLICAS}/;s/HARBOR_HOST/${env.HARBOR_HOST}/;s/NAMESPACE_NAME/${env.NAMESPACE_NAME}/;s/REPOSITORY_NAME/${env.REPOSITORY_NAME}/;s/TAG/${env.TAG}/" ${env.YAML_PATH} kubectl apply -f ${env.YAML_PATH} """ } } } } }