Skip to content

Instantly share code, notes, and snippets.

@john-ho-codeonit-com
Last active June 16, 2025 02:11
Show Gist options
  • Select an option

  • Save john-ho-codeonit-com/a592573dcb99e9df13327d37d368bbc9 to your computer and use it in GitHub Desktop.

Select an option

Save john-ho-codeonit-com/a592573dcb99e9df13327d37d368bbc9 to your computer and use it in GitHub Desktop.
Jenkins groovy init script
#!groovy
import hudson.model.*
import hudson.security.*
import jenkins.security.apitoken.*
import jenkins.model.*
import hudson.security.csrf.DefaultCrumbIssuer
def instance = Jenkins.getInstance()
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
def users = hudsonRealm.getAllUsers()
def userName = "jenkins"
def password = "jenkins"
def tokenName = "jenkins"
instance.setCrumbIssuer(new DefaultCrumbIssuer(true))
instance.save()
users_s = users.collect { it.toString() }
def userExists = "jenkins" in users_s
if (!userExists) {
hudsonRealm.createAccount(userName, password)
instance.setSecurityRealm(hudsonRealm)
def strategy = new hudson.security.FullControlOnceLoggedInAuthorizationStrategy()
strategy.setAllowAnonymousRead(false)
instance.setAuthorizationStrategy(strategy)
instance.save()
def user = User.get(userName, false)
def apiTokenProperty = user.getProperty(ApiTokenProperty.class)
def result = apiTokenProperty.tokenStore.generateNewToken(tokenName)
user.save()
File file = new File("/var/lib/jenkins/token")
file.append(result.plainValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment