The following plugin provides functionality available through Pipeline-compatible steps. Read more about how to integrate steps into your Pipeline in the Steps section of the Pipeline Syntax page.

For a list of other such plugins, see the Pipeline Steps Reference page.

Pipeline: Basic Steps

catchError: Catch error and set build result to failure

If the body throws an exception, mark the build as a failure, but nonetheless continue to execute the Pipeline from the statement following the catchError step. The behavior of the step when an exception is thrown can be configured to print a message, set a build result other than failure, change the stage result, or ignore certain kinds of exceptions that are used to interrupt the build.

This step is most useful when used in Declarative Pipeline or with the options to set the stage result or ignore build interruptions. Otherwise, consider using plain try-catch(-finally) blocks. It is also useful when using certain post-build actions (notifiers) originally defined for freestyle projects which pay attention to the result of the ongoing build.

node {
    catchError {
        sh 'might fail'
    }
    step([$class: 'Mailer', recipients: 'admin@somewhere'])
}

If the shell step fails, the Pipeline build’s status will be set to failed, so that the subsequent mail step will see that this build is failed. In the case of the mail sender, this means that it will send mail. (It may also send mail if this build succeeded but previous ones failed, and so on.) Even in that case, this step can be replaced by the following idiom:

node {
    try {
        sh 'might fail'
    } catch (err) {
        echo "Caught: ${err}"
        currentBuild.result = 'FAILURE'
    }
    step([$class: 'Mailer', recipients: 'admin@somewhere'])
}

For other cases, plain try-catch(-finally) blocks may be used:

node {
    sh './set-up.sh'
    try {
        sh 'might fail'
        echo 'Succeeded!'
    } catch (err) {
        echo "Failed: ${err}"
    } finally {
        sh './tear-down.sh'
    }
    echo 'Printed whether above succeeded or failed.'
}
// …and the pipeline as a whole succeeds

See this document for background.

  • buildResult (optional)
    If an error is caught, the overall build result will be set to this value. Note that the build result can only get worse, so you cannot change the result to SUCCESS if the current result is UNSTABLE or worse. Use SUCCESS or null to keep the build result from being set when an error is caught.
    • Type: String
  • catchInterruptions (optional)
    If true, certain types of exceptions that are used to interrupt the flow of execution for Pipelines will be caught and handled by the step. If false, those types of exceptions will be caught and immediately rethrown. Examples of these types of exceptions include those thrown when a build is manually aborted through the UI and those thrown by the timeout step.
    • Type: boolean
  • message (optional)
    A message that will be logged to the console if an error is caught. If the stage result is specified, the message will also be associated with that result and may be shown in visualizations.
    • Type: String
  • stageResult (optional)
    If an error is caught, the stage result will be set to this value. If a message was specified, the message will be associated with this result. Use SUCCESS or null to keep the stage result from being set when an error is caught.
    • Type: String

deleteDir: Recursively delete the current directory from the workspace

