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 : String (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.
  • catchInterruptions : boolean (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. Defaults to true.
  • message : String (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.
  • stageResult : String (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.

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.

    echo: Print Message

    • message : String
      The message to write to the console output.

    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 : String
      The message that will be logged to the console when an error is caught.

    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/resources/index.html')) {
                    echo "File src/main/resources/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/resources/index.html')) {
            echo "File src/main/resources/index.html found!"
        }
    }
    

    • file : String
      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.' } }

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

      pwd: Determine current directory

      Returns the current directory path as a string.
      • tmp : boolean (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. Defaults to false.

      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 : String
        Relative (/-separated) path to 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.

      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 : int
      • conditions (optional)
        Conditions under which the block should be retried. If none match, the block will fail. If there are no specified conditions, the block will always be retried except in case of user aborts.
          Array / List of Nested Choice of Objects
        • agent
          Detects that a node block, or certain steps inside it such as sh, failed for reasons which are likely due to infrastructure rather than the behavior of the build. If the connection to an agent is broken or the agent is removed from the list of executors while in use (typically in response to the disappearance of underlying cloud resources), this condition will allow retry to allocate a fresh agent and try the whole block again.
          • kubernetesAgent
            Similar to agent() (Agent errors) but tailored to agents provisioned from a Kubernetes cloud. Unlike the generic agent error condition, this will ignore certain pod termination reasons which are likely to be under the control of the Pipeline author (e.g., OOMKilled) while still allowing retry to recover after common cases of pod deletion.
            • handleNonKubernetes : boolean (optional)
              Behave like the generic agent() (Agent errors) when applied to a non-Kubernetes agent. Useful in cases where it is hard to predict in a job definition whether a Kubernetes or other sort of agent will be used.
          • nonresumable
            The Jenkins controller was restarted while the build was running a step which cannot be resumed. Some steps like sh or input are written to survive a Jenkins restart and simply pick up where they left off when the build resumes. Others like checkout or junit normally complete promptly but cannot tolerate a restart. In case one of these steps happened to be in progress when Jenkins shut down, the resumed build will throw an error; using this condition with retry allows the step (or the whole enclosing node block) to be rerun.

          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 : int
            The length of time for which the step will sleep.
          • 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 : String
            Name of a stash. Should be a simple identifier akin to a job name.
          • allowEmpty : boolean (optional)
            Create stash even if no files are included. If false (default), an error is raised when the stash does not contain files.
          • excludes : String (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.
          • includes : String (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.
          • useDefaultExcludes : boolean (optional)
            If selected, use the default excludes from Ant - see here for the list. Defaults to true.

          step: General Build Step

          java.nio.file.FileSystemNotFoundException

          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 : int
            The length of time for which this step will wait before cancelling the nested block.
          • activity : boolean (optional)
            Timeout after no activity in logs for this block instead of absolute duration. Defaults to false.
          • 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 : String
            The name of the tool. The tool name must be pre-configured in Jenkins under Manage JenkinsGlobal Tool Configuration.
          • type : String (optional)
            Select the type from the available built-in tool providers.

          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 : String
            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.

          unstash: Restore files previously stashed

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

          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 : long (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.
          • quiet : boolean (optional)
            If true, the step does not log a message each time the condition is checked. Defaults to false.

          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 : String
            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.
          • catchInterruptions : boolean (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. Defaults to true.

          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 : Array / List of String
            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.

            wrap: General Build Wrapper

            java.nio.file.FileSystemNotFoundException

            writeFile: Write file to workspace

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

            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 : 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.