### Install gojenkins Client Source: https://github.com/bndr/gojenkins/blob/master/README.md Use 'go get' to install the gojenkins library. ```bash go get github.com/bndr/gojenkins ``` -------------------------------- ### Manage Jenkins Plugins Source: https://context7.com/bndr/gojenkins/llms.txt List installed plugins, check for specific plugins, and install or uninstall plugins. Ensure the plugin names and versions are correct. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Get all plugins (depth=1) plugins, err := jenkins.GetPlugins(ctx, 1) if err != nil { panic(err) } fmt.Printf("Installed plugins: %d\n", plugins.Count()) // Check if a plugin is installed gitPlugin, err := jenkins.HasPlugin(ctx, "git") if err != nil { panic(err) } if gitPlugin != nil { fmt.Printf("Git plugin v%s (enabled=%v, hasUpdate=%v)\n", gitPlugin.Version, gitPlugin.Enabled, gitPlugin.HasUpdate) } // Install a plugin if err := jenkins.InstallPlugin(ctx, "pipeline-utility-steps", "latest"); err != nil { fmt.Println("Install error:", err) } // Uninstall a plugin if err := jenkins.UninstallPlugin(ctx, "old-plugin"); err != nil { fmt.Println("Uninstall error:", err) } ``` -------------------------------- ### Manage Jenkins Views Source: https://context7.com/bndr/gojenkins/llms.txt This example shows how to create, populate, and delete Jenkins views. It covers creating a list view, adding and removing jobs from it, listing all available views, and finally deleting the view. Use the provided constants for view types. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a list view view, err := jenkins.CreateView(ctx, "Production", gojenkins.LIST_VIEW) if err != nil { panic(err) } // Add jobs to the view view.AddJob(ctx, "deploy-frontend") view.AddJob(ctx, "deploy-backend") fmt.Printf("View %q has %d jobs\n", view.GetName(), len(view.GetJobs())) // List all views allViews, _ := jenkins.GetAllViews(ctx) for _, v := range allViews { fmt.Printf(" - %s (%s)\n", v.GetName(), v.GetUrl()) } // Remove job from view view.DeleteJob(ctx, "deploy-frontend") // Delete view jenkins.DeleteView(ctx, "Production") ``` -------------------------------- ### Create Nested Folders and Jobs in Jenkins Source: https://context7.com/bndr/gojenkins/llms.txt This example demonstrates creating parent and child folders, then creating a job within the nested folder structure. It also shows how to retrieve a job from a specific folder path. Error handling is crucial for folder and job creation. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a parent folder parent, err := jenkins.CreateFolder(ctx, "team-alpha") if err != nil { panic(err) } fmt.Println("Parent folder:", parent.GetName()) // Create a nested child folder child, err := jenkins.CreateFolder(ctx, "backend", parent.GetName()) if err != nil { panic(err) } // Create a job inside the nested folder jobXML := `` job, err := jenkins.CreateJobInFolder(ctx, jobXML, "api-deploy", parent.GetName(), child.GetName()) if err != nil { panic(err) } fmt.Println("Job in folder:", job.GetName()) // Retrieve nested job nestedJob, err := jenkins.GetJob(ctx, "api-deploy", parent.GetName(), child.GetName()) if err != nil { panic(err) } fmt.Println("Retrieved:", nestedJob.GetDetails().FullDisplayName) // Get folder folder, _ := jenkins.GetFolder(ctx, "backend", "team-alpha") fmt.Println("Folder jobs:", len(folder.Raw.Jobs)) ``` -------------------------------- ### Get and Check Status of Job Builds Source: https://github.com/bndr/gojenkins/blob/master/README.md Fetches all build IDs for a given job, retrieves detailed build data, and checks if the build result is 'SUCCESS'. Also shows how to get the last successful/stable build. ```go 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) ``` -------------------------------- ### Initialize Jenkins Client Source: https://context7.com/bndr/gojenkins/llms.txt Constructs a Jenkins client instance and initializes it by verifying connectivity and populating server metadata. An optional custom HTTP client can be provided, for example, to skip TLS verification. Basic auth credentials are provided as variadic arguments. ```go package main import ( "context" "crypto/tls" "fmt" "net/http" "github.com/bndr/gojenkins" ) func main() { ctx := context.Background() // Default HTTP client, with basic auth jenkins, err := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "s3cr3t").Init(ctx) if err != nil { panic(err) } fmt.Println("Connected to Jenkins", jenkins.Version) // Custom HTTP client (skip TLS verification for self-signed certs) tlsClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } jenkins2, err := gojenkins.CreateJenkins(tlsClient, "https://jenkins.internal/", "admin", "token").Init(ctx) if err != nil { panic(err) } fmt.Println("Server version:", jenkins2.Version) } ``` -------------------------------- ### Plugin Management Source: https://context7.com/bndr/gojenkins/llms.txt List, check, install, and uninstall Jenkins plugins. This section covers retrieving all plugins, checking for a specific plugin's existence and details, installing new plugins, and uninstalling existing ones. ```APIDOC ## Plugin Management List, check, install, and uninstall Jenkins plugins. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Get all plugins (depth=1) plugins, err := jenkins.GetPlugins(ctx, 1) if err != nil { panic(err) } fmt.Printf("Installed plugins: %d\n", plugins.Count()) // Check if a plugin is installed gitPlugin, err := jenkins.HasPlugin(ctx, "git") if err != nil { panic(err) } if gitPlugin != nil { fmt.Printf("Git plugin v%s (enabled=%v, hasUpdate=%v)\n", gitPlugin.Version, gitPlugin.Enabled, gitPlugin.HasUpdate) } // Install a plugin if err := jenkins.InstallPlugin(ctx, "pipeline-utility-steps", "latest"); err != nil { fmt.Println("Install error:", err) } // Uninstall a plugin if err := jenkins.UninstallPlugin(ctx, "old-plugin"); err != nil { fmt.Println("Uninstall error:", err) } ``` ``` -------------------------------- ### Job Management: Enable, Disable, Config, Parameters Source: https://context7.com/bndr/gojenkins/llms.txt Demonstrates how to enable, disable, check the status, retrieve the XML configuration, and get parameter definitions for a Jenkins job. ```APIDOC ## Job Management ### Description Manage the state and configuration of Jenkins jobs. ### Methods - **Disable(ctx context.Context)**: Disables a job. - **Enable(ctx context.Context)**: Enables a job. - **IsEnabled(ctx context.Context)**: Checks if a job is enabled. - **IsQueued(ctx context.Context)**: Checks if a job is queued. - **IsRunning(ctx context.Context)**: Checks if a job is currently running. - **GetConfig(ctx context.Context)**: Retrieves the XML configuration of a job. - **GetParameters(ctx context.Context)**: Retrieves the parameter definitions for a parameterized job. ### Example Usage ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) job, _ := jenkins.GetJob(ctx, "nightly-tests") // Disable and re-enable job.Disable(ctx) fmt.Println("Enabled:", func() bool { ok, _ := job.IsEnabled(ctx); return ok }()) job.Enable(ctx) // Check states queued, _ := job.IsQueued(ctx) running, _ := job.IsRunning(ctx) fmt.Printf("queued=%v running=%v\n", queued, running) // Get XML config xmlConfig, _ := job.GetConfig(ctx) fmt.Println("Config length:", len(xmlConfig)) // Get parameter definitions params, _ := job.GetParameters(ctx) for _, p := range params { fmt.Printf(" Param %q (type %s), default: %v\n", p.Name, p.Type, p.DefaultParameterValue.Value) } ``` ``` -------------------------------- ### Folder Management: Create, Get Source: https://context7.com/bndr/gojenkins/llms.txt Enables the creation of nested folder hierarchies and retrieval of jobs within these folders. ```APIDOC ## Folder Management ### Description Create and manage nested folders in Jenkins, and create jobs within them. ### Methods - **CreateFolder(ctx context.Context, folderName string, parentFolder ...string)**: Creates a new folder. Can be nested by providing parent folder names. - **CreateJobInFolder(ctx context.Context, jobXML string, jobName string, folderNames ...string)**: Creates a new job within a specified folder or nested folders. - **GetFolder(ctx context.Context, folderNames ...string)**: Retrieves a folder by its name or path. - **GetJob(ctx context.Context, jobName string, folderNames ...string)**: Retrieves a job by its name or path within folders. ### Example Usage ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a parent folder parent, err := jenkins.CreateFolder(ctx, "team-alpha") if err != nil { panic(err) } fmt.Println("Parent folder:", parent.GetName()) // Create a nested child folder child, err := jenkins.CreateFolder(ctx, "backend", parent.GetName()) if err != nil { panic(err) } // Create a job inside the nested folder jobXML := `` job, err := jenkins.CreateJobInFolder(ctx, jobXML, "api-deploy", parent.GetName(), child.GetName()) if err != nil { panic(err) } fmt.Println("Job in folder:", job.GetName()) // Retrieve nested job nestedJob, err := jenkins.GetJob(ctx, "api-deploy", parent.GetName(), child.GetName()) if err != nil { panic(err) } fmt.Println("Retrieved:", nestedJob.GetDetails().FullDisplayName) // Get folder folder, _ := jenkins.GetFolder(ctx, "backend", "team-alpha") fmt.Println("Folder jobs:", len(folder.Raw.Jobs)) ``` ``` -------------------------------- ### Get All Artifacts for a Build and Save in Go Source: https://github.com/bndr/gojenkins/blob/master/README.md Retrieves all artifacts for a specific build of a job and saves them to a specified directory. Ensure the job and build exist and the directory is writable. ```go job, _ := jenkins.GetJob(ctx, "job") build, _ := job.GetBuild(ctx, 1) artifacts := build.GetArtifacts(ctx) for _, a := range artifacts { a.SaveToDir("/tmp") } ``` -------------------------------- ### Queue Management Source: https://context7.com/bndr/gojenkins/llms.txt Inspect the build queue and cancel waiting tasks. You can also retrieve tasks for a specific job or get a queue item directly. ```APIDOC ## Queue Management Inspect the build queue and cancel waiting tasks. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) queue, err := jenkins.GetQueue(ctx) if err != nil { panic(err) } for _, task := range queue.Tasks() { fmt.Printf("Task %d (%s): %s\n", task.Raw.ID, task.Raw.Task.Name, task.GetWhy()) for _, p := range task.GetParameters() { fmt.Printf(" param %s=%v\n", p.Name, p.Value) } } // Cancel a specific task by ID queue.CancelTask(ctx, 17) // Get tasks for a specific job pendingTasks := queue.GetTasksForJob("my-pipeline") fmt.Printf("%d tasks pending for my-pipeline\n", len(pendingTasks)) // Get a queue item directly (e.g., after triggering a build) queueID, _ := jenkins.BuildJob(ctx, "slow-job", nil) task, _ := jenkins.GetQueueItem(ctx, queueID) fmt.Println("Why waiting:", task.GetWhy()) ``` ``` -------------------------------- ### Trace Upstream and Downstream Builds Source: https://context7.com/bndr/gojenkins/llms.txt Navigates the build dependency chain by retrieving the upstream build that triggered a given build and listing all downstream builds. It also shows how to get downstream job names via fingerprints. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) build, _ := jenkins.GetBuild(ctx, "integration-tests", 88) // Get the upstream build that triggered this one upstreamBuild, err := build.GetUpstreamBuild(ctx) if err == nil { fmt.Printf("Triggered by: %s #%d\n", upstreamBuild.Job.GetName(), upstreamBuild.GetBuildNumber()) } // Get all downstream builds triggered by this build downstreams, _ := build.GetDownstreamBuilds(ctx) for _, ds := range downstreams { fmt.Printf("Downstream: %s #%d result=%s\n", ds.Job.GetName(), ds.GetBuildNumber(), ds.GetResult()) } // List downstream job names via fingerprints names := build.GetDownstreamJobNames(ctx) fmt.Println("Downstream jobs:", names) ``` -------------------------------- ### Get Current Tasks in Jenkins Queue Source: https://github.com/bndr/gojenkins/blob/master/README.md Retrieves the current tasks in the Jenkins queue and prints the reason why each task is waiting. ```go tasks := jenkins.GetQueue(ctx) for _, task := range tasks { fmt.Println(task.GetWhy(ctx)) } ``` -------------------------------- ### Get Build from Queue ID Source: https://context7.com/bndr/gojenkins/llms.txt Waits for a queued Jenkins item to be assigned a build number and returns the corresponding `*Build` object. This function polls periodically, accounting for Jenkins' quiet period. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) job, _ := jenkins.GetJob(ctx, "my-pipeline") queueID, _ := job.InvokeSimple(ctx, nil) build, err := jenkins.GetBuildFromQueueID(ctx, job, queueID) if err != nil { panic(err) } fmt.Printf("Build #%d started on %s\n", build.GetBuildNumber(), build.GetTimestamp()) ``` -------------------------------- ### Create Nested Folders and Jobs in Go Source: https://github.com/bndr/gojenkins/blob/master/README.md Demonstrates creating a parent folder, a child folder within the parent, and then a job inside the child folder. Ensure the Jenkins client and context are properly initialized. ```go // Create parent folder pFolder, err := jenkins.CreateFolder(ctx, "parentFolder") if err != nil { panic(err) } // Create child folder in parent folder cFolder, err := jenkins.CreateFolder(ctx, "childFolder", pFolder.GetName()) if err != nil { panic(err) } // Create job in child folder configString := ` false true false false false false ` job, err := jenkins.CreateJobInFolder(ctx, configString, "jobInFolder", pFolder.GetName(), cFolder.GetName()) if err != nil { panic(err) } if job != nil { fmt.Println("Job has been created in child folder") } ``` -------------------------------- ### Initialize Jenkins Client and Interact with Jobs Source: https://github.com/bndr/gojenkins/blob/master/README.md Initializes a Jenkins client, retrieves a job, and triggers a build. It then polls for build completion and prints the result. Requires context, Jenkins URL, username, and password. ```go import ( "github.com/bndr/gojenkins" "context" "time" "fmt" ) ctx := context.Background() jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin") // Provide CA certificate if server is using self-signed certificate // caCert, _ := ioutil.ReadFile("/tmp/ca.crt") // jenkins.Requester.CACert = caCert _, err := jenkins.Init(ctx) if err != nil { panic("Something Went Wrong") } job, err := jenkins.GetJob(ctx, "#jobname") if err != nil { panic(err) } queueid, err := job.InvokeSimple(ctx, params) // or jenkins.BuildJob(ctx, "#jobname", params) if err != nil { panic(err) } 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()) ``` -------------------------------- ### Create Jenkins View and Add Jobs Source: https://github.com/bndr/gojenkins/blob/master/README.md Demonstrates creating a new view in Jenkins and adding a specified job to it. Handles potential errors during creation and addition. ```go 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") } ``` -------------------------------- ### Build and Run CLI Source: https://github.com/bndr/gojenkins/blob/master/README.md Navigate to the cli/jenkinsctl directory and run 'make' to build the CLI tool. ```bash cd cli/jenkinsctl make ``` -------------------------------- ### CreateJenkins and Init Source: https://context7.com/bndr/gojenkins/llms.txt Constructs a Jenkins client instance and initializes it by verifying connectivity and populating server metadata. An optional http.Client can be supplied for custom configurations like TLS settings. Basic auth credentials can also be provided. ```APIDOC ## CreateJenkins / Init `CreateJenkins` constructs a Jenkins client instance; calling `Init` verifies connectivity, populates server metadata, and returns the ready-to-use `*Jenkins`. An optional `*http.Client` can be supplied (e.g., for custom TLS). Basic auth credentials are the second and third variadic arguments. ```go package main import ( "context" "crypto/tls" "fmt" "net/http" "github.com/bndr/gojenkins" ) func main() { ctx := context.Background() // Default HTTP client, with basic auth jenkins, err := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "s3cr3t").Init(ctx) if err != nil { panic(err) } fmt.Println("Connected to Jenkins", jenkins.Version) // Custom HTTP client (skip TLS verification for self-signed certs) tlsClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } jenkins2, err := gojenkins.CreateJenkins(tlsClient, "https://jenkins.internal/", "admin", "token").Init(ctx) if err != nil { panic(err) } fmt.Println("Server version:", jenkins2.Version) } ``` ``` -------------------------------- ### Generate and Revoke API Tokens Source: https://context7.com/bndr/gojenkins/llms.txt Demonstrates how to generate a new API token, switch the client to use it, and revoke specific or all tokens. Ensure proper error handling for production use. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Generate a new token token, err := jenkins.GenerateAPIToken(ctx, "ci-pipeline-token") if err != nil { panic(err) } fmt.Printf("Token: name=%s value=%s\n", token.Name, token.Value) // Switch the client to use the new token jenkins.Requester.(*gojenkins.Requester).BasicAuth.Password = token.Value // Revoke the specific token via its UUID if err := jenkins.RevokeAPIToken(ctx, token.UUID); err != nil { fmt.Println("Revoke error:", err) } // Or revoke via the token object itself token2, _ := jenkins.GenerateAPIToken(ctx, "temp-token") token2.Revoke() // Revoke ALL tokens for the current user if err := jenkins.RevokeAllAPITokens(ctx); err != nil { fmt.Println("Error:", err) } ``` -------------------------------- ### Manage Jenkins Job States and Configuration Source: https://context7.com/bndr/gojenkins/llms.txt Use this snippet to enable, disable, check the status (queued, running), retrieve XML configuration, and list parameters for a Jenkins job. Ensure the Jenkins client is initialized. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) job, _ := jenkins.GetJob(ctx, "nightly-tests") // Disable and re-enable job.Disable(ctx) fmt.Println("Enabled:", func() bool { ok, _ := job.IsEnabled(ctx); return ok }()) // Output: Enabled: false job.Enable(ctx) // Check states queued, _ := job.IsQueued(ctx) running, _ := job.IsRunning(ctx) fmt.Printf("queued=%v running=%v\n", queued, running) // Get XML config xmlConfig, _ := job.GetConfig(ctx) fmt.Println("Config length:", len(xmlConfig)) // Get parameter definitions for a parameterized job params, _ := job.GetParameters(ctx) for _, p := range params { fmt.Printf(" Param %q (type %s), default: %v\n", p.Name, p.Type, p.DefaultParameterValue.Value) } ``` -------------------------------- ### Create Jenkins Client with Custom HTTP Client Source: https://github.com/bndr/gojenkins/blob/master/README.md Initializes a Jenkins client using a custom http.Client, allowing for custom configurations like SSL settings. ```go client := &http.Client{ ... } jenkins, := gojenkins.CreateJenkins(client, "http://localhost:8080/").Init(ctx) ``` -------------------------------- ### Create jenkinsctl Configuration Directory and File Source: https://github.com/bndr/gojenkins/blob/master/cli/jenkinsctl/README.md Create the configuration directory and the config.json file. This file stores your Jenkins server URL, username, and API token. ```bash $ mkdir -p ~/.config/jenkinsctl/ $ pushd ~/.config/jenkinsctl/ $ vi config.json { "Server": "https://jenkins.mydomain.com", "JenkinsUser": "jenkins-operator", "Token": "1152e8e7a88f6c7ef605844b35t5y6i" } $ popd ``` -------------------------------- ### Manage Jenkins Jobs (Create, Update, Rename, Copy, Delete) Source: https://context7.com/bndr/gojenkins/llms.txt Provides functions for full lifecycle management of Jenkins jobs using XML configuration strings. This includes creating new jobs, updating existing ones, renaming, copying, and deleting jobs. Ensure the Jenkins client is initialized and valid XML configurations are provided. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) configXML := ` Created by gojenkins false true false ` // Create job, err := jenkins.CreateJob(ctx, configXML, "my-new-job") if err != nil { panic(err) } fmt.Println("Created:", job.GetName()) // Update config updatedXML := `Updated` jenkins.UpdateJob(ctx, "my-new-job", updatedXML) // Rename jenkins.RenameJob(ctx, "my-new-job", "my-renamed-job") // Copy copiedJob, err := jenkins.CopyJob(ctx, "my-renamed-job", "my-copied-job") if err != nil { panic(err) } fmt.Println("Copied:", copiedJob.GetName()) // Delete ok, err := jenkins.DeleteJob(ctx, "my-copied-job") fmt.Printf("Deleted: %v, err: %v\n", ok, err) ``` -------------------------------- ### Jenkinsctl CLI Usage Source: https://github.com/bndr/gojenkins/blob/master/cli/jenkinsctl/README.md Display the help information for the jenkinsctl CLI, showing available commands and flags. ```bash $ ./jenkinsctl Client for jenkins, manage resources by the jenkins Usage: jenkinsctl [command] Available Commands: create Create a resource in Jenkins delete Delete a resource from Jenkins disable Disable a resource in Jenkins download download related commands enable Enable a resource in Jenkins get Get a resource from Jenkins help Help about any command plugins Commands related to plugins Flags: --config string Path to config file -h, --help help for jenkinsctl -v, --version version for jenkinsctl Use "jenkinsctl [command] --help" for more information about a command. ``` -------------------------------- ### Create Jenkins Client with Default Authentication Source: https://github.com/bndr/gojenkins/blob/master/README.md Creates a Jenkins client without explicit authentication, useful for public Jenkins instances or when authentication is handled elsewhere. ```go import "github.com/bndr/gojenkins" jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/").Init(ctx) ``` -------------------------------- ### Build jenkinsctl CLI Source: https://github.com/bndr/gojenkins/blob/master/cli/jenkinsctl/README.md Clone the jenkinsctl repository and build the executable using make. ```bash $ git clone https://github.com/dougsland/jenkinsctl.git $ cd jenkinsctl $ make ``` -------------------------------- ### Retrieve Jenkins Server Information Source: https://context7.com/bndr/gojenkins/llms.txt Fetches general server information, including the list of top-level jobs and views, and updates the cached Jenkins version. Ensure the Jenkins client is initialized before calling this method. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) info, err := jenkins.Info(ctx) if err != nil { panic(err) } fmt.Printf("Jenkins %s has %d top-level jobs\n", jenkins.Version, len(info.Jobs)) // Output: Jenkins 2.440 has 12 top-level jobs ``` -------------------------------- ### Manage Jenkins Users Source: https://context7.com/bndr/gojenkins/llms.txt Create new Jenkins user accounts and delete existing ones. Ensure proper user details are provided for creation and that deletion is handled correctly. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a new user user, err := jenkins.CreateUser(ctx, "jdoe", "P@ssw0rd!", "John Doe", "jdoe@example.com") if err != nil { panic(err) } fmt.Printf("Created user: %s (%s)\n", user.UserName, user.FullName) // Delete via user object if err := user.Delete(); err != nil { panic(err) } // Delete by username directly if err := jenkins.DeleteUser(ctx, "another-user"); err != nil { fmt.Println("Delete error:", err) } ``` -------------------------------- ### Job — Build History Queries Source: https://context7.com/bndr/gojenkins/llms.txt Convenience methods to retrieve the last build by status: successful, stable, failed, or completed, and to query specific build fields. ```APIDOC ## Job — Build History Queries Convenience methods to retrieve the last build by status: successful, stable, failed, or completed. ### Methods - `GetLastSuccessfulBuild(ctx context.Context) (*Build, error)` - `GetLastFailedBuild(ctx context.Context) (*Build, error)` - `GetLastStableBuild(ctx context.Context) (*Build, error)` - `GetFirstBuild(ctx context.Context) (*Build, error)` - `GetBuildsFields(ctx context.Context, fields []string, dest interface{}) error` ### Description These methods provide quick access to specific builds in a job's history, such as the last successful, failed, or stable build. Additionally, `GetBuildsFields` allows for fetching specific fields from multiple builds in the history, which can be useful for analyzing build trends. ``` -------------------------------- ### Inspect Pipeline Runs and Stages Source: https://context7.com/bndr/gojenkins/llms.txt Fetches all pipeline runs for a job, iterates through their stages, and retrieves details for a specific run, including pending input actions and artifacts. Log retrieval for a stage node is also shown. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) job, _ := jenkins.GetJob(ctx, "my-pipeline") // Get all pipeline runs runs, err := job.GetPipelineRuns(ctx) if err != nil { panic(err) } for _, run := range runs { fmt.Printf("Run %s: status=%s duration=%dms\n", run.ID, run.Status, run.Duration) for _, stage := range run.Stages { fmt.Printf(" Stage %q: %s\n", stage.Name, stage.Status) } } // Get a specific run and inspect pending input run, _ := job.GetPipelineRun(ctx, "42") actions, _ := run.GetPendingInputActions(ctx) if len(actions) > 0 { fmt.Println("Waiting for input:", actions[0].Message) // Approve run.ProceedInput(ctx) // Or abort // run.AbortInput(ctx) } // Get pipeline artifacts artifacts, _ := run.GetArtifacts(ctx) for _, a := range artifacts { fmt.Printf("Artifact: %s (%d bytes)\n", a.Name, a.Size) } // Get log for a specific stage node node, _ := run.GetNode(ctx, run.Stages[0].ID) log, _ := node.GetLog(ctx) fmt.Printf("Stage log (%d bytes): %s\n", log.Length, log.Text) ``` -------------------------------- ### Build Operations Source: https://context7.com/bndr/gojenkins/llms.txt Provides comprehensive access to build data including status, console output, test results, artifacts, and SCM information. ```APIDOC ## Build — Status, Console, Results, Artifacts Rich access to build data: status checks, console streaming, test results, artifacts, SCM revision, and upstream/downstream tracing. ### Methods - `IsRunning(ctx context.Context) bool` - `Poll(ctx context.Context) error` - `GetResult() string` - `GetBuildNumber() int64` - `GetTimestamp() time.Time` - `GetConsoleOutput(ctx context.Context) (string, error)` - `GetConsoleOutputFromIndex(ctx context.Context, offset int64) (*ConsoleOutputResponse, error)` - `GetResultSet(ctx context.Context) (*ResultSet, error)` - `GetParameters() []Parameter` - `GetArtifacts() []Artifact` - `GetRevision() string` - `GetDuration() float64` ### Description These methods allow for detailed inspection and interaction with a specific build. You can check if a build is still running, poll for its latest status, retrieve its result, number, and timestamp, access its console output (either fully or paginated), get test results, view parameters used, download artifacts, and retrieve SCM revision information. ``` -------------------------------- ### Manage Jenkins Build Queue Source: https://context7.com/bndr/gojenkins/llms.txt Inspect the build queue, cancel waiting tasks, and retrieve tasks for a specific job. Use this to monitor and control build processes. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) queue, err := jenkins.GetQueue(ctx) if err != nil { panic(err) } for _, task := range queue.Tasks() { fmt.Printf("Task %d (%s): %s\n", task.Raw.ID, task.Raw.Task.Name, task.GetWhy()) for _, p := range task.GetParameters() { fmt.Printf(" param %s=%v\n", p.Name, p.Value) } } // Cancel a specific task by ID queue.CancelTask(ctx, 17) // Get tasks for a specific job pendingTasks := queue.GetTasksForJob("my-pipeline") fmt.Printf("%d tasks pending for my-pipeline\n", len(pendingTasks)) // Get a queue item directly (e.g., after triggering a build) queueID, _ := jenkins.BuildJob(ctx, "slow-job", nil) task, _ := jenkins.GetQueueItem(ctx, queueID) fmt.Println("Why waiting:", task.GetWhy()) ``` -------------------------------- ### Manage Jenkins Nodes (Agents) Source: https://context7.com/bndr/gojenkins/llms.txt This code manages Jenkins build agents, including creating JNLP and SSH nodes, listing all nodes with their status (online, idle), taking nodes offline, bringing them back online, and deleting nodes. Ensure correct parameters for SSH launcher. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a JNLP node node, err := jenkins.CreateNode(ctx, "worker-01", 2, "Build worker", "/home/jenkins", "linux docker") if err != nil { panic(err) } fmt.Println("Created node:", node.GetName()) // Create an SSH node sshNode, err := jenkins.CreateNode(ctx, "ssh-worker", 4, "SSH worker", "/opt/jenkins", "linux", map[string]string{ "method": "SSHLauncher", "host": "192.168.1.50", "port": "22", "credentialsId": "ssh-key-credential", }) if err != nil { panic(err) } fmt.Println("SSH node:", sshNode.GetName()) // List all nodes and check status nodes, _ := jenkins.GetAllNodes(ctx) for _, n := range nodes { n.Poll(ctx) online, _ := n.IsOnline(ctx) idle, _ := n.IsIdle(ctx) fmt.Printf("Node %s: online=%v idle=%v\n", n.GetName(), online, idle) } // Take a node offline specificNode, _ := jenkins.GetNode(ctx, "worker-01") specificNode.SetOffline(ctx, "maintenance window") // Bring back online specificNode.SetOnline(ctx) // Delete node jenkins.DeleteNode(ctx, "worker-01") ``` -------------------------------- ### Jenkins.CreateJob / UpdateJob / RenameJob / CopyJob / DeleteJob Source: https://context7.com/bndr/gojenkins/llms.txt Provides full lifecycle management for Jenkins jobs (freestyle/pipeline) using XML configuration strings. This includes creating, updating, renaming, copying, and deleting jobs. ```APIDOC ## Jenkins.CreateJob / UpdateJob / RenameJob / CopyJob / DeleteJob Full lifecycle management for Jenkins freestyle/pipeline jobs using XML configuration strings. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) configXML := ` Created by gojenkins false true false ` // Create job, err := jenkins.CreateJob(ctx, configXML, "my-new-job") if err != nil { panic(err) } fmt.Println("Created:", job.GetName()) // Update config updatedXML := `Updated` jenkins.UpdateJob(ctx, "my-new-job", updatedXML) // Rename jenkins.RenameJob(ctx, "my-new-job", "my-renamed-job") // Copy copiedJob, err := jenkins.CopyJob(ctx, "my-renamed-job", "my-copied-job") if err != nil { panic(err) } fmt.Println("Copied:", copiedJob.GetName()) // Delete ok, err := jenkins.DeleteJob(ctx, "my-copied-job") fmt.Printf("Deleted: %v, err: %v\n", ok, err) ``` ``` -------------------------------- ### Create and Delete Users in Go Source: https://github.com/bndr/gojenkins/blob/master/README.md Manages Jenkins users by creating new users with credentials or deleting existing ones. The `DeleteUser` function can be used to remove users not created via the gojenkins library. ```go // Create user user, err := jenkins.CreateUser(ctx, "username", "password", "fullname", "user@email.com") if err != nil { log.Fatal(err) } // Delete User er r = user.Delete() if err != nil { log.Fatal(err) } // Delete user not created by gojenkins er r = jenkins.DeleteUser("username") ``` -------------------------------- ### View Management Source: https://context7.com/bndr/gojenkins/llms.txt Allows for the creation and management of Jenkins views, which are used to organize jobs. ```APIDOC ## View Management ### Description Create, manage, and organize Jenkins jobs using views. ### Methods - **CreateView(ctx context.Context, viewName string, viewType string)**: Creates a new view of a specified type. - **GetAllViews(ctx context.Context)**: Retrieves a list of all available views. - **DeleteView(ctx context.Context, viewName string)**: Deletes a view. - **AddJob(ctx context.Context, jobName string)**: Adds a job to the current view. - **DeleteJob(ctx context.Context, jobName string)**: Removes a job from the current view. - **GetName()**: Returns the name of the view. - **GetUrl()**: Returns the URL of the view. - **GetJobs()**: Returns a list of jobs in the view. ### View Types Available view type constants: `gojenkins.LIST_VIEW`, `gojenkins.NESTED_VIEW`, `gojenkins.MY_VIEW`, `gojenkins.DASHBOARD_VIEW`, `gojenkins.PIPELINE_VIEW`. ### Example Usage ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a list view view, err := jenkins.CreateView(ctx, "Production", gojenkins.LIST_VIEW) if err != nil { panic(err) } // Add jobs to the view view.AddJob(ctx, "deploy-frontend") view.AddJob(ctx, "deploy-backend") fmt.Printf("View %q has %d jobs\n", view.GetName(), len(view.GetJobs())) // List all views allViews, _ := jenkins.GetAllViews(ctx) for _, v := range allViews { fmt.Printf(" - %s (%s)\n", v.GetName(), v.GetUrl()) } // Remove job from view view.DeleteJob(ctx, "deploy-frontend") // Delete view jenkins.DeleteView(ctx, "Production") ``` ``` -------------------------------- ### Create and Revoke API Tokens in Go Source: https://github.com/bndr/gojenkins/blob/master/README.md Handles the generation and revocation of API tokens for Jenkins authentication. After creating a token, the Jenkins client can be updated to use it for subsequent requests. All tokens for a user can also be revoked. ```go // Create a token for admin user token, err := jenkins.GenerateAPIToken(ctx, "TestToken") if err != nil { log.Fatal(err) } // Set Jenkins client to use new API token jenkins.Requester.BasicAuth.Password = token.Value // Revoke token that was just created token.Revoke() // Revoke all tokens for admin user er r = jenkins.RevokeAllAPITokens(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Node (Agent) Management Source: https://context7.com/bndr/gojenkins/llms.txt Provides functionality to create, query, and control Jenkins build agents (nodes), supporting both JNLP and SSH launchers. ```APIDOC ## Node (Agent) Management ### Description Manage Jenkins build agents (nodes), including creation, status checking, and deletion. ### Methods - **CreateNode(ctx context.Context, name string, numExecutors int, description string, remoteFS string, labels ...string, opts ...map[string]string)**: Creates a new node. Supports JNLP and SSH launchers via options. - **GetAllNodes(ctx context.Context)**: Retrieves a list of all nodes. - **GetNode(ctx context.Context, name string)**: Retrieves a specific node by name. - **DeleteNode(ctx context.Context, name string)**: Deletes a node. - **Poll(ctx context.Context)**: Polls the status of a node. - **IsOnline(ctx context.Context)**: Checks if a node is online. - **IsIdle(ctx context.Context)**: Checks if a node is idle. - **SetOffline(ctx context.Context, msg string)**: Sets a node to offline status with a message. - **SetOnline(ctx context.Context)**: Brings a node back online. ### Example Usage ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a JNLP node node, err := jenkins.CreateNode(ctx, "worker-01", 2, "Build worker", "/home/jenkins", "linux docker") if err != nil { panic(err) } fmt.Println("Created node:", node.GetName()) // Create an SSH node sshNode, err := jenkins.CreateNode(ctx, "ssh-worker", 4, "SSH worker", "/opt/jenkins", "linux", map[string]string{ "method": "SSHLauncher", "host": "192.168.1.50", "port": "22", "credentialsId": "ssh-key-credential", }) if err != nil { panic(err) } fmt.Println("SSH node:", sshNode.GetName()) // List all nodes and check status nodes, _ := jenkins.GetAllNodes(ctx) for _, n := range nodes { n.Poll(ctx) online, _ := n.IsOnline(ctx) idle, _ := n.IsIdle(ctx) fmt.Printf("Node %s: online=%v idle=%v\n", n.GetName(), online, idle) } // Take a node offline specificNode, _ := jenkins.GetNode(ctx, "worker-01") specificNode.SetOffline(ctx, "maintenance window") // Bring back online specificNode.SetOnline(ctx) // Delete node jenkins.DeleteNode(ctx, "worker-01") ``` ``` -------------------------------- ### Jenkins.Info Source: https://context7.com/bndr/gojenkins/llms.txt Retrieves general server information, including the list of top-level jobs and views. This method also refreshes the cached Jenkins version information. ```APIDOC ## Jenkins.Info Returns general server information including the list of top-level jobs and views, and refreshes the cached `Jenkins.Version`. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) info, err := jenkins.Info(ctx) if err != nil { panic(err) } fmt.Printf("Jenkins %s has %d top-level jobs\n", jenkins.Version, len(info.Jobs)) // Output: Jenkins 2.440 has 12 top-level jobs ``` ``` -------------------------------- ### User Management Source: https://context7.com/bndr/gojenkins/llms.txt Create and delete Jenkins user accounts. This includes creating a new user with specified details and deleting users either via their user object or directly by username. ```APIDOC ## User Management Create and delete Jenkins user accounts. ```go ctx := context.Background() jenkins, _ := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin").Init(ctx) // Create a new user user, err := jenkins.CreateUser(ctx, "jdoe", "P@ssw0rd!", "John Doe", "jdoe@example.com") if err != nil { panic(err) } fmt.Printf("Created user: %s (%s)\n", user.UserName, user.FullName) // Delete via user object if err := user.Delete(); err != nil { panic(err) } // Delete by username directly if err := jenkins.DeleteUser(ctx, "another-user"); err != nil { fmt.Println("Delete error:", err) } ``` ```