Ejemplo n.º 1
0
def connectJenkins():
    startingUp = True
    js = None
    while startingUp:
        try:
            #            app.logger.debug('Connecting to Jenkins %s as %s', app.config["JENKINS_URL"], app.config["UID"])
            js = JenkinsServer(app.config["JENKINS_URL"],
                               username=app.config["UID"],
                               password=app.config["PWD"])
            if (js.wait_for_normal_op(30)):
                #                app.logger.debug('Connected')
                #                app.logger.info('Hello from Jenkins %s', js.get_version())
                startingUp = False
        except:
            app.logger.debug('%s caught during Jenkins connect',
                             sys.exc_info()[0])
            app.logger.debug('Waiting for startup, sleeping')
            time.sleep(5)
    return js
Ejemplo n.º 2
0
def main():
    module_args = {
        'api': {
            'type': 'str',
            'required': False
        },
        'wait_for': {
            'type':    'str',
            'required': False,
        },
    }

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )

    result = { 
        'changed' :False,
    }

    # format: <github-user>:<github-token>
    auth_file = path.join(Path.home(), ".jenkins/auth")
    with open(auth_file) as af:
        auth = [line.strip() for line in af if not line.strip().startswith("#")]
    github_user, github_token = auth[0].split(":")

    # jenkins server name
    instance = environ['INSTANCE']
    workspace = environ['WORKSPACE']
    domain = environ['DOMAIN']
    server_name = f'https://jenkins-{instance}.{workspace}.{domain}'

    server = Jenkins(server_name, username=github_user, password=github_token, timeout=10)

    if module.params['api']:
        info, _ = inspect_server(server, result)

        if module.params['api'] == "/quietDown":
            if info['quietingDown'] == True:
                module.exit_json(**result)  # Already quiesced
            if not module.check_mode:
                server.quiet_down()
            result['changed'] = True
            module.exit_json(**result)
    elif module.params['wait_for']:
        if module.params['wait_for'] == 'normal_operation':
            info = {}
            try:
                info, _ = inspect_server(server, result)
            except:
                pass

            if 'mode' in info and info['mode'] == "NORMAL":
                serverAPI = jenkinsapi.jenkins.Jenkins(server_name, username=github_user, password=github_token, timeout=10, useCrumb=True)
                if serverAPI.is_quieting_down:
                    serverAPI.cancel_quiet_down()
                    result['changed'] = True
                module.exit_json(**result)  # Already operating normally
            if server.wait_for_normal_op(NORMAL_TIMEOUT):
                result['changed'] = True
                module.exit_json(**result)  # Successfully waited
            else:  # Waiting failed
                module.fail_json(msg=f'Timeout waiting for server transition to NORMAL operation mode ({NORMAL_TIMEOUT}s)', **result)
        elif module.params['wait_for'] == 'running_jobs':
            info, _ = inspect_server(server, result)

            running_builds = server.get_running_builds()
            if len(running_builds) == 0:
                module.exit_json(**result)  # No jobs running
            else:
                result['changed'] = True
                if not module.check_mode:
                    _start = time()
                    while time() < _start + RUNNING_JOBS_TIMEOUT:
                        running_builds = server.get_running_builds()
                        if len(running_builds) == 0:
                            module.exit_json(**result)  # Successfully waited for running jobs to end
            # Jobs still running, fail
            module.fail_json(msg=f'Timeout waiting for running jobs to complete ({RUNNING_JOBS_TIMEOUT}s)', **result)
Ejemplo n.º 3
0
 def addJob():
     startingUp = True
     JS_URL = app.config["JENKINS_URL"]
     while startingUp:
         try:
             app.logger.debug('Connecting to Jenkins %s as %s', JS_URL,
                              app.config["UID"])
             js = JenkinsServer(JS_URL,
                                username=app.config["UID"],
                                password=app.config["PWD"])
             if (js.wait_for_normal_op(30)):
                 app.logger.debug('Connected')
                 app.logger.info('Hello from Jenkins %s', js.get_version())
                 startingUp = False
         except:
             app.logger.debug('%s caught during Jenkins connect',
                              sys.exc_info()[0])
             app.logger.debug('Waiting for startup, sleeping')
             time.sleep(5)
     try:
         app.logger.debug('Creating folder %s', app.config["FOLDER_NAME"])
         js.create_job(app.config["FOLDER_NAME"], jenkins.EMPTY_FOLDER_XML)
     except:
         app.logger.debug('%s caught during folder create.',
                          sys.exc_info()[0])
         pass
     if app.config["GIT_UID"] != "":
         cj = credentialXML()
         try:
             app.logger.debug('Credential check.')
             try:
                 app.logger.debug('Prophylactic delete of credential.')
                 js.delete_credential(app.config["GIT_UID"],
                                      app.config["FOLDER_NAME"])
             except:
                 pass
             app.logger.debug('Creating credential.')
             js.create_credential(app.config["FOLDER_NAME"], cj)
         except:
             app.logger.debug('%s caught during config', sys.exc_info()[0])
     else:
         app.logger.debug("Anonymous GIT access")
     app.logger.debug('Generating Job XML.')
     nj = jobXML()
     app.logger.debug('Creating job.')
     try:
         app.logger.debug('Does job exist?.')
         if js.job_exists(app.config["FOLDER_NAME"] + '/' +
                          app.config["PIPELINE_NAME"]):
             exists = True
             app.logger.debug('Yep!')
             #app.logger.debug('Reconfiguring job %s using [%s]', app.config["PIPELINE_NAME"], nj)
             js.reconfig_job(
                 app.config["FOLDER_NAME"] + '/' +
                 app.config["PIPELINE_NAME"], nj)
             exists = True
         else:
             app.logger.debug('Nope!')
             #app.logger.debug('Trying to create job %s using [%s].', app.config["PIPELINE_NAME"], nj)
             js.create_job(
                 app.config["FOLDER_NAME"] + '/' +
                 app.config["PIPELINE_NAME"], nj)
             app.logger.debug(
                 'Attempting initial build to allow Jenkinsfile based configuration.'
             )
             rid = js.build_job(app.config["FOLDER_NAME"] + '/' +
                                app.config["PIPELINE_NAME"])
             app.logger.debug('Started %d', rid)
         app.logger.debug('Initial build to set parameters (jobid=%d)',
                          JenkinsBuild('', ''))
     except:
         app.logger.debug('%s caught during job config', sys.exc_info()[0])