This tutorial will show you how to run a Python script from a Jenkins pipeline. We will be using the Jenkins Pipeline syntax to accomplish this.
Before we get started, make sure that you have the following prerequisites:
- A Jenkins instance
- A Python script that you want to run
- The Python interpreter installed on the Jenkins controller or Agent
Jenkins Run Python Script in Pipeline
We can run a Python script within a Jenkins pipeline using the sh command in Jenkins. Let us see how we can do this.
Start by creating a new Jenkins pipeline. To do this, go to the Jenkins dashboard, click on the “New Item” link, and then choose the “Pipeline” option.
Give the pipeline a name and click the “OK” button.
Next, we will need to define the Jenkins pipeline. There are two ways to do this:
- Declarative Pipeline syntax
- Scripted Pipeline syntax
We will be using the Declarative Pipeline syntax in this tutorial.
To define the pipeline, we need to specify a series of stages where each stage represents a specific step in the pipeline.
In this case, we will create a single stage that runs our Python script. An example pipeline is as shown in the example below:
agent {
label 'python'
}
stages {
stage('Run Python Script') {
steps {
sh 'python3 script.py'
}
}
}
}
Let us go through each section of this Jenkinsfile in more detail:
- The pipeline block allows us to define the start of our pipeline.
- Next, we use the agent block to specify the agent used to run our pipeline. In this case, we are using the label directive to specify that we want to use a Jenkins agent with the label “python.” This ensures that the pipeline will run on a machine with the Python interpreter installed.
- The stages block defines a series of stages in our pipeline. In this case, we only have a stage called “Run Python Script.”
- In the next section, the steps block to define the steps that will be executed within the stage. We are using the sh directive to run a shell command in this case. The command we are running is python3 script.py which will execute our Python script.
Once we have defined the pipeline, we can save and run it by clicking the “Build Now” button on the Jenkins dashboard.
If the pipeline runs successfully, we should see the output of the Python script in the Jenkins console output.
We can also use the Console Output to diagnose any errors and fix them for the job to run successfully.
Conclusion
In this article, you learned how to use the sh directive in a Jenkins pipeline to run a Python script.