Skip to content

Instantly share code, notes, and snippets.

View ababushk's full-sized avatar

Andrey Babushkin ababushk

View GitHub Profile
@ababushk
ababushk / get_commit.groovy
Created August 14, 2019 15:48
Get commit hash without checkout step in Jenkins Pipeline in GitHub Organization Folder
def commitHashForBuild(build) {
def scmAction = build?.actions.find { action -> action instanceof jenkins.scm.api.SCMRevisionAction }
if (scmAction?.revision instanceof org.jenkinsci.plugins.github_branch_source.PullRequestSCMRevision) {
return scmAction?.revision?.pullHash
} else if (scmAction?.revision instanceof jenkins.plugins.git.AbstractGitSCMSource$SCMRevisionImpl) {
return scmAction?.revision?.hash
} else {
error("Build doesn't contain revision information. Do you run this from GitHub organization folder?")
}
}
@ababushk
ababushk / gitlab_cancel_builds.groovy
Last active October 25, 2019 14:07
A function to cancel previous builds from the same GitLab merge request
def cancelBuilds(int builds_to_scan=300) {
def jobName = env.JOB_NAME
def currentMR = env.gitlabMergeRequestIid?.toInteger()
def currentRepoUrl = env.gitlabSourceRepoURL
def currentBuildNumber = env.BUILD_NUMBER?.toInteger()
def currentJob = Jenkins.instance.getItemByFullName(jobName)
def i = 0
for (def build : currentJob.builds) {
if (i > builds_to_scan) {
@ababushk
ababushk / add_custom_prometheus_metric_to_Jenkins.groovy
Last active June 17, 2021 14:19
A groovy script that can be executed in Jenkins Script Console, it adds additional metric to regular Jenkins Prometheus plugin output
import jenkins.model.Jenkins
import io.prometheus.client.Collector;
import io.prometheus.client.GaugeMetricFamily
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Collector.MetricFamilySamples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class BuildsCountByJobCollector extends Collector {
private static final Logger LOG = LoggerFactory.getLogger(BuildsCountByJobCollector.class)
@ababushk
ababushk / decrypt_credentials.groovy
Created August 9, 2021 19:23
Get Decrypted Jenkins Credentials via Script Console
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
def credId = 'my_credentials_id'
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,