Skip to content

Instantly share code, notes, and snippets.

@xbeta
Created November 25, 2014 23:38
Show Gist options
  • Save xbeta/e5edcf239fcdbe3f1672 to your computer and use it in GitHub Desktop.
Save xbeta/e5edcf239fcdbe3f1672 to your computer and use it in GitHub Desktop.
put them in $JENKINS_HOME/init.groovy.d/
import jenkins.model.*;
import hudson.security.*;
// JVM did not like 'hypen' in the class name, it will crap out saying it is
// illegal class name.
class BuildPermission {
static buildNewAccessList(userOrGroup, permissions) {
def newPermissionsMap = [:]
permissions.each {
newPermissionsMap.put(Permission.fromId(it), userOrGroup)
}
return newPermissionsMap
}
}
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "matrix-auth" } != null ) {
if ( Jenkins.instance.isUseSecurity() ) {
println "--> setting project matrix authorization strategy"
strategy = new hudson.security.ProjectMatrixAuthorizationStrategy()
//---------------------------- anonymous ----------------------------------
// NOTE: It is very bad to let anonymous to install/upload plugins, but
// that's how our chef run as to install plugins. :-/
anonymousPermissions = [
"hudson.model.Hudson.Read",
"hudson.model.Item.Read",
]
anonymous = BuildPermission.buildNewAccessList("anonymous", anonymousPermissions)
anonymous.each { p, u -> strategy.add(p, u) }
//------------------- fa-rel-jenkins --------------------------------------
faUserPermissions = [
"hudson.model.Hudson.Administer",
"hudson.model.Hudson.ConfigureUpdateCenter",
"hudson.model.Hudson.Read",
"hudson.model.Hudson.RunScripts",
"hudson.model.Hudson.UploadPlugins",
"hudson.model.Item.Read"
]
faUser = BuildPermission.buildNewAccessList("<%= @creds['plugins']['active-directory']['user'] %>", faUserPermissions)
faUser.each { p, u -> strategy.add(p, u) }
//------------------- authenticated ---------------------------------------
authenticatedPermissions = [
"hudson.model.Hudson.Read",
"hudson.model.Item.Build",
"hudson.model.Item.Configure",
"hudson.model.Item.Create",
"hudson.model.Item.Delete",
"hudson.model.Item.Discover",
"hudson.model.Item.Read",
"hudson.model.Item.Workspace",
"hudson.model.Run.Delete",
"hudson.model.Run.Update",
"hudson.model.View.Configure",
"hudson.model.View.Create",
"hudson.model.View.Delete",
"hudson.model.View.Read",
"hudson.model.Item.Cancel"
]
// plugin 'gerrit-trigger' permissions
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "gerrit-trigger" } != null ){
authenticatedPermissions.addAll(["com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl.ManualTrigger"])
}
// plugin 'promoted-builds' permissions
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "promoted-builds" } != null ){
authenticatedPermissions.addAll(["hudson.plugins.promoted_builds.Promotion.Promote"])
}
authenticated = BuildPermission.buildNewAccessList("authenticated", authenticatedPermissions)
authenticated.each { p, u -> strategy.add(p, u) }
//----------------- jenkins admin -----------------------------------------
jenkinsAdminPermissions = [
"hudson.model.Hudson.Administer",
"hudson.model.Hudson.ConfigureUpdateCenter",
"hudson.model.Hudson.Read",
"hudson.model.Hudson.RunScripts",
"hudson.model.Hudson.UploadPlugins",
"hudson.model.Computer.Build",
"hudson.model.Computer.Build",
"hudson.model.Computer.Configure",
"hudson.model.Computer.Connect",
"hudson.model.Computer.Create",
"hudson.model.Computer.Delete",
"hudson.model.Computer.Disconnect",
"hudson.model.Run.Delete",
"hudson.model.Run.Update",
"hudson.model.View.Configure",
"hudson.model.View.Create",
"hudson.model.View.Read",
"hudson.model.View.Delete",
"hudson.model.Item.Create",
"hudson.model.Item.Delete",
"hudson.model.Item.Configure",
"hudson.model.Item.Read",
"hudson.model.Item.Discover",
"hudson.model.Item.Build",
"hudson.model.Item.Workspace",
"hudson.model.Item.Cancel"
]
// plugin 'credentials' permissions
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "credentials" } != null ){
jenkinsAdminPermissions.addAll(["com.cloudbees.plugins.credentials.CredentialsProvider.Create",
"com.cloudbees.plugins.credentials.CredentialsProvider.Delete",
"com.cloudbees.plugins.credentials.CredentialsProvider.ManageDomains",
"com.cloudbees.plugins.credentials.CredentialsProvider.Update",
"com.cloudbees.plugins.credentials.CredentialsProvider.View"])
}
// plugin 'gerrit-trigger' permissions
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "gerrit-trigger" } != null ){
jenkinsAdminPermissions.addAll(["com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl.ManualTrigger",
"com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl.Retrigger"])
}
// plugin 'promoted-builds' permissions
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "promoted-builds" } != null ){
jenkinsAdminPermissions.addAll(["hudson.plugins.promoted_builds.Promotion.Promote"])
}
jenkinsAdmin = BuildPermission.buildNewAccessList("GRP-JenkinsAdmins", jenkinsAdminPermissions)
jenkinsAdmin.each { p, u -> strategy.add(p, u) }
//-------------------------------------------------------------------------
// now set the strategy globally
Jenkins.instance.setAuthorizationStrategy(strategy)
}
}
import hudson.model.*;
import jenkins.model.*;
import hudson.plugins.ec2.*;
import com.amazonaws.services.ec2.model.*;
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "ec2" } != null ) {
println "--> setting ec2 plugin"
///////////////// GLOBAL SETTINGS ///////////////////////////////////////////
// should use the same tag for all slave templates
def ec2Tags = [
new EC2Tag('Name', 'jenkins-builder.elastic.us-west-2a'),
new EC2Tag('created_by', '<%= node['fqdn'] %>'), // master node
new EC2Tag('Service', 'jenkins'),
new EC2Tag('Team', 'releng'),
new EC2Tag('Stage', 'prod')
] as List
UnixData unixData = new UnixData(null, '22') // linux box
////////////////////// SLAVE INSTANCE TEMPLATES /////////////////////////////
SlaveTemplate awsTemplate = new SlaveTemplate(
'ami-37e7af07', // ami
'us-west-2a', // zone
null, // spotconfiguration
'corp, jenkins', // security groups
'/home/jenkins/slave-root', // remote fs
InstanceType.M3Large, // instance type
'aws', // jenkins label
hudson.model.Node.Mode.NORMAL, // hudson.model.Node.Mode
'aws builder us-west-2a', // description
"""#!/bin/bash
source /usr/local/lib/bob/rvm_s3.sh || true
downloadRvmRubiesS3 || true""", // init script
'', // userdata
'1', // num executors
'jenkins', // remote admin user
unixData, // unix or windows (hudson.plugins.ec2.AMITypeData)
'', // slave jvmopts
true, // stop on terminate?
'subnet-cxxxxxxx', // subnet id
ec2Tags, // ec2 tags
'-5', // idle termination minutes
false, // use private dns name?
'200', // instance cap per ami
'', // IAM instance profile
false, // use ephemeral devices?
false, // use dedicated tenancy?
'1200', // launch timeout
false, // associate public ip?
'' // custom device mapping?
)
// a list of slave templates
def slaveTemplates = [awsTemplate]
////////////////////////////// EC2 CLOUDs ///////////////////////////////////
def ec2Cloud = new AmazonEC2Cloud(
'SAMPLEID', // access id
'<%= @creds['plugins']['ec2']['secret_key'] %>', // secret key
'us-west-1', // region
"""<%= @creds['plugins']['ec2']['private_key'] %>""", // private key
'500', // instance cap
slaveTemplates // list of slave templates
)
//////////////////////////// ADDING EC2 CLOUDS //////////////////////////////
def cloudList = Jenkins.instance.clouds
// avoid duplicate cloud provider on the cloud list
if ( cloudList.getByName(ec2Cloud.name) ) {
cloudList.remove(cloudList.getByName(ec2Cloud.name))
}
cloudList.add(ec2Cloud)
}
import jenkins.model.*;
import net.sf.json.*;
import com.sonyericsson.hudson.plugins.gerrit.trigger.*;
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "gerrit-trigger" } != null ) {
println "--> setting gerrit-trigger plugin"
def gerritPlugin = Jenkins.instance.getPlugin(com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl.class)
gerritPlugin.getPluginConfig().setNumberOfReceivingWorkerThreads(3)
gerritPlugin.getPluginConfig().setNumberOfSendingWorkerThreads(1)
def serverName = "lookout-gerrit"
GerritServer server = new GerritServer(serverName)
def config = server.getConfig()
def triggerConfig = [
'gerritHostName':"gerrit.mydomain.com",
'gerritSshPort':29418,
'gerritUserName':"jenkins",
'gerritFrontEndUrl':"https://gerrit.mydomain.com",
'gerritBuildCurrentPatchesOnly':true,
'gerritBuildStartedVerifiedValue':0,
'gerritBuildStartedCodeReviewValue':0,
'gerritBuildSuccessfulVerifiedValue':1,
'gerritBuildSuccessfulCodeReviewValue':0,
'gerritBuildFailedVerifiedValue':-1,
'gerritBuildFailedCodeReviewValue':0,
'gerritBuildUnstableVerifiedValue':-1,
'gerritBuildUnstableCodeReviewValue':0,
'gerritBuildNotBuiltVerifiedValue':0,
'gerritBuildNotBuiltCodeReviewValue':0,
'enableManualTrigger':true,
'enablePluginMessages':true,
'buildScheduleDelay':3,
'dynamicConfigRefreshInterval':30,
'watchdogTimeoutMinutes':0,
'verdictCategories': [
[ 'verdictValue':'CRVW', 'verdictDescription':'Code Review'],
[ 'verdictValue':'VRIF', 'verdictDescription':'Verified']
] as LinkedList
]
config.setValues(JSONObject.fromObject(triggerConfig))
server.setConfig(config)
// avoid duplicate servers on the server list
if ( gerritPlugin.containsServer(serverName) ) {
gerritPlugin.removeServer(gerritPlugin.getServer(serverName))
}
gerritPlugin.addServer(server)
}
import jenkins.model.*;
import java.lang.reflect.Field;
if ( Jenkins.instance.pluginManager.activePlugins.find { it.shortName == "hipchat" } != null ) {
println "--> setting hipchat plugin"
def descriptor = Jenkins.instance.getDescriptorByType(jenkins.plugins.hipchat.HipChatNotifier.DescriptorImpl.class)
// no setters :-(
// Groovy can disregard object's pivacy anyway to directly access private
// fields, but we use a different technique 'reflection' this time
Field[] fld = descriptor.class.getDeclaredFields();
for(Field f:fld){
f.setAccessible(true);
switch (f.getName()) {
case "server" : f.set(descriptor, "hipchat.mydomain.com")
break
case "token" : f.set(descriptor, "TOKEN")
break
case "buildServerUrl" : f.set(descriptor, "/")
break
case "sendAs" : f.set(descriptor, "jenkinsbot")
break
}
}
}
@espoelstra
Copy link

You shouldn't need to let anonymous install plugins if you properly configure your authorization strategy immediately after installing your list of required plugins.

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