1

I'm trying to calling Jenkins API from bare groovy script ( in local environment ) instead of https://jenkins.domain.com/script.

Now I can successful import Jenkins libs as below:

@GrabResolver(name='jenkins', root='https://repo.jenkins-ci.org/releases')
@Grab(group='org.jenkins-ci.main', module='jenkins-core', version='2.377')
@Grab(group='org.jenkins-ci.plugins.workflow', module='workflow-api', version='1200.v8005c684b_a_c6')
@Grab(group='org.jenkins-ci.plugins.workflow', module='workflow-job', version='1254.v3f64639b_11dd')
@Grab(group='org.jenkins-ci.plugins.workflow', module='workflow-step-api', version='639.v6eca_cd8c04a_a_')

import jenkins.model.Jenkins
import hudson.Util
import hudson.model.Job
import org.jenkinsci.plugins.workflow.job.WorkflowJob

String rootUrl  = 'https://my.jenkins.com'
String username = 'admin'
String password = 'admin'

// .. how to new a Jenkins instance here ..
// i.e.: Jenkins jenkins = new Jenkins.instance( url, username, password )

// list all workflowjobs
Jenkins.instance.getAllItems( WorkflowJob.class ).collect { it.fullName }

I'd like to know how I can new a jenkins instance by using url similar to run jenkins.model.Jenkins.instance.xxx


btw, I've tried the java-client-api as below, however it cannot identify AbstractItem.class, WorkflowJob.class, etc... is there any solution to "convert" com.offbytwo.jenkins.JenkinsServer to jenkins.model.Jenkins ?

@GrabResolver(name='jenkins', root='https://repo.jenkins-ci.org/releases')
@Grab(group='org.jenkins-ci.main', module='jenkins-core', version='2.377')
@Grab(group='com.offbytwo.jenkins', module='jenkins-client', version='0.3.8')

import com.offbytwo.jenkins.JenkinsServer

String rootUrl  = 'https://my.jenkins.com'
String username = 'admin'
String password = 'admin'

JenkinsServer jenkins = new JenkinsServer( new URI(rootUrl), username, password )
jenkins.getJobs()
Marslo
  • 2,994
  • 4
  • 26
  • 35

1 Answers1

0

the solution is kinda off topic. however it indeed execute the groovy script locally.

  • by using api

    $ SERVER='localhost'
    $ COOKIEJAR="$(mktemp)"
    # get crumb issue
    $ CRUMB=$(curl -u "admin:admin" \
                   --cookie-jar "${COOKIEJAR}" \
                   "https://${SERVER}/crumbIssuer/api/json" |
                   jq -r '[.crumbRequestField, .crumb] | join(":")'
             )
    
    # execute /path/to/script.groovy
    $ curl -u "admin:admin" \
           --cookie "${COOKIEJAR}" \
           -H "${CRUMB}" \
           -d "script=$(< /path/to/script.groovy)" \
           https://${SERVER}/scriptText
    
  • by using cli

    • after setup the environment
    • execute /path/to/script.groovy:
      $ ssh -l <username> -p <port> -i <identityFile> ${SERVER} groovy =< ./path/to/script.groovy
      
    • if setup ~/.ssh/config, it will be simpler as:
      $ ssh ${SERVER} groovy =< /path/to/script.groovy
      
    • i.e.: enter image description here
Marslo
  • 2,994
  • 4
  • 26
  • 35