0
0
JenkinsHow-ToBeginner · 3 min read

How to Use archiveArtifacts in Jenkins Pipeline

Use the archiveArtifacts step in a Jenkins Pipeline to save files generated during a build. Specify the files to archive using a pattern like **/*.jar. This makes the files available in the build's artifacts section for download or later stages.
📐

Syntax

The archiveArtifacts step archives files from the workspace so they can be accessed later. It takes a artifacts parameter which is a string pattern matching files to archive.

  • artifacts: A string pattern to select files, e.g., **/*.zip.
  • allowEmptyArchive: Optional boolean to allow no files found without failing.
  • onlyIfSuccessful: Optional boolean to archive only if the build succeeds.
groovy
archiveArtifacts artifacts: 'path/to/files/*.zip', allowEmptyArchive: false, onlyIfSuccessful: true
💻

Example

This example shows a simple Jenkins Pipeline that builds a project, creates a zip file, and archives it using archiveArtifacts. The archived file will be available in the build's artifacts.

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                // Simulate build by creating a file
                sh 'echo Hello Jenkins > output.txt'
                sh 'zip output.zip output.txt'
            }
        }
        stage('Archive') {
            steps {
                archiveArtifacts artifacts: 'output.zip'
            }
        }
    }
}
Output
Build creates output.zip and archives it. The build page shows 'output.zip' under 'Artifacts'.
⚠️

Common Pitfalls

  • Using incorrect file patterns that match no files causes the step to fail unless allowEmptyArchive: true is set.
  • Archiving files before they are created or outside the workspace will fail.
  • Not using onlyIfSuccessful: true may archive artifacts even if the build fails.
groovy
pipeline {
    agent any
    stages {
        stage('Archive without files') {
            steps {
                // This will fail if no files match
                archiveArtifacts artifacts: 'nonexistent/*.jar'
            }
        }
    }
}

// Correct way:
archiveArtifacts artifacts: 'nonexistent/*.jar', allowEmptyArchive: true
📊

Quick Reference

ParameterDescriptionDefault
artifactsFile pattern to archive (required)none
allowEmptyArchiveAllow no files found without errorfalse
onlyIfSuccessfulArchive only if build succeedsfalse

Key Takeaways

Use archiveArtifacts to save build files for later access.
Specify file patterns carefully to match the files you want to archive.
Set allowEmptyArchive: true to avoid failures if no files match.
Use onlyIfSuccessful: true to archive artifacts only on successful builds.
Archived artifacts appear in the Jenkins build page for download.