#!/usr/bin/env groovy pipeline { agent any options { timestamps() } parameters { choice( name: 'profile', choices: ['prod', 'test'], description: '选择部署环境' ) } environment { ARTIFACTID = "storleadwebsite" DOCKER_REGISTRY = "reg-aliyun" DOCKER_HOST = "registry.cn-shenzhen.aliyuncs.com" DOCKER_LOGIN_REGISTRY = "https://${DOCKER_HOST}" BUILD_PREFIX = "storlead-huawei" DOCKER_IMG_NAME = "${DOCKER_HOST}/${BUILD_PREFIX}/${ARTIFACTID}" SWARM_INIT_REPLICAS_NUM = 1 SERVER_HOST_NAME = "test1" API_PORT = 3001 } stages { stage('处理环境') { steps { script { if (params.profile == "test") { SERVER_HOST = "test1.storlead.com" SERVER_PORT = 53023 SERVER_HOST_NAME = "test1" } if (params.profile == "prod") { SERVER_HOST = "110.41.82.21" SERVER_PORT = 22 SERVER_HOST_NAME = "node2" } echo "部署服务器: ${SERVER_HOST}" } } } stage('部署服务') { steps { withCredentials([ usernamePassword(credentialsId: 'storleadHW', usernameVariable: 'usernameHW', passwordVariable: 'passwordHW'), usernamePassword(credentialsId: 'storlead', usernameVariable: 'username', passwordVariable: 'password'), usernamePassword(credentialsId: 'reg-aliyun', usernameVariable: 'aliUsername', passwordVariable: 'aliPassword') ]) { script { def remote = [:] remote.name = "${SERVER_HOST}" remote.host = "${SERVER_HOST}" remote.port = SERVER_PORT remote.allowAnyHosts = true if (params.profile == "prod") { remote.user = usernameHW remote.password = passwordHW } else { remote.user = username remote.password = password } echo "登录阿里云镜像仓库" sshCommand remote: remote, command: """ docker login -u ${aliUsername} -p ${aliPassword} ${DOCKER_LOGIN_REGISTRY} """ echo "删除镜像" sshCommand remote: remote, command: """ docker rmi ${DOCKER_IMG_NAME}:latest || true """ echo "拉取镜像" sshCommand remote: remote, command: """ docker pull ${DOCKER_IMG_NAME}:latest """ sh """ echo ' version: "3.7" services: ${ARTIFACTID}-${params.profile}: image: ${DOCKER_IMG_NAME}:latest restart: always deploy: replicas: ${SWARM_INIT_REPLICAS_NUM} placement: constraints: - 'node.hostname == ${SERVER_HOST_NAME}' restart_policy: condition: on-failure environment: - "TZ=Asia/Shanghai" env_file: - /docker/sp/storleadwebsite.env ports: - "${API_PORT}:3000" networks: - ${ARTIFACTID} networks: ${ARTIFACTID}: driver: overlay attachable: true ' > stack.yml """ sshPut remote: remote, from: "stack.yml", into: "/docker/sp/${ARTIFACTID}-stack.yml" echo "部署 docker swarm" sshCommand remote: remote, command: """ docker stack deploy \ --resolve-image=always \ --with-registry-auth \ -c /docker/sp/${ARTIFACTID}-stack.yml \ ${ARTIFACTID}-${params.profile} """ } } } } } }