From 华仔

    1、

    1. #!/usr/bin/env groovy
    2. def projectProperties = [
    3. [$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '5']],
    4. parameters([
    5. string(name: 'DOCKER_USER', defaultValue: 'admin', description: 'docker用户名'),
    6. string(name: 'DOCKER_PASSWORD', defaultValue: 'Harbor12345', description: 'docker用户密码'),
    7. string(name: 'REGISTRY_URL', defaultValue: 'bqrzzl.harbor.com', description: 'docker仓库地址')
    8. ])
    9. ]
    10. properties(projectProperties)
    11. def git_address = "http://10.10.1.236/car/cls.git"
    12. def branch = "origin/k8s"
    13. def logpath = "/bqhexin/logs/zuul"
    14. def logname = "cls.gateway"
    15. def project_name = "cls"
    16. def app_name = "gateway"
    17. def port = "8182"
    18. def namespace = "sitcls"
    19. def dep_name = "${project_name}-${app_name}"
    20. def date = new Date().format("yyyMMddHHmmss")
    21. def image = "${params.REGISTRY_URL}/${project_name}/${app_name}:${date}"
    22. // 继承default模板,可自定义slave镜像等配置maven:3.6.0-jdk-8
    23. podTemplate(cloud: 'kubernetes', inheritFrom: 'default', containers: [
    24. containerTemplate(name: 'maven', image: 'maven:3.3.9', command: 'cat', ttyEnabled: true),
    25. containerTemplate(name: 'docker', image: 'docker', command: 'cat', ttyEnabled: true),
    26. containerTemplate(name: 'kubectl', image: 'lachlanevenson/k8s-kubectl:v1.14.0', command: 'cat', ttyEnabled: true)
    27. ],
    28. volumes: [
    29. hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'),
    30. hostPathVolume(hostPath: '/root/.kube', mountPath: '/root/.kube'),
    31. hostPathVolume(hostPath: '/root/.m2', mountPath: '/root/.m2')
    32. ],
    33. annotations: [
    34. podAnnotation(key: "sidecar.istio.io/inject", value: "false")
    35. ]
    36. ) {
    37. // POD_LABEL
    38. // 将会根据流水线名称和构建序号自动生成
    39. node(POD_LABEL) {
    40. container('maven') {
    41. stage('拉取代码') {
    42. checkout(
    43. [$class: 'GitSCM', branches: [[name: "${branch}"]],
    44. doGenerateSubmoduleConfigurations: false,
    45. extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'gateway']],
    46. submoduleCfg: [], userRemoteConfigs: [
    47. [credentialsId: '3f2648ab-6463-42d1-b85a-ff23a0bb3eb0',
    48. url: "${git_address}"]
    49. ]
    50. ]
    51. )
    52. }
    53. stage("修改配置文件") {
    54. sh '''
    55. sed -i 's+eureka.instance.hostname=.*+eureka.instance.hostname=eureka+g' gateway/cls-parent/cls-zuul/src/main/resources/filters/sit.properties
    56. '''
    57. }
    58. stage('mvn pacakge') {
    59. sh '''cd gateway/cls-parent
    60. chmod 757 -R /home/jenkins/agent
    61. mvn clean package -Dmaven.test.skip=true -P sit
    62. ls ./cls-zuul/target/cls-api.jar
    63. '''
    64. }
    65. }
    66. container('docker') {
    67. stage('docker-login') {
    68. //REGISTRY_URL私有仓库地址,也可使用官方地址:docker.io
    69. sh "docker login -u ${params.DOCKER_USER} -p ${params.DOCKER_PASSWORD} ${params.REGISTRY_URL}"
    70. }
    71. // stage('docker-build') {
    72. // sh "cd gateway/cls-parent/cls-zuul && cat Dockerfile && docker build -t ${image} ."
    73. // }
    74. stage('docker-push') {
    75. //sh "docker push ${image}"
    76. withDockerRegistry(credentialsId: '14ba6cb3-7571-40a9-9e91-51b0be475809', url: 'https://bqrzzl.harbor.com') {
    77. docker.build("${image}","gateway/cls-parent/cls-zuul/").push()
    78. }
    79. }
    80. stage('docker-remove') {
    81. sh "docker rmi ${image}"
    82. }
    83. }
    84. container('kubectl') {
    85. stage("修改kubernetes部署文件") {
    86. sh """
    87. cd gateway/cls-parent/cls-zuul
    88. sed -i \"s+container_port+${port}+g\" deployment.yaml
    89. sed -i \"s+namespace: namespace_name+namespace: ${namespace}+g\" deployment.yaml
    90. sed -i \"s+dep_name+${dep_name}+g\" deployment.yaml
    91. sed -i \"s+imageurl+${image}+g\" deployment.yaml
    92. sed -i \"s+logpath+${logpath}+g\" deployment.yaml
    93. sed -i \"s+logname+${logname}+g\" deployment.yaml
    94. """
    95. // sh "cd gateway/cls-parent/cls-zuul && sed -i \"s+container_port+${port}+g\" deployment.yaml"
    96. // sh "cd gateway/cls-parent/cls-zuul && sed -i \"s+namespace: namespace_name+namespace: ${namespace}+g\" deployment.yaml"
    97. // sh "cd gateway/cls-parent/cls-zuul && sed -i \"s+dep_name+${dep_name}+g\" deployment.yaml"
    98. // sh "cd gateway/cls-parent/cls-zuul && sed -i \"s+imageurl+${image}+g\" deployment.yaml"
    99. // sh "cd gateway/cls-parent/cls-zuul && sed -i \"s+logpath+${logpath}+g\" deployment.yaml"
    100. // sh "cd gateway/cls-parent/cls-zuul && sed -i \"s+logname+${logname}+g\" deployment.yaml"
    101. }
    102. stage('k8s 部署应用') {
    103. sh "kubectl --kubeconfig=/root/.kube/config apply -f ./gateway/cls-parent/cls-zuul/deployment.yaml"
    104. }
    105. }
    106. }
    107. }

    2、

    1. #!groovy
    2. pipeline {
    3. agent {
    4. docker {
    5. image 'jenkinsslave:latest'
    6. registryUrl 'http://8598567586.dkr.ecr.us-west-2.amazonaws.com'
    7. registryCredentialsId 'ecr:us-east-1:3435443545-5546566-567765-3225'
    8. args '-v /home/centos/.ivy2:/home/jenkins/.ivy2:rw -v jenkins_opt:/usr/local/bin/opt -v jenkins_apijenkins:/home/jenkins/config -v jenkins_logs:/var/logs -v jenkins_awsconfig:/home/jenkins/.aws --privileged=true -u jenkins:jenkins'
    9. }
    10. }
    11. environment {
    12. APP_NAME = 'billing-rest'
    13. BUILD_NUMBER = "${env.BUILD_NUMBER}"
    14. IMAGE_VERSION="v_${BUILD_NUMBER}"
    15. GIT_URL="git@github.yourdomain.com:mpatel/${APP_NAME}.git"
    16. GIT_CRED_ID='izleka2IGSTDK+MiYOG3b3lZU9nYxhiJOrxhlaJ1gAA='
    17. REPOURL = 'cL5nSDa+49M.dkr.ecr.us-east-1.amazonaws.com'
    18. SBT_OPTS='-Xmx1024m -Xms512m'
    19. JAVA_OPTS='-Xmx1024m -Xms512m'
    20. WS_PRODUCT_TOKEN='FJbep9fKLeJa/Cwh7IJbL0lPfdYg7q4zxvALAxWPLnc='
    21. WS_PROJECT_TOKEN='zwzxtyeBntxX4ixHD1iE2dOr4DVFHPp7D0Czn84DEF4='
    22. HIPCHAT_TOKEN = 'SpVaURsSTcWaHKulZ6L4L+sjKxhGXCkjSbcqzL42ziU='
    23. HIPCHAT_ROOM = 'NotificationRoomName'
    24. }
    25. options {
    26. buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '10', numToKeepStr: '20'))
    27. timestamps()
    28. retry(3)
    29. timeout time:10, unit:'MINUTES'
    30. }
    31. parameters {
    32. string(defaultValue: "develop", description: 'Branch Specifier', name: 'SPECIFIER')
    33. booleanParam(defaultValue: false, description: 'Deploy to QA Environment ?', name: 'DEPLOY_QA')
    34. booleanParam(defaultValue: false, description: 'Deploy to UAT Environment ?', name: 'DEPLOY_UAT')
    35. booleanParam(defaultValue: false, description: 'Deploy to PROD Environment ?', name: 'DEPLOY_PROD')
    36. }
    37. stages {
    38. stage("Initialize") {
    39. steps {
    40. script {
    41. notifyBuild('STARTED')
    42. echo "${BUILD_NUMBER} - ${env.BUILD_ID} on ${env.JENKINS_URL}"
    43. echo "Branch Specifier :: ${params.SPECIFIER}"
    44. echo "Deploy to QA? :: ${params.DEPLOY_QA}"
    45. echo "Deploy to UAT? :: ${params.DEPLOY_UAT}"
    46. echo "Deploy to PROD? :: ${params.DEPLOY_PROD}"
    47. sh 'rm -rf target/universal/*.zip'
    48. }
    49. }
    50. }
    51. stage('Checkout') {
    52. steps {
    53. git branch: "${params.SPECIFIER}", url: "${GIT_URL}"
    54. }
    55. }
    56. stage('Build') {
    57. steps {
    58. echo 'Run coverage and CLEAN UP Before please'
    59. sh '/usr/local/bin/opt/bin/sbtGitActivator; /usr/local/bin/opt/play-2.5.10/bin/activator -Dsbt.global.base=.sbt -Dsbt.ivy.home=/home/jenkins/.ivy2 -Divy.home=/home/jenkins/.ivy2 compile coverage test coverageReport coverageOff dist'
    60. }
    61. }
    62. stage('Publish Reports') {
    63. parallel {
    64. stage('Publish FindBugs Report') {
    65. steps {
    66. step([$class: 'FindBugsPublisher', canComputeNew: false, defaultEncoding: '', excludePattern: '', healthy: '', includePattern: '', pattern: 'target/scala-2.11/findbugs/report.xml', unHealthy: ''])
    67. }
    68. }
    69. stage('Publish Junit Report') {
    70. steps {
    71. junit allowEmptyResults: true, testResults: 'target/test-reports/*.xml'
    72. }
    73. }
    74. stage('Publish Junit HTML Report') {
    75. steps {
    76. publishHTML target: [
    77. allowMissing: true,
    78. alwaysLinkToLastBuild: false,
    79. keepAll: true,
    80. reportDir: 'target/reports/html',
    81. reportFiles: 'index.html',
    82. reportName: 'Test Suite HTML Report'
    83. ]
    84. }
    85. }
    86. stage('Publish Coverage HTML Report') {
    87. steps {
    88. publishHTML target: [
    89. allowMissing: true,
    90. alwaysLinkToLastBuild: false,
    91. keepAll: true,
    92. reportDir: 'target/scala-2.11/scoverage-report',
    93. reportFiles: 'index.html',
    94. reportName: 'Code Coverage'
    95. ]
    96. }
    97. }
    98. stage('Execute Whitesource Analysis') {
    99. steps {
    100. whitesource jobApiToken: '', jobCheckPolicies: 'global', jobForceUpdate: 'global', libExcludes: '', libIncludes: '', product: "${env.WS_PRODUCT_TOKEN}", productVersion: '', projectToken: "${env.WS_PROJECT_TOKEN}", requesterEmail: ''
    101. }
    102. }
    103. stage('SonarQube analysis') {
    104. steps {
    105. sh "/usr/bin/sonar-scanner"
    106. }
    107. }
    108. stage('ArchiveArtifact') {
    109. steps {
    110. archiveArtifacts '**/target/universal/*.zip'
    111. }
    112. }
    113. }
    114. }
    115. stage('Docker Tag & Push') {
    116. steps {
    117. script {
    118. branchName = getCurrentBranch()
    119. shortCommitHash = getShortCommitHash()
    120. IMAGE_VERSION = "${BUILD_NUMBER}-" + branchName + "-" + shortCommitHash
    121. sh 'eval $(aws ecr get-login --no-include-email --region us-west-2)'
    122. sh "docker-compose build"
    123. sh "docker tag ${REPOURL}/${APP_NAME}:latest ${REPOURL}/${APP_NAME}:${IMAGE_VERSION}"
    124. sh "docker push ${REPOURL}/${APP_NAME}:${IMAGE_VERSION}"
    125. sh "docker push ${REPOURL}/${APP_NAME}:latest"
    126. sh "docker rmi ${REPOURL}/${APP_NAME}:${IMAGE_VERSION} ${REPOURL}/${APP_NAME}:latest"
    127. }
    128. }
    129. }
    130. stage('Deploy') {
    131. parallel {
    132. stage('Deploy to CI') {
    133. steps {
    134. echo "Deploying to CI Environment."
    135. }
    136. }
    137. stage('Deploy to QA') {
    138. when {
    139. expression {
    140. params.DEPLOY_QA == true
    141. }
    142. }
    143. steps {
    144. echo "Deploy to QA..."
    145. }
    146. }
    147. stage('Deploy to UAT') {
    148. when {
    149. expression {
    150. params.DEPLOY_UAT == true
    151. }
    152. }
    153. steps {
    154. echo "Deploy to UAT..."
    155. }
    156. }
    157. stage('Deploy to Production') {
    158. when {
    159. expression {
    160. params.DEPLOY_PROD == true
    161. }
    162. }
    163. steps {
    164. echo "Deploy to PROD..."
    165. }
    166. }
    167. }
    168. }
    169. }
    170. post {
    171. /*
    172. * These steps will run at the end of the pipeline based on the condition.
    173. * Post conditions run in order regardless of their place in the pipeline
    174. * 1. always - always run
    175. * 2. changed - run if something changed from the last run
    176. * 3. aborted, success, unstable or failure - depending on the status
    177. */
    178. always {
    179. echo "I AM ALWAYS first"
    180. notifyBuild("${currentBuild.currentResult}")
    181. }
    182. aborted {
    183. echo "BUILD ABORTED"
    184. }
    185. success {
    186. echo "BUILD SUCCESS"
    187. echo "Keep Current Build If branch is master"
    188. // keepThisBuild()
    189. }
    190. unstable {
    191. echo "BUILD UNSTABLE"
    192. }
    193. failure {
    194. echo "BUILD FAILURE"
    195. }
    196. }
    197. }
    198. def keepThisBuild() {
    199. currentBuild.setKeepLog(true)
    200. currentBuild.setDescription("Test Description")
    201. }
    202. def getShortCommitHash() {
    203. return sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%h'").trim()
    204. }
    205. def getChangeAuthorName() {
    206. return sh(returnStdout: true, script: "git show -s --pretty=%an").trim()
    207. }
    208. def getChangeAuthorEmail() {
    209. return sh(returnStdout: true, script: "git show -s --pretty=%ae").trim()
    210. }
    211. def getChangeSet() {
    212. return sh(returnStdout: true, script: 'git diff-tree --no-commit-id --name-status -r HEAD').trim()
    213. }
    214. def getChangeLog() {
    215. return sh(returnStdout: true, script: "git log --date=short --pretty=format:'%ad %aN <%ae> %n%n%x09* %s%d%n%b'").trim()
    216. }
    217. def getCurrentBranch () {
    218. return sh (
    219. script: 'git rev-parse --abbrev-ref HEAD',
    220. returnStdout: true
    221. ).trim()
    222. }
    223. def isPRMergeBuild() {
    224. return (env.BRANCH_NAME ==~ /^PR-\d+$/)
    225. }
    226. def notifyBuild(String buildStatus = 'STARTED') {
    227. // build status of null means successful
    228. buildStatus = buildStatus ?: 'SUCCESS'
    229. def branchName = getCurrentBranch()
    230. def shortCommitHash = getShortCommitHash()
    231. def changeAuthorName = getChangeAuthorName()
    232. def changeAuthorEmail = getChangeAuthorEmail()
    233. def changeSet = getChangeSet()
    234. def changeLog = getChangeLog()
    235. // Default values
    236. def colorName = 'RED'
    237. def colorCode = '#FF0000'
    238. def subject = "${buildStatus}: '${env.JOB_NAME} [${env.BUILD_NUMBER}]'" + branchName + ", " + shortCommitHash
    239. def summary = "Started: Name:: ${env.JOB_NAME} \n " +
    240. "Build Number: ${env.BUILD_NUMBER} \n " +
    241. "Build URL: ${env.BUILD_URL} \n " +
    242. "Short Commit Hash: " + shortCommitHash + " \n " +
    243. "Branch Name: " + branchName + " \n " +
    244. "Change Author: " + changeAuthorName + " \n " +
    245. "Change Author Email: " + changeAuthorEmail + " \n " +
    246. "Change Set: " + changeSet
    247. if (buildStatus == 'STARTED') {
    248. color = 'YELLOW'
    249. colorCode = '#FFFF00'
    250. } else if (buildStatus == 'SUCCESS') {
    251. color = 'GREEN'
    252. colorCode = '#00FF00'
    253. } else {
    254. color = 'RED'
    255. colorCode = '#FF0000'
    256. }
    257. // Send notifications
    258. hipchatSend(color: color, notify: true, message: summary, token: "${env.HIPCHAT_TOKEN}",
    259. failOnError: true, room: "${env.HIPCHAT_ROOM}", sendAs: 'Jenkins', textFormat: true)
    260. if (buildStatus == 'FAILURE') {
    261. emailext attachLog: true, body: summary, compressLog: true, recipientProviders: [brokenTestsSuspects(), brokenBuildSuspects(), culprits()], replyTo: 'noreply@yourdomain.com', subject: subject, to: 'mpatel@yourdomain.com'
    262. }
    263. }