4

脚本式流水线

 2 years ago
source link: https://linuxsuren.github.io/blog/devops/jenkins/pipeline/scripted/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
codes/jenkinsfile/script-trigger.groovy
node('local') {
	echo 'hello'
}

properties([
	buildDiscarder(
		logRotator(
			artifactDaysToKeepStr: '',
			artifactNumToKeepStr: '',
			daysToKeepStr: '5',
			numToKeepStr: '10'
		)
	),
	pipelineTriggers([
		cron('H 3,12,17 * * *'),
		scm('H 3,12,17 * * *')
	])
])
原文件

参数化执行

properties([[$class: 'JobRestrictionProperty'],
	parameters([run(description: '',
		filter: 'ALL', 
		name: 'Name', 
		projectName: 'Project')]),
	pipelineTriggers([])]
)

你可以利用处理异常的方式来实现类似于申明式流水线中post

codes/jenkinsfile/try-catch.groovy
node {
    stage("one"){
        try {
            echo "hello"
        }catch(error){
            echo error.getMessage()
        }finally{
            echo "finally"
        }
    }
}
原文件
codes/jenkinsfile/loop.groovy
node('suren') {
    def dev_path = '/opt/suren/bin'
    def services = [
        [
            'name': 'admin',
            'project': 'admin',
            'port': '7002',
            'jarName': 'admin'
        ]
    ];
    
    stage('Copy Artifact') {
        for(service in services){
            step([$class: 'CopyArtifact', fingerprintArtifacts: true, flatten: true,
                projectName: service.project,
                selector: [$class: 'StatusBuildSelector', stable: false],
                target: dev_path + '/' + service.name
            ])
        }
    }
    
    stage('Stop Service') {
        for(service in services){
           sh 'fuser -n tcp -k ' + service.port + ' > redirection &'
        }
    }
    
    stage('Start Service') {
        for(service in services){
            sh 'cd ' + pass_bin + '/' + service.name + ' && nohup nice java -server -Xms128m -Xmx384m \
                -jar ' + service.jarName + '.jar \
                --server.port=' + service.port + ' $> initServer.log 2>&1 &'
        }
    }
}
原文件

我们有时候需要在流水线中发送 HTTP 请求,下面给出一个例子:

codes/jenkinsfile/http.groovy
// dependecy plugin is https://plugins.jenkins.io/phoenix-autotest
pipeline {
    agent {
        label "master"
    }
    
    stages {
      stage('test') {
          steps{
              script {
                  http url: "http://baidu.com"
                  http url: "http://baidu.com", responseBody: "body.txt"
                  
                  archiveArtifacts "body.txt"
                  
                  def quy = 'https://www.baidu.com/s?wd=' + URLEncoder.encode('a b', 'UTF-8')
                  echo quy
                  http url: quy
              }
          }
      }
    }
}
原文件

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK