def configure(self):
     #self.logger.info("setting jenkins authentication method to use unix userdata")
     #self.checkForSuccess(bash("cp %s/jenkis_auth_file /var/lib/jenkins"%currentDir))
     #self.logger.info("setting jenkins password")
     #self.logger.info("echo %s | sudo passwd jenkins --stdin"%self.jenkinsPasswd)
     #self.checkForSuccess(bash("service jenkins restart"))
     time.sleep(10)
     self.logger.info("checking if auth config is successful")
     j=Jenkins(self.jenkinsUrl, "admin", self.jenkinsPasswd)
     try:
        j.get_plugins()
     except Exception as e:
        self.logger.info("failed to retrive plugin info, may be auth problem")
        self.logger.exception(e) 
        raise e
     self.logger.info("auth config successful")
     self.logger.info("installing requried plugins")
     self.logger.info("reading from jenkins plugins file %s/jenkins_plugins.txt"%currentDir)
     f=open('%s/jenkins_plugins.txt'%currentDir, 'r')
     pluginsToInstall=f.read()  
     pluginsToInstall=pluginsToInstall.split('\n')
     self.installPlugins(j,pluginsToInstall)
     self.logger.info("Plugin installation complete")
     self.logger.info("restarting jenkins")
     self.restartJenkins()
     self.logger.info("Creating CI jobs on jenkins")
     for file in os.listdir(os.path.join(currentDir,'jenkins_job_templates')):
       try:
          if not j.job_exists(file):
             f=open(os.path.join(currentDir,'jenkins_job_templates',file),'r')
             config=f.read()
             f.close()
             self.logger.info("creating job %s, reading config from file %s"%(repr(file),os.path.join(currentDir,'jenkins_job_templates',file)))
             j.create_job(file, config)  
          else:
            self.logger.info("job %s already exists, not creating"%file)
       except Exception as e:
            self.logger.warn("failed to create job %s"%(file))
            self.logger.exception(e) 
     self.logger.info("created all CI jobs")
     self.logger.info("Adding driverVM as node in jenkins")
     params = {
              'port': '22',
              'username': '******',
              'credentialsId':'abe3f139-77bd-4db4-824b-1c79d5205d8b',
              'host':self.config['nodes']['driverVM']['ip'] 
     }
     self.addPasswdToCredential(j,"vagrant")
     self.checkForSuccess(bash("cp %s /var/lib/jenkins/."%(os.path.join(currentDir,"jenkins_credentials","credentials.xml"))))
     j.create_node('driverVM', numExecutors=20, nodeDescription="CI slave VM", remoteFS='/automation/jenkins', labels='driverVM', exclusive=True,launcher=jenkins.LAUNCHER_SSH, launcher_params=params) 
     self.logger.info("jenkins install complete")
 def restartJenkins(self):
     self.checkForSuccess(bash("service jenkins restart"))
     retry=20
     while retry > 0:
       retry-=1
       try:
           j=Jenkins(self.jenkinsUrl, "admin", self.jenkinsPasswd)
           j.get_plugins()
           break
       except Exception as e:
            if retry==0:
               self.logger.info("Failed to restart jenkins")  
            else:
               time.sleep(20)
               self.logger.info("waiting for jenkins to restart, this may take a while")
 def installPlugins(self, Jenkins, pluginsToInstall):
     plugins=Jenkins.get_plugins()
     currentPluginList=[]
     for k,v in plugins.keys():
         currentPluginList.append(k)
     installedPluginList=[]
     installedPluginList.append("startVal")
     while len(installedPluginList) > 0:      
          installedPluginList=[]
          for plugin in pluginsToInstall:
              if(len(plugin)==0):
                pass
              else:
                print "trying to install plugin %s"%plugin
                Jenkins.install_plugin(plugin,True)
          time.sleep(60)
          self.restartJenkins()
          plugins=Jenkins.get_plugins()
          for k,v in plugins.keys():
              if k not in currentPluginList:
                 installedPluginList.append(k)
                 currentPluginList.append(k)
          print "set diff", installedPluginList    
def get_plugins_dict(jenkins_url, puppet=False, user=None, password=None):
    if user is not None:
        logger.debug("Connecting to Jenkins (<%s>) as user %s ...",
                     jenkins_url, user)
        j = Jenkins(jenkins_url, user, password)
    else:
        logger.debug("Connecting to Jenkins (<%s>) anonymously...", jenkins_url)
        j = Jenkins(jenkins_url)
    logger.debug("Connected.")
    p = j.get_plugins()
    plugins = {}
    for k, v in p.items():
        plugins[k[0]] = v['version']
    return plugins
示例#5
0
def get_plugins_dict(jenkins_url, puppet=False, user=None, password=None):
    if user is not None:
        logger.debug("Connecting to Jenkins (<%s>) as user %s ...",
                     jenkins_url, user)
        j = Jenkins(jenkins_url, user, password)
    else:
        logger.debug("Connecting to Jenkins (<%s>) anonymously...",
                     jenkins_url)
        j = Jenkins(jenkins_url)
    logger.debug("Connected.")
    p = j.get_plugins()
    plugins = {}
    for k, v in p.items():
        plugins[k[0]] = v['version']
    return plugins
