Vitamin C
Vitamin C

Reputation: 312

Get info about Jenkins job from within python while the job is running

So, I have this python script on Jenkins.

I would like to write a function that, when called from Jenkins pipeline, will tell me which job it belongs to and ideally a link to the job itself.

Basically, the script must know that it is being run on Jenkins and tell which job / pipeline is running it.

If I run a build and it has this path: https://jenkins.foo.com/job/PYTHON-TEST/job/env_test/226/, I want the script to return this link or at least parts of it like:

  1. jenkins.foo.com
  2. PYTHON-TEST
  3. env_test
  4. 226

I see that points 2,3,4 can be pretty much extracted using

import socket

socket.gethostname() # python-test-env-test-226-pt1l3-a1op4-61ak5

I know it is possible on Databricks using:

dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson()

In fact, I already implemented it there. Now, I am searching for a similar functionality on Jenkins. Any advice on how to do it? Perhaps, there are some other ways instead of socket.gethostname()?

Upvotes: 0

Views: 542

Answers (1)

ycr
ycr

Reputation: 14604

All of these information are avaialble as environment variables for you. So if you want to extract them through python you should be able to easily do it. Following are some relvent environment variables you can use.

JOB_NAME - Name of the Job of this build.
BUILD_NUMBER - The current build number. For example "153"
JENKINS_URL - URL of Jenkins. For example http://server:port/jenkins/
BUILD_URL - Full URL of this build. For example http://server:port/jenkins/job/foo/15/
JOB_URL - Full URL of this job. For example http://server:port/jenkins/job/foo/

Upvotes: 1

Related Questions