This tutorial explains how to use stash and unstash in a Declarative Jenkins Pipeline to share artifacts between stages and across restarts.
In this tutorial, you’ll learn how to share artifacts between stages—and even across restarts—in a Declarative Jenkins Pipeline using stash and unstash. This is especially useful when stages run on different agents or when you need to resume a job from a later stage.
Enter stash-pipeline-demo, select Pipeline, and click OK.
Paste this basic pipeline script. It has two stages on the same agent, so quote.txt is created and read successfully.
Copy
Ask AI
pipeline { agent any stages { stage('Generate Motivational Quote') { steps { script { def quotes = [ "Believe you can and you're halfway there.", "The only way to do great work is to love what you do.", "Don't watch the clock; do what it does. Keep going.", "Success is not the key to happiness. Happiness is the key to success.", "The only limit to our realization of tomorrow will be our doubts of today." ] def quote = quotes[new Random().nextInt(quotes.size())] writeFile file: 'quote.txt', text: quote } sh 'echo Generate Motivational Quote Success!' sh 'cat quote.txt' } } stage('Display Motivational Quote') { steps { sh 'cat quote.txt' } } }}
If you assign the first stage to a different agent, the file won’t persist on the controller:
Copy
Ask AI
pipeline { agent any stages { stage('Generate Motivational Quote') { agent { label 'ubuntu-docker-jdk17-node20' } steps { /* same script to generate quote.txt */ sh 'cat quote.txt' } } stage('Display Motivational Quote') { steps { sh 'cat quote.txt' sh 'rm quote.txt' } } }}
Run this build—the first stage completes on the Ubuntu agent, but the second fails because quote.txt doesn’t exist on the controller:
Copy
Ask AI
+ echo Generate Motivational Quote Success!Generate Motivational Quote Success!+ cat quote.txtSuccess is not the key to happiness. Happiness is the key to success.+ cat quote.txtcat: quote.txt: No such file or directory
By default, restarting the pipeline at Display Motivational Quote fails since the stash from the previous run isn’t retained:
Copy
Ask AI
Stage "Generate Motivational Quote" skipped due to this build restarting at stage "Display Motivational Quote"[Pipeline] unstashERROR: No such saved stash 'quote'Finished: FAILURE
Use the preserveStashes option in your pipeline to keep stashes from recent builds. You can generate this snippet with the Declarative Directive Generator: