当前位置:网站首页>Jenkins+webhooks- multi branch parametric construction-

Jenkins+webhooks- multi branch parametric construction-

2022-07-01 13:06:00 An operation and maintenance young man

Jenkins+webhooks- Multi branch parametric construction -

demand :
 I'm here because the company has a static resource , The completion of the construction needs to be placed in nginx Published catalog , But it's not very convenient to build manually every time , What I have here is webhook Updating code triggers automatic build , But our environment is divided into formal environment and test environment , You need to build and publish to different environments and servers 

 My solution :
 Scheme 1 :
 The first way is to create two pipeline, Trigger for different branches webhook, It is not recommended to use too much memory 
 Option two :
 If there are two branches , Development - test 
 hold jenkinsfile Write complete , Put it in the development branch ,jenkins-webhook Recognize that the development branch has been updated , Then pull the development branch code , Recognize the inside jenkinsfile, Will build and release as required 
Senior boss document
https://xie.infoq.cn/article/600f642fcb26f0c280a7acf59
https://www.cnblogs.com/testopsfeng/p/15139538.html
https://blog.csdn.net/weixin_39637661/article/details/110087309?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-110087309-blog-106900128.pc_relevant_antiscanv3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-110087309-blog-106900128.pc_relevant_antiscanv3&utm_relevant_index=14
https://blog.csdn.net/shm19990131/article/details/107529357
https://gitbook.curiouser.top/origin/jenkins-generic-webhook-trigger%E6%8F%92%E4%BB%B6.html

Adopt the second scheme

pipeline adopt Custom parameters (This project is parameterized - String Parame), To build the deployment .

( notes : Parametric construction - String parameters )

One 、 Implementation content

Gitlab -- perhaps gitea The main branch 、 From branch After the code is modified , adopt webhook Trigger jenkins.

jenkins Can pass Branch variables To build the deployment .

Two 、 Implementation steps

1、 stay pipeline Pipeline project starts parameterized construction

image-20220623112529293

Here I define two

image-20220623112815855

2、 modify pipeline Of Jenkinsfile file , Specify variables to pull code

Be careful : What is used here is Jenkinsfile - pipeline, Each branch needs such a file

image-20220623113345810

