How do I create jenkins credentials using a golang script? In this blog article, we are going use GoJenkins library to create jenkins Username, String and SSH credentials.
The Jenkins credentials plugin provides a default internal credentials store, which can be used to store high value or privileged credentials, such as Amazon bucket deployment username/password combinations and GitHub user tokens.
The jenkins credentials binding plugin - https://plugins.jenkins.io/credentials-binding - Allows credentials to be bound to environment variables for use from miscellaneous build steps.
Prerequisites
To follow along, ensure:
- you have a working jenkins with admin username and password
- You have golang set up in your local machine
- You know basics of golang and Jenkins
Install the Credential and Credential Binding Plugin
Go to Jenkins > Plugins Manager and select Credentials and Credential Bindings Plugin. Then click install.
Create directory structure and initialize module
Create a directory.
|
|
Switch to the directory, Initialize a module in that directory using the go mod init
command:
|
|
Adding imports
We need to instantiate the package and add imports. Let’s do it with this code block:
|
|
In the above code snippet, the most important import is the gojenkins one - github.com/bndr/gojenkins
. This is the module that we will use manage jenkins credentials.
Define constants
The next bit is to define constants. We need these to instantiate things like jenkins url, username and password that do not change. These will be used in the script.
Define the constants:
|
|
Initialize connection to jenkins
Next is the main function. We need to connect to jenkins. We can also provide a CA certificate if server is using self-signed certificate. Checkout this code block:
|
|
Define credentials structs
Next, for each credential that we are defining we need a struct. gojenkins already defines structs that we can just pass values.
Username credentials
These are credentials that have a key and a value. Let’s instantiate a struct that an be expanded:
|
|
Use this block to create the credentials:
|
|
String credentials
These are strings that are credentials. Let us define with:
|
|
Now create:
|
|
SSH credentials
This is private ssh key creds. To define, use this snippet:
|
|
Now let’s create:
|
|
Getting a list of existing credentials
To get all the credentials, use this:
|
|
Whole code
This is the whole code:
|
|
Building and testing the script
Go mod tidy:
|
|
Build:
|
|
Test Execution:
|
|
Conclusion
We managed to automate the process of creating jenkins credentials.