Check out this plugin on the plugin site
catchError
: Catch errors and set build result to errors
If the body throws an exception, mark the build as an error, but still continue executing the pipeline from statement tocatchError
Step. The behavior of the step when an exception is thrown can be configured to print a message, set a build result other than an error, change the stage result, or ignore certain types of exceptions used to break the build.
This step is most useful when used in the declarative pipeline or with the options to set stage outcome or ignore build breaks. Otherwise, consider using plainattempt
-catch
(-Finally
) Blocks. It is also useful when using certain post-build actions (notifiers) originally defined for freestyle projects that pay attention to the result of the ongoing build.
node { catchError { sh 'might fail' } step([$class: 'Mailer', recipient: 'admin@somewhere'])}
If the shell stage fails, the status of the pipeline build is set to "failed" so that the subsequent mail stage recognizes that this build failed. In the case of the email sender, this means that they will send emails. (It can also send emails if this buildsuccededbut previous ones failed, and so on.) Also in this case, this step can be replaced by the following idiom:
node { try { sh 'might fail' } catch (err) { echo "Caught: ${err}" currentBuild.result = 'FEHLER' } step([$class: 'Mailer', EmpfÃĪnger: 'admin@irgendwo'] )}
For other cases easyattempt
-catch
(-Finally
) blocks are used:
node { sh './set-up.sh' try { sh 'may fail' echo 'Successful!' } catch (err) { echo "Failed: ${err}" } finally { sh './tear-down.sh' } echo 'Printed whether the above succeeded or failed.'} // ...and the pipeline as a whole succeeds
Seethis documentfor background.
buildResult : String
(Optional)When an error is caught, the overall build result is set to this value. Note that the build result can only get worse, so you cannot change the result
SUCCESS
if the current result isUNSTABLE
or worse. UseSUCCESS
orNull
to avoid setting the build result when an error is caught.catchInterruptions : boolean
(Optional)If true, certain types of exceptions used to interrupt the flow of execution for pipelines are caught and handled by the step. If false, these types of exceptions are caught and immediately rethrown. Examples of these types of exceptions are those thrown when a build is manually canceled via the UI and those thrown by the
time out
Step. True by default.Message: string
(Optional)A message logged to the console when an error is caught. If the stage outcome is provided, the message is also associated with that outcome and can be viewed in visualizations.
stageResult : String
(Optional)When an error is caught, the step result is set to this value. If a message was specified, the message is associated with that result. Use
SUCCESS
orNull
to prevent the stage result from being set when an error is caught.
delete Dir
: Recursively deletes the current directory from the workspace
Recursively deletes the current directory and its contents. Symbolic links and junctions are not followed, but removed. To delete a specific directory of a workspace, wrap thedelete Dir
step in onedir
Step.
Echo
: Print message
Message: string
The message to write to the console output.
Mistake
: error signal
Signals an error. Useful when you want to conditionally abort part of your program. You can also justthrow new Exception()
, but this step avoids printing a stack trace.
Message: string
The message logged to the console when an error is caught.
file exists
: Check if the file exists in the workspace
Checks whether the specified file exists on the current node. Returnstrue | INCORRECT
. This step must be performed within anode
Context:
# Declarative syntax stage ('Check existence of index.html') { agent any # Could be a top-level or stage-level directive steps { script { if (fileExists('src/main/resources/index.html') ) { echo "Found src/main/resources/index.html file!" } } }}
With the declarative syntax, it must be executed in a stage with an agent defined (e.g. other than "agent none"):
# Scripted Syntaxnode { if (fileExists('src/main/resources/index.html')) { echo "Datei src/main/resources/index.html gefunden!" }}
File: string
Path to a file or directory to verify its existence.
- Both absolute and relative paths are supported. If you use a relative path, it is relative to the current working directory (the workspace by default).
- Both Unix and Windows paths are supported with a
/
Separator:node('Linux') { if (fileExists('/usr/local/bin/jenkins.sh')) { sh '/usr/local/bin/jenkins.sh' }}node('Windows') { if ( fileExists('C:/jenkins.exe')) {bat 'C:/jenkins.exe' }}
When using a Windows path with the backslash (\
) separator, don't forget to escape it:node('Windows') { if (fileExists('src\\main\\resources')) { echo 'Found directory resources.' } }
istUnix
: Checks if it is running on a Unix-like node
Returns true if includednode
is running on a Unix-like system (like Linux or Mac OS X), false if Windows.
Post
: Post
Simple step to send email.
Subject: String
Email subject line.
body: string
message text.
bcc : string
(Optional)BCC email address list. Comma separated list of email addresses.
See AlsoGetting started with pipelinescc: string
(Optional)CC email address list. Comma separated list of email addresses.
Character set : string
(Optional)Character encoding for the email body. Defaults to
UTF-8
from : string
(Optional)From the email address. By default, the admin address configured globally for the Jenkins instance.
mimeType : String
(Optional)MIME type of the email body. Defaults to
Text/ready
.answerTo : String
(Optional)Reploy-To email address. By default, the admin address configured globally for the Jenkins instance.
to : string
(Optional)To the email address list. Comma separated list of email addresses.
pwd
: Get current directory
Returns the current directory path as a string.
tmp: boolesch
(Optional)When this option is selected, a temporary directory associated with the current directory path is returned, not the directory path itself. The return value is different for each current directory. No two directories share the same temporary directory. This is a convenient place to put temporary files that shouldn't overload a source check; local repositories or caches; etc. False by default.
readFile
: Read file from workspace
Reads a file from a relative path (with root in the current directory, usually workspace) and returns its content as a simple string.
File: string
Relative (
/
-delimited) Path to the file within a workspace to read.Encoding: string
(Optional)The encoding to use when reading the file. If left blank, the platform default encoding will be used. Binary files can be read into a Base64 encoded string by specifying "Base64" as the encoding.
repeat
: Repeat the body up to N times
Repeat the block (up to N times) if an exception occurs during execution of the body. If an exception occurs on the last attempt, it will cause the build to abort (unless it's somehow caught and processed). User crashes of the build arenotcaught.
count : int
Conditions
(Optional)Conditions under which the block should be repeated. If none match, the block fails. If no conditions are specified, the block is always repeated, except in the case of user exits.
(Video) The Basic Steps of an Animation Pipeline- Array/list of nested selection of objects
Agent
Recognize that a
node
block, or specific steps in it such asSch
, failed for reasons likely related to infrastructure rather than build behavior. If the connection to an agent is lost or the agent is removed from the list of executors while in use (usually in response to the disappearance of underlying cloud resources), this condition allowsrepeat
assign a new agent and try the whole block again.kubernetesAgent
Similar to
Agent()
(agent error), but tailored for agents deployed from a Kubernetes cloud. Unlike the agent's generic error condition, this ignores certain pod termination reasons that are likely under the pipeline author's control (e.g.OOM killed
) while still allowedrepeat
to recover from frequent cases of pod deletion.handleNonKubernetes : boolean
(Optional)Act like the generic
Agent()
(agent error) when applied to a non-Kubernetes agent. Useful in cases where it is difficult to predict in a job definition whether a Kubernetes or another agent will be used.
not continueable
The Jenkins controller restarted while the build was performing a step that cannot continue. Some steps like
Sch
orEntry
are written to survive a Jenkins restart and just pick up where they left off when the build resumes. others likeBox
orjunit
usually completes immediately but cannot tolerate a reboot. If any of these steps were in progress when Jenkins was shut down, the continued build will throw an error. Use this condition withrepeat
allows the stage (or the whole enclosurenode
block) are repeated.
sleep
: Sleep
The pipeline build will simply pause until the specified amount of time elapses. Equivalent (on Unix)sch 'sleep ...'
. Can be used to pause a branch ofparallel
while another continues.
Time: International
The length of time the step sleeps.
Unit
(Optional)The unit for the time parameter. Defaults to 'SECONDS' if not specified.
- Values:
NANOSECONDS
,THE MICROSECOND
,MILLISECONDS
,SECONDS
,PROTOCOL
,STD
,TAKE
- Values:
stow away
: Stash away some files to be used later in the build
Saves a set of files for later use on each node/workspace in the same pipeline run. By default, cached files are discarded at the end of a pipeline run. Other plugins can change this behavior to keep stashes longer. For example, the declarative pipeline contains akeepStashes()
Option to allow stashes from a run to be retained and used when that run is restarted.
Stashes from one pipeline run are not available in other runs, other pipelines, or other jobs. If you want to persist artifacts for use outside of a single execution, consider usingArchive Artifactsinstead of this.notethat thestow away
Anddecongest
Steps are designed for use with small files. For large data transfers, use the External Workspace Manager plugin or an external repository manager like Nexus or Artifactory. This is because hidden files are archived in a compressed TAR and for large files this requires significant on-master resources, especially CPU time. There is no hard stash size limit, but between 5 and 100 MB you should probably consider alternatives.
Name: string
name of a hiding place. Should be a simple identifier, similar to a job name.
allowEmpty : boolesch
(Optional)Stash even if no files are included. If
INCORRECT
(Default) throws an error if the stash contains no files.excludes: string
(Optional)Optional set ofAnt style exclusion pattern.
Use a comma separated list to add more than one expression.
If empty, no files are excluded.contains: string
(Optional)Optional set ofAnt style include patterns.
Use a comma separated list to add more than one expression.
If empty, how treated**
: all files.
The current working directory is the base directory for the saved files, which are later restored to the same relative locations. So if you want to use a subdirectory, include thatdir.useDefaultExcludes : boolesch
(Optional)If selected, use Ant's default exclusions - seeHerefor the list. True by default.
Step
: General build step
This is a special step that allows to call builders or post-build actions (as in freestyle or similar projects), generally "build steps". Simply select the build step to invoke from the drop-down list and configure as needed.
Note that only pipeline-compatible steps appear in the list.
To use this step, you must provide a delegate class, e.gstep([$class: 'A3Builder'])
.
time out
: Enforce timeout
Executes the code within the block with a specified timeout limit. When the timeout is reached, an exception (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException) is thrown, causing the build to abort (unless it's somehow caught and processed).
Time: International
The amount of time this step will wait before aborting the nested block.
Activity: Boolean
(Optional)Timeout after no activity in logs for this block instead of the absolute duration. False by default.
Unit
(Optional)The unit of the time parameter. Defaults to 'MINUTES' if not specified.
- Values:
NANOSECONDS
,THE MICROSECOND
,MILLISECONDS
,SECONDS
,PROTOCOL
,STD
,TAKE
- Values:
Tool
: Use a tool from a predefined tool installation
Binds a tool installation to a variable (returns the tool's home directory). Only already configured tools inConfigure system
are available here. If the original tool installer has the auto-deploy feature, the tool will be installed as required.
Name: string
The name of the tool. The tool name must be preconfigured in Jenkins atManage JenkinsâGlobal tool configuration.
Type: String
(Optional)Select the type from those availableintegrated tool provider.
unstable
: Set stage result to unstable
Prints a message to the log and sets up the total build result and the stage resultUNSTABLE
. The message is also linked to the stage result and can be viewed in visualizations.
Message: string
A message that is logged to the console. The message is also linked to the stage result and can be viewed in visualizations.
decongest
: Restore previously saved files
Previously restores a set of filesstow away
pasted into the current workspace.
Name: string
Name of a previously saved stash.
wait until
: Wait for status
Performs his body repeatedly until he returnsTRUE
. when it returnsINCORRECT
, wait a while and try again. (Consecutive errors slow the delay between attempts to a maximum of 15 seconds.) There is no limit to the number of repetitions, but if the body throws an error, it is issued immediately.
initialRecurrencePeriod : lang
(Optional)Sets the initial wait time between retries in milliseconds. Default 250ms.
Each error slows down the delay between attempts to a maximum of 15 seconds.quiet : boolean
(Optional)If true, the step does not log a message each time the condition is checked. False by default.
warnError
: Catch errors and set build and stage result to unstable
Executes its body and, if an exception is thrown, sets up the general build result and the stage resultUNSTABLE
, prints a specified message and the exception that is thrown in the build log, and associates the stage result with the message for visualizations to display.
EquivalentcatchError(message: message, buildResult: 'UNSTABLE', stageResult: 'UNSTABLE')
.
Message: string
A message logged to the console when an error is caught. The message is also linked to the stage result and can be viewed in visualizations.
(Video) Basic Pipeline ConstructioncatchInterruptions : boolean
(Optional)If true, certain types of exceptions used to interrupt the flow of execution for pipelines are caught and handled by the step. If false, these types of exceptions are caught and immediately rethrown. Examples of these types of exceptions are those thrown when a build is manually canceled via the UI and those thrown by the
time out
Step. True by default.
mitEnv
: set environment variables
Sets one or more environment variables within a block. Environment variable names are not case-sensitive, so setting "Foo" changes the value of "FOO" if it already exists. Environment variables are available to all external processes spawned in this area. For example:
node { withEnv(['MYTOOL_HOME=/usr/local/mytool']) { sh '$MYTOOL_HOME/bin/start' }}
(Note that we're using Groovy single quotes here, so variable expansion is done by the Bourne shell, not Jenkins.)
See the documentation for thatenv
singleton for more information on environment variables.
overrides: array/list of string
A list of environment variables to set, each on the form
VARIABLE=Wert
orVARIABLE=
to reset otherwise defined variables. You can also use the syntaxPATH+WHATEEVER=/etwas
put in front/something
To$PATH
.
wrap
: Generic build wrapper
This is a special step that makes it possible to call build wrappers (also called "environment configuration" in Freestyle or similar projects). Simply select the wrapper to use from the drop-down list and configure as needed. Everything inside the wrapper block is under its effect.
Note that only pipeline-compatible wrappers appear in the list.
To use this step, you must provide a delegate class, e.gwrap([$class: 'AnsiColorBuildWrapper'])
.
write file
: Write file to workspace
Writes the specified content to a named file in the current directory.
File: string
Relative path of a file within the workspace.
text string
The data to write to the file.
Encoding: string
(Optional)The target encoding for the file. If left blank, the platform default encoding will be used. If the text is a Base64 encoded string, the decoded binary data can be written to the file by specifying Base64 as the encoding.
archive
: Archive artifacts
Archives create output artifacts for later use. As of Jenkins 2.x, this step is deprecated in favor of the more configurable onesArchive Artifacts
.
contains: string
Include matching artifactsAnt style pattern. Use a comma separated list to add more than one expression.
excludes: string
(Optional)Exclude artifacts that matchAnt style pattern.
Use a comma separated list to add more than one expression.
getContext
: Get context object from internal APIs
Gets a context object as inStepContext.get
; see.myContext
. Lasts a singleTyp
Dispute. Example:
getContext hudson.FilePath
For use from trusted code, such as B. global libraries that can manipulate internal Jenkins APIs.
Typ
- Typ:
java.lang.Class<?>
- Typ:
unarchivieren
: Copy archived artifacts to the workspace
mapping
(Optional)- Typ:
java.util.Map<java.lang.String, java.lang.String>
- Typ:
myContext
: Use context object from internal APIs inside a block
Encloses a block in a context object as inBodyInvoker.withContext
; see.getContext
. Lasts a singlecontext
argument plus block. Example:
withContext(new MyConsoleLogFilter()) { sh 'process'}
In the case of automatically, merges its argument with context objectsConsoleLogFilter
,LauncherDecorator
, AndEnvironmentExpander
.
For use from trusted code, such as B. global libraries that can manipulate internal Jenkins APIs.
Do nottry to pass objects defined in Groovy; only Java-defined objects are supported. Really you should avoid using this andgetContext
and just define aStep
instead in a plugin.
Context:
Object