Skip to content

Instantly share code, notes, and snippets.

@hayderimran7
Last active April 10, 2024 17:29
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save hayderimran7/50cb1244cc1e856873a4 to your computer and use it in GitHub Desktop.
Save hayderimran7/50cb1244cc1e856873a4 to your computer and use it in GitHub Desktop.
Jenkins Groovy enable security and create a user in groovy script

This is a snippet that will create a new user in jenkins and if security has been disabled , it will enable it :)

import jenkins.model.*
import hudson.security.*

def instance = Jenkins.getInstance()

def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount("MyUSERNAME","MyPASSWORD")
instance.setSecurityRealm(hudsonRealm)
instance.save()

Bonus: Add the created user as admin for jenkins: what if you want that user to be like admin of jenkins who can access anything.. no problem..just add following lines right above the 'instance.save()' statement and run :)

def strategy = new GlobalMatrixAuthorizationStrategy()
strategy.add(Jenkins.ADMINISTER, "myUSERNAME")
instance.setAuthorizationStrategy(strategy)
@marchev
Copy link

marchev commented Feb 8, 2016

Just what I've been looking for! Thanks

@toweih
Copy link

toweih commented May 16, 2016

Seems as if GlobalMatrixAuthorizationStrategy does not longer exist in Jenkins 3.

The "FullControlOnceLoggedInAuthorizationStrategy" works for me:

def strategy = new hudson.security.FullControlOnceLoggedInAuthorizationStrategy()
strategy.setAllowAnonymousRead(false)
instance.setAuthorizationStrategy(strategy)

@brianantonelli
Copy link

Thanks! And thanks for the matrix fix @toweih!

@Bharathkumarraju
Copy link

This is really awesome!!! You made my task so simple

@mohamed-el-habib
Copy link

To use the GlobalMatrixAuthorizationStrategy you must install matrix-auth plugin

@pradheba123
Copy link

Thanks a ton! This is exactly what I was looking for.

@scheung38
Copy link

Hi, what if I need more finer granularity for access to certain resources, such as Developer, or Tester role.

@hayderimran7
Copy link
Author

You can use Role Role Strategy plugin and configure finer permissions as shown in this script -> https://github.com/cloudbees/jenkins-scripts/blob/master/RBAC_Example.groovy

@leeraldy
Copy link

How to modify this script to this user to a specific existing group in Jenkins?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment