johan855 johan855 - 1 month ago 5
Python Question

Importing a module outside of Jenkins home directory

I am trying to run a custom Python module located at

'/home/modules/module.py'


The python script is run by Jenkins and located at
'/home/user_name/scripts/script.py'


Since Jenkins home directory is '/var/lib/jenkins' how can I import my module?

I have tried adding the following to the python script:

import sys
sys.path.insert(0,'/home/modules') """also /home/modules/"""

import module


but I am still getting the error:

ImportError: No module named


I am running everything in Ubuntu 14.04 and Python 2.7

EDIT:

I changed Jenkins user directory like this:

root@dwh-01:~$ usermod -m -d /home/jenkins jenkins


and modified
JENKINS_HOME=/home/jenkins
in
/etc/default/jenkins


I think I can work with this, but now the issue is, if I log into jenkins shell and do:

jenkins@dwh-01:/$ cd
bash: cd: jenkins/: No such file or directory


Should the behaviour of the
cd
command direct me to
/home/jenkins/
?
If I repeat the same when in
/home/
It works though.

If I try and start jenkins, it gives me:


  • Starting Jenkins Continuous Integration Server jenkins


    No directory, logging in with HOME=/



EDIT-2:

User jenkins home dir error fixed, I just made sure the home directory of the user was /home/jenkins using
usermod -d /home/jenkins jenkins


I'm a step closer to importing the module, but am still having issues going one step outside of the jenkins home directory.

Answer

Ok finally figured it out. What I did was change in the /etc/default/jenkins file the variable JENKINS_USER and JENKINS_GROUP to the user i needed to outside of the jenkins user folder (outside of /var/lib/jenkins).

This way the scripts ran by Jenkins will be ran as if it was the selected user I specified.

After that, I realized that in Jenkins, even if the working directory is /var/lib/jenkins/jobs/adjust_data_parser/workspace, scripts and files can be called from '/'

So the trick was:

-Accessing the script outside of the jenkins home directory

-Importing the module from its absolute path.