gojenkins

repository·master·Indexed 21 days ago

https://github.com/bndr/gojenkins

A developer-friendly Jenkins API client for Go designed to simplify interactions with Jenkins features including jobs, builds, nodes, users, and the build queue. The package includes the jenkinsctl CLI tool for managing Jenkins resources via commands such as create, delete, disable, enable, and get.

Tokens
26.8K
Snippets
108
Records
128
Agent score
75%

What's inside gojenkins

  1. Generate a Jenkins API Token

    master

    To use jenkinsctl, you must first generate an API token for your Jenkins user account:

    1. Log in to your Jenkins instance.
    2. Click your username in the upper-right corner.
    3. Select Configure from the left-side menu.
    4. Locate the API Token section and click the Add new Token button.
    5. Provide a name for the token.
    6. Important: Copy the token immediately after generation. You will not be able to view it again once you leave the page.
  2. Configure jenkinsctl

    master

    Create a configuration directory and a config.json file to store your Jenkins server details. The configuration file must contain the Server URL, your JenkinsUser username, and the Token you generated in Jenkins.

    $ mkdir -p ~/.config/jenkinsctl/
    $ pushd ~/.config/jenkinsctl/
        $ vi config.json 
        {
            "Server": "https://jenkins.mydomain.com",
            "JenkinsUser": "jenkins-operator",
            "Token": "1152e8e7a88f6c7ef605844b35t5y6i"
        }
    $ popd
  3. Understand the FingerPrint and FingerPrintResponse structures

    master

    The fingerprinting system uses two primary structures:

    1. FingerPrint: The main handle used by consumers. It contains a pointer to the Jenkins client, the Base URL path, the fingerprint Id, and the Raw response data.
    2. FingerPrintResponse: The data model representing the Jenkins API JSON response. Key fields include:
      • FileName: The name of the file.
      • Hash: The fingerprint hash.
      • Original: Contains Name (job name) and Number (build number) of the build that created the fingerprint.
      • Timestamp: Unix timestamp of the fingerprint.
      • Usage: A list of usage entries containing the name and byte Ranges (start/end) where the artifact was used.
  4. Download all artifacts for a build

    master

    Retrieve all artifacts associated with a specific build and save them to a local directory using a.SaveToDir(path).

    job, _ := jenkins.GetJob(ctx, "job")
    build, _ := job.GetBuild(ctx, 1)
    artifacts := build.GetArtifacts(ctx)
    
    for _, a := range artifacts {
      a.SaveToDir("/tmp")
    }
  5. Create views and add jobs

    master

    Create a new view (e.g., using gojenkins.LIST_VIEW) and add existing jobs to it.

    view, err := jenkins.CreateView(ctx, "test_view", gojenkins.LIST_VIEW)
    if err != nil {
      panic(err)
    }
    
    status, err := view.AddJob(ctx, "jobName")
    if status != nil {
      fmt.Println("Job has been added to view")
    }
  6. Get builds and check status for a specific job

    master

    You can retrieve all build IDs for a job and then fetch individual build data to check results (e.g., SUCCESS). Additionally, you can quickly retrieve the last successful, failed, or stable build using the job object.

    jobName := "someJob"
    builds, err := jenkins.GetAllBuildIds(ctx, jobName)
    if err != nil {
      panic(err)
    }
    
    for _, build := range builds {
      buildId := build.Number
      data, err := jenkins.GetBuild(ctx, jobName, buildId)
      if err != nil {
        panic(err)
      }
    
      if "SUCCESS" == data.GetResult(ctx) {
        fmt.Println("This build succeeded")
      }
    }
    
    // Get Last Successful/Failed/Stable Build for a Job
    job, err := jenkins.GetJob(ctx, "someJob")
    if err != nil {
      panic(err)
    }
    
    job.GetLastSuccessfulBuild(ctx)
    job.GetLastStableBuild(ctx)
  7. Manage users

    master

    The library allows creating and deleting users.

    • CreateUser requires username, password, fullname, and email.
    • user.Delete() deletes the specific user instance.
    • jenkins.DeleteUser("username") deletes a user by name.
    // Create user
    user, err := jenkins.CreateUser(ctx, "username", "password", "fullname", "user@email.com")
    if err != nil {
      log.Fatal(err)
    }
    
    // Delete User via user object
    err = user.Delete()
    if err != nil {
      log.Fatal(err)
    }
    
    // Delete user by name
    err = jenkins.DeleteUser("username")
    if err != nil {
      log.Fatal(err)
    }
  8. Build a job and wait for completion

    master

    To trigger a job and monitor its progress, retrieve the job object, invoke it, and then poll the resulting build until it is no longer running.

    job, err := jenkins.GetJob(ctx, "#jobname")
    if err != nil {
      panic(err)
    }
    
    // Trigger the job
    queueid, err := job.InvokeSimple(ctx, params)
    if err != nil {
      panic(err)
    }
    
    // Get the build from the queue ID
    build, err := jenkins.GetBuildFromQueueID(ctx, job, queueid)
    if err != nil {
      panic(err)
    }
    
    // Wait for build to finish
    for build.IsRunning(ctx) {
      time.Sleep(5000 * time.Millisecond)
      build.Poll(ctx)
    }
    
    fmt.Printf("build number %d with result: %v\n", build.GetBuildNumber(), build.GetResult())