def main(jenkins_url, user=None, password=None):
    if user is not None:
        logger.debug("Connecting to Jenkins as user %s ...", user)
        j = Jenkins(jenkins_url, user, password)
    else:
        logger.debug("Connecting to Jenkins anonymously...")
        j = Jenkins(jenkins_url)
    logger.debug("Connected.")
    p = j.get_plugins()
    plugins = {}
    namelen = 0
    for k, v in p.items():
        plugins[k[0]] = v['version']
        if len(k[0]) > namelen:
            namelen = len(k[0])
    # format
    for name, ver in sorted(plugins.items()):
        print("  jenkins::plugin {'%s': version => '%s'}" % (name, ver))
def main(jenkins_url, user=None, password=None):
    if user is not None:
        logger.debug("Connecting to Jenkins as user %s ...", user)
        j = Jenkins(jenkins_url, user, password)
    else:
        logger.debug("Connecting to Jenkins anonymously...")
        j = Jenkins(jenkins_url)
    logger.debug("Connected.")
    p = j.get_plugins()
    plugins = {}
    namelen = 0
    for k, v in p.items():
        plugins[k[0]] = v['version']
        if len(k[0]) > namelen:
            namelen = len(k[0])
    # format
    for name, ver in sorted(plugins.items()):
        print("  jenkins::plugin {'%s': version => '%s'}" % (name, ver))
示例#8
0
def test_jenkins_plugins():
    master = Jenkins('http://127.0.0.1:8080')
    plugins = master.get_plugins()

    assert plugins['git']['active']
    assert plugins['git']['enabled']
示例#9
0
#!/usr/bin/env python

from jenkins import Jenkins
import sys

server = Jenkins(sys.argv[1])
for plugin in server.get_plugins().itervalues():
  print ("{name}:{version}".format(name=plugin['shortName'],
                                   version=plugin['version']))
示例#10
0
class JenkinsTools(object):
    """
    This is to expose the functional capability of jenkins for the various operations that it can perform programatically without having access to console.
    """

    _jenkins_url = None
    _login_id = None
    _password = None

    def __init__(self, jenkins_url, login_id, password):
        """
        Initialize the jenkins connection object
        :param jenkins_url:
        :param login_id:
        :param password:
        """
        self._jenkins_url = jenkins_url
        self._login_id = login_id
        self._password = password
        self.server_obj = Jenkins(jenkins_url, username=self._login_id, password=self._password)

    def get_jenkins_version(self):
        """
        To get the Jenkins version
        :return:
        """
        return self.server_obj.get_version()

    def get_job_details(self):
        """
        Get the jenkins job details.
        :return:
        """
        for job in self.server_obj.get_jobs():
            job_instance = self.server_obj.get_job(job[0])
            print 'Job Name:%s' % job_instance.name
            print 'Job Description:%s' %(job_instance.get_description())
            print 'Is Job running:%s' %(job_instance.is_running())
            print 'Is Job enabled:%s' %(job_instance.is_enabled())

    def get_job_count(self):
        """
        To get the count of jobs in Jenkins
        :return:
        """
        return self.server_obj.jobs_count()

    def disable_jenkins_job(self, job_name=None):
        """
        To  disable the jobs from jenkins.
        :return:
        """
        if self.server_obj.has_job(job_name):
            job_instance = self.server_obj.get_job(job_name)
            job_instance.disable()
            print 'Name:%s,Is Job Enabled ?:%s' % (job_name, job_instance.is_enabled())

    def get_jenkins_plugin_details(self):
        """
        To get the details of existing plugins in jenkins.
        :return:
        """
        for plugin in self.server_obj.get_plugins().values():
            print "Short Name:%s" % plugin.shortName
            print "Long Name:%s" % plugin.longName
            print "Version:%s" % plugin.version
            print "URL:%s" % plugin.url
            print "Active:%s" % plugin.active
            print "Enabled:%s" % plugin.enabled

    def get_plugin_details(self, plugin_name):
        """
        TO get the new plugin details
        :param plugin_name:
        :return:
        """
        plugins_metadata = self.server_obj.get_plugin_info(plugin_name)
        pprint(plugins_metadata)

    def getSCMInfroFromLatestGoodBuild(url, jobName, username=None, password=None):
        """
        To get the latest SCM from the latest good builds.
        :param url:
        :param jobName:
        :param username:
        :param password:
        :return:
        """
        J = Jenkins(url, username, password)
        job = J[jobName]
        lgb = job.get_last_good_build()
        return lgb.get_revision()
示例#11
0
#!/usr/bin/env python

from jenkins import Jenkins
import sys

server = Jenkins(sys.argv[1])
for plugin in server.get_plugins().itervalues():
    print("{name}:{version}".format(name=plugin['shortName'],
                                    version=plugin['version']))