David Pelayo
David Pelayo

Reputation: 158

DSL Job in Jenkins and Github

I'm trying to fetch the forks of a certain repo in Github, the same of executing:

curl -k -X GET https://api.github.com/repos/rackt/redux/forks

But in a DSL script in Jenkins.

Why? Because I would like to clone all people's fork and build the project on separate jobs generated by job-dsl-plugin.

Of course this is just an example with a repo I found. I'm trying to do it with SSH credentials with private repos.

Do you know which would be the best way to do it?

Upvotes: 1

Views: 2476

Answers (2)

David Pelayo
David Pelayo

Reputation: 158

I've finally solved by doing this (see the Gist I published):

import groovy.json.JsonSlurper

def owner = "<owner>"
def project = "<project>"

// curl -k -u <user>:<token> -X GET https://api.github.com/repos/<owner>/<repo>/forks > forks.txt

def fetch(addr, params = [:]) {
  def auth = "<personalAPIToken>" // see https://github.com/blog/1509-personal-api-tokens
  def json = new JsonSlurper()
  return json.parse(addr.toURL().newReader(requestProperties: ["Authorization": "token ${auth}".toString(), "Accept": "application/json"]))
}

def forks = fetch("https://api.github.com/repos/${owner}/${project}/forks")

forks.each {
    def fork = it.full_name
    def name = it.owner.login
    def jobName = "${project}-${name}".replaceAll('/','-')
    job(jobName) {
        scm {
            git {
              remote {
                github(fork, 'https')
                credentials('<idCredentials>')
              }
            }
        }
    }
}

Thanks!

Upvotes: 0

KeepCalmAndCarryOn
KeepCalmAndCarryOn

Reputation: 9075

There is a real world example in the wiki which details how to create jobs for branches

def project = 'Netflix/asgard'
def branchApi = new URL("https://api.github.com/repos/${project}/branches")
def branches = new groovy.json.JsonSlurper().parse(branchApi.newReader())
branches.each {
    def branchName = it.name
    def jobName = "${project}-${branchName}".replaceAll('/','-')
    job(jobName) {
        scm {
            git("https://github.com/${project}.git", branchName)
        }
    }
}

What you will need to do is move the job section outside the each closure and use the fork name.

As for your comments about ssh and private repos. Its a good idea to keep your ssh key out of the script by using the Credentials plugin like the wiki says

The first option involves the Credentials Plugin which manages credentials in a secure manner and allows Job DSL scripts to reference credentials by their identifier. It is also the most secure option because the credentials do not need to passed to the Job DSL script.

// use the github-ci-key credentials for authentication with GitHub
job('example-1') {
    scm {
        git {
            remote {
                github('account/repo', 'ssh')
                credentials('github-ci-key')
            }
        }
    }
}

Upvotes: 4

Related Questions