Jenkins脚本式pipeline笔记

Jenkins集成需关注的难点

  1. 公司代码技术栈的种类
  2. 所使用的技术框架种类
  3. 业务开发项目组员代码风格

1- 硬杀job任务

POST http://jenkins-url/job/job-name/job-nubmer/kill

2- Jenkins构建页面获取git分支或tag

import jenkins.model.*
//jenkins凭证名字
credentialsId = 'xxxxx'

try {
    def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class, Jenkins.instance, null, null ).find {
            it.id == credentialsId
    }

    def user = creds.username.replaceAll('@', '%40')
    def pass = creds.password.toString().replaceAll('@', '%40')

    def cmd = "git ls-remote -h -t https://${user}:${pass}@xxx.gitlab.com/ce/repo-code-for-app.git"
    def proc = cmd.execute()
    proc.waitFor()
    
    def branchs = proc.in.text.readLines().collect {
        it.replaceAll("[0-9a-z]*\trefs/[a-z]*/", '')
    }
    return branchs.findAll{
         it[-3..-1] != '^{}'
    }.sort{ a,b-> 
         return -a.compareTo(b) 
    } 
} catch (Exception e) {
    return ["Exception"]
}

3- Jenkins读取job列表

import jenkins.model.Jenkins
import hudson.model.Job

Jenkins.instance.allItems(Job).findAll{
  it ->it.fullName.startsWith('mydefined-prefix-') && it.fullName.split('-').size()>3
}.collect{
	job -> job.fullName
}

4- 下载Job所有配置

        4.1 安装工具jq

                sudo apt-get install jq

        4.2 脚本执行

#!/bin/bash
authKey='[uername]:[password]'
JENKINS_URL='http--x---'
vm_jenkins_list=`curl -u $authKey -X GET $JENKINS_URL/view/all/api/json?tree=jobs[name] | jq -r .jobs[].name`
echo $vm_jenkins_list>fetch_vm/all.name.list.txt
for jobname in $vm_jenkins_list;
do
   echo $jobname
   curl -X GET -u $authKey $JENKINS_URL/job/$jobname/config.xml -o fetch_vm/$jobname-config.xml
done

5- npm构建报错

    5.1  Jenkins容器jnlp的.ssh/config导致问题,配置:

## .ssh/config
StrictHostKeyChecking no
UserKnownHostsFile /dev/null

报错

npm ERR! Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR! 
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR! 
npm ERR! exited with error code: 128

解决方法:

nodejs(configId: 'npmrc-config', nodeJSInstallationName: nodejsVer) {
    sh '''
        export StrictHostKeyChecking=ask
        npm install
    '''
}

   

5.2   git协议问题

npm ERR! /usr/bin/git ls-remote -h -t git://github.com/adobe-webplatform/eve.git
npm ERR! 
npm ERR! fatal: remote error: 
npm ERR!   The unauthenticated git protocol on port 9418 is no longer supported.

解决方法:

nodejs(configId: 'npmrc-config', nodeJSInstallationName: nodejsVer) {
    sh '''
        git config --global url."https://".insteadOf git://
        npm install
    '''
}

6- 依赖包上传

def api_list = !env.API_LIST?['api']:env.API_LIST.split(',')
api_list.each{ api_dir ->
    dir(api_dir) {
		if(!fileExists('pom.xml')){
			echo '不是子包'
			return ;
		}
		/****
			先校验后上传
		****/
		
		def apipominfo=readProperties defaults: [:], file: 'target/maven-archiver/pom.properties', text: 'other=Override'
		
		sh """
			rm  out.json||true
			curl -X GET 'https://x.xxx.com/nexus/service/rest/v1/search?group=${apipominfo.groupId}&name=${apipominfo.artifactId}&version=${apipominfo.version}' -o out.json
		"""
		def nexusrepo = readJSON(file: 'out.json');
		if(nexusrepo.items.size() == 0){
			configFileProvider(
				[configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
				sh "'${mvnHome}/bin/mvn' deploy -fn -e -s $MAVEN_SETTINGS "
			}
		}else{
			echo "已存在:${apipominfo.groupId}:${apipominfo.artifactId}:${apipominfo.version}"
		}
   		
	}
}

7- 指定maven配置文件构建

//在系统管理-config中,配置maven-settings
//使用方式如下
configFileProvider(
					[configFile(fileId: 'maven-settings', variable: 'MAVEN_SETTINGS')]) {
					sh "'${mvnHome}/bin/mvn' clean package -s $MAVEN_SETTINGS "
				}

8- 指定目录读取最大jar包名字

dir('target'){
    finalName=sh(label: 'finalName', returnStdout: true, script: /ls -1s *.jar|sort -n|tail -1/).toString().split(/\s+/)[-1]
}

9- 获取仓库指定目录内容

def ret=checkout([$class: 'GitSCM', 
                    branches: [[name: '*/master']], 
                    doGenerateSubmoduleConfigurations: false, 
                    extensions: [[$class: 'SparseCheckoutPaths', sparseCheckoutPaths: [[path: 'main/src']]]], 
                    submoduleCfg: [], 
                    userRemoteConfigs: [[credentialsId: 'repo-auth', url: 'https://xxx.git']]])

currentBuild.description="COMMIT_ID:${ret.GIT_COMMIT[0..9]}"//取前10位显示

10- 添加环境变量(以sonar为例)

//先在全局工具配置sonar安装方式

def SCANNER_HOME=tool 'sonar-scanner'

withEnv(["SCANNER_HOME=$SCANNER_HOME","PATH+EXTRA=$SCANNER_HOME/bin"]){
    withCredentials([string(credentialsId: 'x-x-x-xx-xx', variable: 'sonar_token')]) {
        sh "sonar-scanner -Dsonar.projectKey=xxxx -Dsonar.sources='src' -Dsonar.projectVersion='xxxx' -Dsonar.projectDescription='xxxx' -Dsonar.projectName=xxxx -Dsonar.host.url=http://xxxx/sonar -Dsonar.login=sonar_token"
    }
}

11-校验用户

    stage('权限检查') {
        wrap([$class: 'BuildUser']) {
            def activeUserEmail = [
                'lxxxxg@cn.com',
            ]

            if ((env.BUILD_USER_EMAIL in activeUserEmail) && (env.Environment != 'sit')) {
                throw new RuntimeException("${env.BUILD_USER} 没有权限构建 ${env.Environment} 项目")
            }
        }
    }

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值