pipeline grammar
pipeline {
     
   agent any 
   stages {
     
      stage(' Pull the code ') {
     
          steps {
     
              checkout([$class: 'GitSCM', branches: [[name: '${branch}']], extensions: [], userRemoteConfigs: [[credentialsId: '7f49313d-880d-4a5e-836f-cef4bf2ec37a', url: 'http://192.168.2.204:3000/aike/test.git']]])
            } 
        }
      stage(' choice node Version compilation and packaging ') {
     
             steps {
     
              nodejs('node') {
    
                sh '''cd ${single_project_name}
                      npm  install 
                      npm run build
                      tar -zcvf  ./front.end-levee.tar.gz   ./dist'''
              }
            } 
        } 
      stage(' Publish to server ') {
     
             steps {
     
              sshPublisher(publishers: [sshPublisherDesc(configName: '192.168.2.204', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''
            cd /a
            tar -xzf front.end-levee.tar.gz -C ./
            cp -r dist/* ./ 
            rm -rf   front.end-levee.tar.gz''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/a', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'front.end-levee.tar.gz')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
            } 
        }             
   }
}
Code warehouse

image-20220623133209481

Put this code , Upload to each branch

image-20220623132928596

Look at the code

image-20220623133435755

①、 To configure webhook, Notice that there are several branches , Just drive a few webhook

The main branch webhook:

image-20220623134435741

To configure jenkins - Pipeline Build tasks

Build trigger

image-20220623134808026

The problem summary
 The above build , Basically, trigger automatic construction has been realized , But the only drawback is that each build pulls by default master Branch code 

Full version

stay Jenkinsfile in , Add the configuration : Detailed explanation of variables

triggers {
    
    GenericTrigger (
            //  Title during construction 
            causeString: 'Triggered by $ref',
            //  obtain POST Variables in parameters ,key Refers to the variable name , adopt $ref To access the corresponding value ,value refer to JSON Match the value ( Reference resources Jmeter Of JSON Extractor )
            // ref Refers to the push Branch , The format is as follows :refs/heads/master
            genericVariables: [[key: 'ref', value: '$.ref']],
            //  Print the obtained variable key-value, Here will be printed as :ref=refs/heads/master
            printContributedVariables: true,
            //  Print POST Parameters passed 
            printPostContent: true,
            // regexpFilterExpression And regexpFilterExpression Use in pairs 
            //  When the two are equal , It will trigger the construction of the corresponding branch 
            regexpFilterExpression: '^refs/heads/(master|production)$',
            regexpFilterText: '$ref',
            //  And webhook Configured in token Consistent parameter values 
            token: 'mytoken'
    )
}

Sort out your ideas

 This multi pipeline construction , Manage a lot pipeline Assembly line , There are only a few pipelines to manage 
 But you have to Jenkinsfile Put the file in your code , To recognize ,J It's capital 

image-20220624142303375

Identified
image-20220624142333562

Code repository configuration

image-20220624142459807

Pipeline configuration

 Here is the pipeline created 
Defining variables

image-20220624142641700

Post content parameters Middle configuration

For example, here we want to get ref The value of can be configured in this way

#  Custom variable name 
Variable: ref
 
#  The expression uses  JSONPath  The way 
Expression: $.ref      # ref  value 
 
#  Expression get value filter and match , for example  refs/tags/Test_cet_v1.0.0 ,  When the configuration is as follows ref Its value is  Test_cet_v1.0.0 
Value filter: refs/tags/ 
 
#  Does not match the default value 
Default value:master

image-20220624142746689

To configure token

image-20220624142956909

Cause To configure
Triggered by  $ref

image-20220624163221227

Ignore some branches

It can be done by Filter by name (with wildcards) Realization :

image-20220624143138314

To configure Optional filter
^refs/heads/(master|release)$

image-20220624143251785

complete jenkinsfile You can refer to
pipeline {
     
   agent any 
      triggers {
    
    GenericTrigger (
            //  Title during construction 
            causeString: 'Triggered by $ref',
            //  obtain POST Variables in parameters ,key Refers to the variable name , adopt $ref To access the corresponding value ,value refer to JSON Match the value ( Reference resources Jmeter Of JSON Extractor )
            // ref Refers to the push Branch , The format is as follows :refs/heads/master
            genericVariables: [[key: 'ref', value: '$.ref']],
            //  Print the obtained variable key-value, Here will be printed as :ref=refs/heads/master
            printContributedVariables: true,
            //  Print POST Parameters passed 
            printPostContent: true,
            // regexpFilterExpression And regexpFilterExpression Use in pairs 
            //  When the two are equal , It will trigger the construction of the corresponding branch 
            regexpFilterExpression: '^refs/heads/(master|release)$',
            regexpFilterText: '$ref',
            //  And webhook Configured in token Consistent parameter values 
            token: 'aikeya'
    )
}
   stages {
     
    	stage(" Test the deployed ") {
    
            when {
    
                branch 'release'
            }
    	    steps {
    
                echo 'release branch'
    	    }
    	}
    	stage(" Production deployment ") {
    
            when {
    
                branch 'master'
            }
    	    steps {
    
                echo 'master branch'
    	    }
    	}
        stage(' choice node Version compilation and packaging ') {
     
             steps {
     
              nodejs('node') {
    
                sh '''cd ${single_project_name}
                      npm  install 
                      npm run build
                      tar -zcvf  ./front.end-levee.tar.gz   ./dist'''
              }
            } 
        } 
        stage(' Publish to server ') {
     
             steps {
     
              sshPublisher(publishers: [sshPublisherDesc(configName: '192.168.2.204', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''
            cd /b
            tar -xzf front.end-levee.tar.gz -C ./
            cp -r dist/* ./ 
            rm -rf   front.end-levee.tar.gz''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/a', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'front.end-levee.tar.gz')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
            } 
        }             
   }
}

efaultExcludes: false, patternSeparator: ‘[, ]+’, remoteDirectory: ‘/a’, remoteDirectorySDF: false, removePrefix: ‘’, sourceFiles: ‘front.end-levee.tar.gz’)], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
}
}
}
}




######  Configuration complete   Test it 
原网站

版权声明
本文为[An operation and maintenance young man]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011244369048.html