jenkins docker pipeline 腳本

pipeline {
    agent any
    
    parameters {
        gitParameter(name: 'BRANCH', type: 'PT_BRANCH', defaultValue: 'master', description: '選擇 Git 分支')
        choice(name: 'ENV', choices: ['dev', 'staging', 'prod'], description: '選擇部署環境')
    }
    
    environment {
     //需要到系統憑證中配置git憑證 git_auth
= "jenkins-pipeline" git_timeout = "120" git_url = "[email protected]:xxxxxxxx/xxxxxxxx.git" docker_url = "docker-hub.xxxxxx.com" docker_space = "xxxx" project_name = "xx-xx" docker_tag = "latest" } stages { stage('環境檢測') { steps { script{ } sh label: '', script: ''' mvn -v git version java -version docker -v ''' } } stage('代碼獲取') { steps { checkout([ $class: 'GitSCM', branches: [[name: "${params.BRANCH}"]], extensions: [[ $class: 'CloneOption', noTags: false, reference: '', shallow: false, timeout: "${git_timeout}" ]], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_url}"]] ]) } } stage('項目構建') { steps { script { sh """ mvn clean package -Dmaven.test.skip=true """ } } } stage('構建鏡像') { steps { script { // 使用 Dockerfile 構建鏡像 sh """ docker build -t ${docker_url}/${docker_space}/${project_name}:${docker_tag} . """ } } } stage('鏡像上傳') { steps { script { // 登錄到 Docker Hub // sh "echo '${DOCKER_HUB_PASSWORD}' | docker login -u '${DOCKER_HUB_USERNAME}' --password-stdin" // 推送鏡像 sh """ docker push ${docker_url}/${docker_space}/${project_name}:${docker_tag} docker rmi ${docker_url}/${docker_space}/${project_name}:${docker_tag} """ } } } stage('發佈') { steps { script { // 根據選擇的部署環境設置相應的環境變量 if (params.DEPLOY_ENV == 'dev') { // 設置開發環境的環境變量 } else if (params.DEPLOY_ENV == 'staging') { // 設置預發佈環境的環境變量 } else if (params.DEPLOY_ENV == 'production') { // 設置生產環境的環境變量 } // 目標服務器的 IP 列表 def target_servers = ['192.168.0.123'] // 使用循環遍歷目標服務器列表 for (target_server_ip in target_servers) { echo "Deploying to server: ${target_server_ip}" // 在目標服務器上部署 Docker 容器(替換爲目標服務器的用戶名) // 確保目標服務器已經安裝了 Docker,並且 Jenkins 有權限 SSH 訪問目標服務器 sh """ ssh -o StrictHostKeyChecking=no root@${target_server_ip} ' set -x && docker pull ${docker_url}/${docker_space}/${project_name}:${docker_tag} && if docker ps -a | grep -w "${project_name}" >/dev/null; then docker stop ${project_name} && docker rm ${project_name} && docker rmi ${docker_url}/${docker_space}/${project_name}:${docker_tag} fi && docker run --init -d -m 512M -v /data:/data -e JVM_XMX=256M -e JVM_XMS=256M --net=host --name ${project_name} -d --restart always ${docker_url}/${docker_space}/${project_name}:${docker_tag} ' """ } } } } stage('清空工作目錄') { steps { deleteDir() } } } post { always { sh label:'', script:""" """ } } }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章