Last active
June 16, 2025 02:11
-
-
Save john-ho-codeonit-com/a592573dcb99e9df13327d37d368bbc9 to your computer and use it in GitHub Desktop.
Jenkins groovy init script
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
| #!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