Created
February 25, 2020 21:17
-
-
Save jamcole/74487dc8af7f588b8476f97056974301 to your computer and use it in GitHub Desktop.
OpenShift Token Credentials Creator Jenkins Library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jenkins.model.* | |
import com.cloudbees.hudson.plugins.folder.*; | |
import com.cloudbees.hudson.plugins.folder.properties.*; | |
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty; | |
import com.cloudbees.plugins.credentials.impl.*; | |
import com.cloudbees.plugins.credentials.*; | |
import com.cloudbees.plugins.credentials.domains.*; | |
import com.openshift.jenkins.plugins.OpenShiftTokenCredentials; | |
import hudson.util.Secret; | |
class OpenShiftCredentials { | |
static Boolean createOrUpdateJenkinsTokenCredential(String folder, String id, String description, String token, Boolean createOnly = false) { | |
Credentials credentials = new OpenShiftTokenCredentials(CredentialsScope.GLOBAL, id, description, new Secret(token)) | |
def jenkins = Jenkins.instance | |
def folderRef | |
for (def item in jenkins.getAllItems(Folder.class)) { | |
if (item.fullName.equals(folder)) { | |
folderRef = item | |
break | |
} | |
} | |
if (!folderRef) { | |
error "Unable to find folder ${folder}" | |
} | |
println "Found ${folderRef.fullName}" | |
AbstractFolder<?> folderAbs = AbstractFolder.class.cast(folderRef) | |
FolderCredentialsProperty property = folderAbs.getProperties().get(FolderCredentialsProperty.class) | |
def updated = false | |
if (property) { | |
def store = property.getStore(); | |
for (def existing in property.getCredentials(OpenShiftTokenCredentials.class)) { | |
if (existing.id.equals(id)) { | |
if (createOnly) { | |
println "Found existing ${id} but skipping update as per createOnly flag" | |
} else { | |
println "Update credentials for ${id}" | |
updated = true | |
store.updateCredentials(Domain.global(), existing, credentials) | |
} | |
break; | |
} | |
} | |
if (!updated) { | |
println "Add credentials for ${id}" | |
store.addCredentials(Domain.global(), credentials) | |
updated = true | |
} | |
} else { | |
println "Initialize Credentials store and add credentials for ${id}" | |
folderAbs.addProperty(new FolderCredentialsProperty([credentials])) | |
} | |
return updated | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment