0
0
JenkinsHow-ToBeginner · 3 min read

How to Use writeFile in Jenkins Pipeline

In Jenkins Pipeline, use the writeFile step to create or overwrite a file by specifying the file name and text content. This step writes the given text to the file on the agent where the pipeline runs, enabling you to generate configuration or data files dynamically.
📐

Syntax

The writeFile step requires two main parameters:

  • file: The name (and path) of the file to write.
  • text: The content to write inside the file.

Both parameters are strings. The file is created or overwritten on the agent workspace.

groovy
writeFile file: 'filename.txt', text: 'file content here'
💻

Example

This example shows a simple Jenkins Pipeline script that writes a message to a file named greeting.txt and then reads and prints its content.

groovy
pipeline {
    agent any
    stages {
        stage('Write File') {
            steps {
                script {
                    writeFile file: 'greeting.txt', text: 'Hello from Jenkins Pipeline!'
                }
            }
        }
        stage('Read File') {
            steps {
                script {
                    def content = readFile('greeting.txt')
                    echo "File content: ${content}"
                }
            }
        }
    }
}
Output
[Pipeline] echo File content: Hello from Jenkins Pipeline!
⚠️

Common Pitfalls

Common mistakes when using writeFile include:

  • Not specifying the file parameter correctly, causing the file to be created in unexpected locations.
  • Using relative paths without understanding the workspace context, which can lead to file not found errors later.
  • Forgetting that writeFile overwrites existing files without warning.

Always verify the file path and content before and after writing.

groovy
/* Wrong: missing file parameter name */
writeFile('greeting.txt', 'Hello')

/* Right: named parameters */
writeFile file: 'greeting.txt', text: 'Hello'
📊

Quick Reference

Use this quick reference to remember the writeFile usage:

ParameterDescriptionExample
fileName and path of the file to write'output.txt'
textContent to write inside the file'Hello Jenkins!'

Key Takeaways

Use writeFile with named parameters: file and text.
writeFile creates or overwrites files in the agent workspace.
Always specify file paths relative to the workspace for clarity.
writeFile is useful for generating config or data files dynamically.
Check file content after writing using readFile or echo.