In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
In this issue, the editor will bring you about how to trigger Pipeline execution in Jenkins 2.x. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
1. Time trigger
Time trigger refers to defining a time that triggers pipeline execution when the time is up. Use the trigger instruction in Jenkins pipeline to define a time trigger.
Trigger instructions can only be defined under the pipeline block, and Jenkins supports cron and pollSCM,upstream built-in. Other ways can be achieved through plug-ins.
1.1 timed execution: cron
Timed execution is like cronjob, which is executed as soon as the time is reached. Its usage scenario is usually to perform periodic job, such as nightly builds.
Pipeline {agent any triggers {cron ('00 *')} stages {stage ('Nightly build') {steps {echo "this is a time-consuming build that executes"}} every morning.
The Jenkins trigger cron syntax uses the UNIX cron syntax (with some subtle differences). A cron contains five fields, separated by spaces or Tab, in the format: MINUTE HOUR DOM MONTH DOW. The meaning of each field is:
MINUTE: minutes within an hour, with a value range of 0 ∼ 59.
HOUR: hours within a day, with a value range of 0 ∼ 23.
DOM: one day in a month, with a value range of 1 ∼ 31.
MONTH: month, with a value range of 1 ∼ 12.
DOW: day of the week. The value range is 0 ∼ 7. 0 and 7 represent Sunday.
You can also specify multiple values at once using the following special characters.
*: match all values
Mmurn: matches the value between M and N.
M-N/X or*/X: specifies that the step is in the range of M to N, with an X value.
Amemery B, Z: enumerates multiple values using commas.
In some large organizations, there are a large number of scheduled tasks executed at the same time, such as N tasks performed at midnight (00 *). This will result in a load imbalance. Use the "H" character in Jenkins trigger cron syntax to solve this problem, where H stands for hash. For tasks that don't have to be accurate to 00:00, cron can write: h 0 *, which stands for 00:00 to, and H for hash. Represents execution at any point in time between 00:00 and 00:59.
It is important to note that H applications are inaccurate in the DOM (day of the month) field because there are 31 days in October and 28 days in February.
Jenkins trigger cron has also designed some human aliases: @ yearly, @ annually, @ monthly, @ weekly, @ daily, @ midnight, and @ hourly. For example, @ hourly is the same as H * and represents any time in an hour; @ midnight actually represents some time between 12:00 and 2:59 in the morning. There are few application scenarios for other aliases.
1.2 polling code repository: pollSCM
Polling the code repository refers to going to the code repository regularly to ask if the code has changed, and execute it if there is any change.
Pipeline {agent any triggers {/ / every minute to determine whether the code has changed pollSCM ("Hmax 1 *")}}
In fact, if the code changes, the best way is for the code repository to actively notify Jenkins, rather than Jenkins going to the code repository frequently to check. So what is the meaning of this way of existence?
In some special cases, such as the code repository of the extranet cannot call the Jenkins of the intranet, or vice versa, it will be used in this way.
two。 Event trigger
Event triggering means that pipeline execution is triggered when an event occurs. This event can be anything you can think of. For example, manual trigger on the interface, other Job active trigger, HTTP API Webhook trigger and so on.
2.1 triggered by upstream tasks: upstream
When the execution of B task depends on the execution result of A task, An is called the upstream task of B. In Jenkins 2.22 and above, the trigger directive began to support trigger conditions of type upstream. The role of upstream is to let B pipeline decide which upstream tasks to rely on.
/ / job1 and job2 are both task names triggers {upstream (upstreamProjects: "job1,job2", threshold: hudson.model.Result.SUCCESS)}
Use, separate when the upstreamProjects parameter receives multiple tasks. The threshold parameter is triggered when the result of the execution of the upstream task is triggered. Hudson.model.Result is an enumeration that includes the following values:
ABORTED: the task was aborted manually.
FAILURE: build failed.
SUCCESS: built successfully.
UNSTABLE: there are some errors, but the build will not fail.
NOT_BUILT: in a multi-phase build, problems in the previous phase prevent the later phase from being executed.
Note: you need to manually trigger a task for Jenkins to load pipeline before the trigger instruction takes effect.
2.2 GitLab notification trigger
GitLab notification triggering means that when GitLab discovers a change in the source code, it triggers Jenkins to execute the build.
The benefits of being actively notified to build by GitLab are obvious, which easily solves the problem of "how often" we mentioned earlier when polling the code repository, realizing that each code change corresponds to a build.
2.2.1 implement GitLab trigger in pipeline
GitLab-based trigger is implemented on the GitLab plug-in. The following is how to use it.
Pipeline {agent any triggers {gitlab (triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: "All", secretToken: "t8vcxwuza023ehzcftzr5a74vkpto6xr")} stages {stage ('build') {steps {echo' Hello World from gitlab trigger'}
SecretToken can be generated using a random string generator. If Jenkins is used in the intranet and security is guaranteed, we can define secretToken as a Jenkins global variable for all projects to use. This eliminates the need to regenerate the token for each project.
The GitLab trigger method has many parameters that can be configured. Here are some commonly used parameters.
TriggerOnPush: whether to execute the build when the GitLab triggers the push event.
TriggerOnMergeRequest: whether to execute the build when the GitLab triggers the mergeRequest event.
BranchFilterType: only branches that meet the criteria will be triggered. Required, otherwise the trigger cannot be implemented. The values that can be set are:
NameBasedFilter: filter based on branch names, with multiple branch names separated by commas.
RegexBasedFilter: filter branch names based on regular expressions.
All: all branches are triggered.
IncludeBranchesSpec: based on the branchFilterType value, enter the rules for the branches you want to include.
ExcludeBranchesSpec: based on the branchFilterType value, enter the rules for the branches that you want to exclude.
2.2.2 trigger using the Generic Webhook Trigger plug-in
After installing the Generic Webhook Trigger plug-in (hereinafter referred to as GWT), Jenkins exposes an API:
< JENKINS URL > / generic-webhook-trigger/invoke, that is, the GWT plug-in processes the request for this API.
The following is an example of using token:
Pipeline {agent any triggers {GenericTrigger (genericVariables: [[key: 'ref', value:' $.ref']], token: 'secret', causeString:' Triggered on $ref', printContributedVariables: true PrintPostContent: true)} stages {stage ("Some step") {steps {sh "echo $ref" sh "printenv"}
Curl-X POST-H "Content-Type: application/json"-d'{"ref": "ref/heads/master"}'- s https://jenkins.utcook.com/generic-webhook-trigger/invoke?token=secret
The GenericTrigger trigger condition is provided by the GWT plug-in. This trigger condition can be said to be all the contents of GWT.
The GenericTrigger trigger condition can be divided into five parts, which makes it easier to understand the role of each parameter.
Extract the parameter values from the HTTP POST request.
The token,GWT plug-in is used to identify the uniqueness of Jenkins projects.
Determine whether the execution of the Jenkins project is triggered according to the request parameter value.
Log printing control.
Webhook response control.
A HTTP POST request can extract parameters from three dimensions, namely, POST body, URL parameters, and header
The GWT plug-in provides three parameters to extract the data from these three dimensions.
GenericVariables: extract parameters from POST body.
GenericVariables: [[key: 'ref', value:' $.ref'], [key: 'before', value:' $.before', expressionType: 'JSONPath', regexpFilter:', defaultValue:']]
Value:JSONPath expressions, or XPath expressions, depending on the value of the expressionType parameter, are used to extract values from POST body.
Key: the new variable name of the value extracted from POST body, which can be used in other steps of pipeline.
ExpressionType: optional, the expression type of value. Default is JSONPath. When the request is XML content, you must specify an XPath value.
DefaultValue: optionally, defaultValue is used as the return value when no value is extracted and defaultValue is not empty.
RegexpFilter: optional, filter expressions, filter the extracted values. What regexpFilter does is actually string.replaceAll (regexpFilter, "");. String is the value extracted from the HTTP request.
GenericRequestVariables: extract the value from the URL parameter.
GenericRequestVariables: [[key: 'requestWithNumber', regexpFilter:' [^ 0-9]], [key: 'requestWithString', regexpFilter:']]
Key: the new variable name of the extracted value, which can be used in other steps of pipeline.
RegexpFilter: filter the extracted values.
GenericHeaderVariables: extract values from HTTP header.
GenericHeaderVariables: [[key: 'headerWithNumber', regexpFilter:' [^ 0-9]], [key: 'headerWithString', regexpFilter:']]
GenericHeaderVariables is used in the same way as genericRequestVariables, except that it extracts values from HTTP header.
Judge whether the Jenkins project execution is triggered according to the request parameter value.
GWT does not only judge whether it is triggered by the token value, but also based on the value we have extracted. Examples are as follows:
GenericTrigger (genericVariables: [key: 'refValue', value:' $.ref'],], token: env.JOB_NAME, regexpFilterText:'$refValue', regexpFilterExpression: 'refs/heads/ (master | dev)')
RegexpFilterText: the key that needs to match. In the example, we use the value of the refValue variable extracted from POST body.
RegexpFilterExpression: regular expression.
If the value of the regexpFilterText parameter matches the regular expression of the regexpFilterExpression parameter, execution is triggered.
Control what is printed
Printing logs is helpful for debugging. The GWT plug-in provides three parameters.
PrintPostContent: a Boolean value that prints Webhook request information to the log.
PrintContributedVariables: Boolean value that prints out the extracted variable name and variable value.
CauseString: string type, trigger reason, you can directly refer to the extracted variable, such as causeString:'Triggered on $msg'.
Control response
SilentResponse: Boolean type. Normally, when the Webhook request is successful, the GWT plug-in will return the HTTP 200status code and trigger result to the caller. But when silentResponse is set to true, only the HTTP 200status code is returned, and no trigger result is returned.
3. Develop push code to trigger jenkins build practice 3.1 install Jenkins plug-in
GitLab
Git
3.2 create a project
Create a new gitlab project
Create a new jenkins project
Gltlab Settings Integration webhook
Webhook test error report
The above error report requires jenkins installation setting. Uncheck "CSRF Protection".
3.3 push build status information to Gitlab
After jenkins builds the project, you can push the status information of the build to the pipeline of gitlab, and clicking pipeline will automatically jump to the build page of jenkins.
First of all, the personal access token is generated under the administrative account of the gitlab warehouse.
Then in jenkins, go to "Manage Jenkins" → "Configure System", find "Gitlab" on the page, and add gitlab and token credential information.
Modify the Jenkinsfile. If the task has not been triggered in the jenkins, it needs to be triggered manually for the first time. Later, the modification of the code in the gitlab will be triggered automatically, and the running result will be submitted to the gitlab pipeline.
Complete Jenkinsfile:
Pipeline {agent any triggers {gitlab (triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: "All" SecretToken: "t8vcxwuza023ehzcftzr5a74vkpto6xr")} stages {stage ('build') {steps {echo' Hello World from gitlab trigger'} post {failure {updateGitlabCommitStatus name: "build", state: "failed"} success {updateGitlabCommitStatus name: "build" State: "success"}} options {gitLabConnection ("gitlab")}}
The build information can be seen in the pipeline of the gitlab repository.
This is how to trigger Pipeline execution in Jenkins 2.x shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.