Fezofchekov
Fezofchekov

Reputation: 69

Pass build inputs from Jenkins to a Python script

I wrote this simple Jenkinsfile to execute a Python script.

The Jenkins job is supposed to take the value of the Jenkins build parameter and inject it to the python script, then execute the python script.

Here is the Jenkinsfile

pipeline{
agent any
parameters {
    string description: 'write the week number', name: 'Week_Number'
}
stages{
    stage("Pass Week Number&execute script"){
        steps{
            sh 'python3 statistics.py'
        }
    }
}
}

So what will happen is that I will go to Jenkins, choose build with parameters, and write some value in the Week_Number variable.

What i need to do is: Pass this Week_Number value as an integer to a variable in the python script.

This is the part of the Python script that I'm interested in:

  weekNum = int(os.environ.get("Week_Number"))

I read online about the use of os.environ.get() to pass values, but I think something is still missing for the Python script to fetch the Jenkins build parameter.

Any help?

Upvotes: 0

Views: 3556

Answers (1)

Siddharth Kaul
Siddharth Kaul

Reputation: 972

You need your python script to be able to parse command line arguments or named command line arguments.

If your script is using command line argument you can pass parameters as follow:

stages{
    stage("Pass Week Number&execute script"){
        steps{
            sh('python3 statistics.py ' + params.Week_Number)
        }
    }
}

If your script uses the named command line argument where the named argument in the script is input_week_number you can pass as follows:

stages{
    stage("Pass Week Number&execute script"){
        steps{
            sh('python3 statistics.py --input_week_number' + params.Week_Number)
        }
    }
}

Upvotes: 1

Related Questions