Recursively deletes the current directory and its contents. Symbolic links and junctions will not be followed but will be removed. To delete a specific directory of a workspace wrap the deleteDir step in a dir step.

    dir: Change current directory

    Change current directory. Any step inside the dir block will use this directory as current and any relative path will use it as base path.
    • path
      • Type: String

    echo: Print Message

    • message
      • Type: String

    error: Error signal

    Signals an error. Useful if you want to conditionally abort some part of your program. You can also just throw new Exception(), but this step will avoid printing a stack trace.
    • message
      • Type: String

    fileExists: Verify if file exists in workspace

    Checks if the given file exists on the current node. Returns true | false. This step must be run inside a node context:

    # Declarative Syntax
    stage ('Check for existence of index.html') {
        agent any # Could be a top-level directive or a stage level directive
        steps {
            script {
                if (fileExists('src/main/rersources/index.html') {
                    echo "File src/main/rersources/index.html found!"
                }
            }
        }
    }
    

    With the Declarative Syntax, it must be run in a stage with a defined agent (e.g. different than `agent none`):

    # Scripted Syntax
    node {
        if (fileExists('src/main/rersources/index.html') {
            echo "File src/main/rersources/index.html found!"
        }
    }
    

    • file
      Path to a file or a directory to verify its existence.
      • Both absolute and relative paths are supported. When using relative path, it is relative to the current working directory (by default: the workspace).
      • Both Unix and Windows path are supported using 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, do not forget to escape it:

        node('Windows') { if (fileExists('src\\main\\resources') { echo 'Found a directory resources.' } }

      • Type: String

    isUnix: Checks if running on a Unix-like node

    Returns true if enclosing node is running on a Unix-like system (such as Linux or Mac OS X), false if Windows.

      mail: Mail

      Simple step for sending email.
      • subject
        Email subject line.
        • Type: String
      • body
        Email body.
        • Type: String
      • bcc (optional)
        BCC email address list. Comma separated list of email addresses.
        • Type: String
      • cc (optional)
        CC email address list. Comma separated list of email addresses.
        • Type: String
      • charset (optional)
        Email body character encoding. Defaults to UTF-8
        • Type: String
      • from (optional)
        From email address. Defaults to the admin address globally configured for the Jenkins instance.
        • Type: String
      • mimeType (optional)
        Email body MIME type. Defaults to text/plain.
        • Type: String
      • replyTo (optional)
        Reploy-To email address. Defaults to the admin address globally configured for the Jenkins instance.
        • Type: String
      • to (optional)
        To email address list. Comma separated list of email addresses.
        • Type: String

      pwd: Determine current directory

      Returns the current directory path as a string.
      • tmp (optional)
        If selected, return a temporary directory associated with the current directory path rather than the directory path itself. The return value is different for each current directory. No two directories share the same temporary directory. This is an appropriate place to put temporary files which should not clutter a source checkout; local repositories or caches; etc.
        • Type: boolean

      readFile: Read file from workspace

      Reads a file from a relative path (with root in current directory, usually workspace) and returns its content as a plain string.
      • file
        Relative (/-separated) path to file within a workspace to read.
        • Type: String
      • encoding (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.
        • Type: String

      retry: Retry the body up to N times

      Retry the block (up to N times) if any exception happens during its body execution. If an exception happens on the final attempt then it will lead to aborting the build (unless it is caught and processed somehow). User aborts of the build are not caught.
      • count
        • Type: int

      sleep: Sleep

      Simply pauses the Pipeline build until the given amount of time has expired. Equivalent to (on Unix) sh 'sleep …'. May be used to pause one branch of parallel while another proceeds.
      • time
        The length of time for which the step will sleep.
        • Type: int
      • unit (optional)
        The unit for the time parameter. Defaults to 'SECONDS' if not specified.
        • Values: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS

      stash: Stash some files to be used later in the build

      Saves a set of files for later use on any node/workspace in the same Pipeline run. By default, stashed files are discarded at the end of a pipeline run. Other plugins may change this behavior to preserve stashes for longer. For example, Declarative Pipeline includes a preserveStashes() option to allow stashes from a run to be retained and used if 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 run, consider using archiveArtifacts instead. Note that the stash and unstash steps are designed for use with small files. For large data transfers, use the External Workspace Manager plugin, or use an external repository manager such as Nexus or Artifactory. This is because stashed files are archived in a compressed TAR, and with large files this demands considerable on-master resources, particularly CPU time. There's not a hard stash size limit, but between 5-100 MB you should probably consider alternatives.
      • name
        Name of a stash. Should be a simple identifier akin to a job name.
        • Type: String
      • allowEmpty (optional)
        • Type: boolean
      • excludes (optional)
        Optional set of Ant-style exclude patterns.
        Use a comma separated list to add more than one expression.
        If blank, no files will be excluded.
        • Type: String
      • includes (optional)
        Optional set of Ant-style include patterns.
        Use a comma separated list to add more than one expression.
        If blank, treated like **: all files.
        The current working directory is the base directory for the saved files, which will later be restored in the same relative locations, so if you want to use a subdirectory wrap this in dir.
        • Type: String
      • useDefaultExcludes (optional)
        If selected, use the default excludes from Ant - see here for the list.
        • Type: boolean

      step: General Build Step

      This is a special step that allows to call builders or post-build actions (as in freestyle or similar projects), in general "build steps". Just select the build step to call from the dropdown list and configure it as needed.

      Note that only Pipeline-compatible steps will be shown in the list.

      To use this step you need to specify a delegate class, e.g step([$class: 'A3Builder']).

      timeout: Enforce time limit

      Executes the code inside the block with a determined time out limit. If the time limit is reached, an exception (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException) is thrown, which leads to aborting the build (unless it is caught and processed somehow).
      • time
        The length of time for which this step will wait before cancelling the nested block.
        • Type: int
      • activity (optional)
        Timeout after no activity in logs for this block instead of absolute duration.
        • Type: boolean
      • unit (optional)
        The unit of the time parameter. Defaults to 'MINUTES' if not specified.
        • Values: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS

      tool: Use a tool from a predefined Tool Installation

      Binds a tool installation to a variable (the tool home directory is returned). Only tools already configured in Configure System are available here. If the original tool installer has the auto-provision feature, then the tool will be installed as required.
      • name
        • Type: String
      • type (optional)
        • Type: String

      unstable: Set stage result to unstable

      Prints a message to the log and sets the overall build result and the stage result to UNSTABLE. The message will also be associated with the stage result and may be shown in visualizations.
      • message
        A message that will be logged to the console. The message will also be associated with the stage result and may be shown in visualizations.
        • Type: String

      unstash: Restore files previously stashed

      Restores a set of files previously stashed into the current workspace.
      • name
        Name of a previously saved stash.
        • Type: String

      waitUntil: Wait for condition

      Runs its body repeatedly until it returns true. If it returns false, waits a while and tries again. (Subsequent failures will slow down the delay between attempts up to a maximum of 15 seconds.) There is no limit to the number of retries, but if the body throws an error that is thrown up immediately.
      • initialRecurrencePeriod (optional)
        Sets the initial wait period, in milliseconds, between retries. Defaults to 250ms.
        Each failure will slow down the delay between attempts up to a maximum of 15 seconds.
        • Type: long
      • quiet (optional)
        If true, the step does not log a message each time the condition is checked. Defaults to false.
        • Type: boolean

      warnError: Catch error and set build and stage result to unstable

      Executes its body, and if an exception is thrown, sets the overall build result and the stage result to UNSTABLE, prints a specified message and the thrown exception to the build log, and associates the stage result with the message so that it can be displayed by visualizations.

      Equivalent to catchError(message: message, buildResult: 'UNSTABLE', stageResult: 'UNSTABLE').

      • message
        A message that will be logged to the console if an error is caught. The message will also be associated with the stage result and may be shown in visualizations.
        • Type: String
      • catchInterruptions (optional)
        If true, certain types of exceptions that are used to interrupt the flow of execution for Pipelines will be caught and handled by the step. If false, those types of exceptions will be caught and immediately rethrown. Examples of these types of exceptions include those thrown when a build is manually aborted through the UI and those thrown by the timeout step.
        • Type: boolean

      withEnv: Set environment variables

      Sets one or more environment variables within a block. The names of environment variables are case-insensitive but case-preserving, that is, setting `Foo` will change the value of `FOO` if it already exists. Environment variables are available to any external processes spawned within that scope. For example:

      node {
        withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
          sh '$MYTOOL_HOME/bin/start'
        }
      }
      

      (Note that here we are using single quotes in Groovy, so the variable expansion is being done by the Bourne shell, not Jenkins.)

      See the documentation for the env singleton for more information on environment variables.

      • overrides
        A list of environment variables to set, each in the form VARIABLE=value or VARIABLE= to unset variables otherwise defined. You may also use the syntax PATH+WHATEVER=/something to prepend /something to $PATH.
        • Type: Array / List of String

      wrap: General Build Wrapper

      This is a special step that allows to call build wrappers (also called "Environment Configuration" in freestyle or similar projects). Just select the wrapper to use from the dropdown list and configure it as needed. Everything inside the wrapper block is under its effect.

      Note that only Pipeline-compatible wrappers will be shown in the list.

      To use this step you need to specify a delegate class, e.g wrap([$class: 'AnsiColorBuildWrapper']).

      writeFile: Write file to workspace

      Write the given content to a named file in the current directory.
      • file
        • Type: String
      • text
        • Type: String
      • encoding (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.
        • Type: String

      archive: Archive artifacts

      Archives build output artifacts for later use. As of Jenkins 2.x, this step is deprecated in favor of the more configurable archiveArtifacts.
      • includes
        Include artifacts matching this Ant style pattern. Use a comma separated list to add more than one expression.
        • Type: String
      • excludes (optional)
        Exclude artifacts matching this Ant-style pattern.
        Use a comma-separated list to add more than one expression.
        • Type: String

      getContext: Get contextual object from internal APIs

      Obtains a contextual object as in StepContext.get; cf. withContext. Takes a single type argument. Example:

      getContext hudson.FilePath

      For use from trusted code, such as global libraries, which can manipulate internal Jenkins APIs.

      • type
        • Type: java.lang.Class<?>

      unarchive: Copy archived artifacts into the workspace

      • mapping (optional)
        • Type: java.util.Map<java.lang.String, java.lang.String>

      withContext: Use contextual object from internal APIs within a block

      Wraps a block in a contextual object as in BodyInvoker.withContext; cf. getContext. Takes a single context argument plus a block. Example:

      withContext(new MyConsoleLogFilter()) {
          sh 'process'
      }

      Automatically merges its argument with contextual objects in the case of ConsoleLogFilter, LauncherDecorator, and EnvironmentExpander.

      For use from trusted code, such as global libraries, which can manipulate internal Jenkins APIs.

      Do not attempt to pass objects defined in Groovy; only Java-defined objects are supported. Really you should avoid using this and getContext and just define a Step in a plugin instead.

      • context
        • Type: Object

      Was this page helpful?

      Please submit your feedback about this page through this quick form.

      Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?

          


      See existing feedback here.