Skip to content

Instantly share code, notes, and snippets.

@hemanth22
Forked from fishi0x01/baseURL.groovy
Created February 3, 2025 16:37
Show Gist options
  • Save hemanth22/2dceac75e2ea6f04383dea5f84f9b9ff to your computer and use it in GitHub Desktop.
Save hemanth22/2dceac75e2ea6f04383dea5f84f9b9ff to your computer and use it in GitHub Desktop.

Revisions

  1. @fishi0x01 fishi0x01 revised this gist Mar 10, 2019. 2 changed files with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions triggerConfigurationAsCodePlugin.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    #! groovy

    import jenkins.model.Jenkins

    // trigger configuration as code plugin
    def jcacPlugin = Jenkins.instance.getExtensionList(io.jenkins.plugins.casc.ConfigurationAsCode.class).first()
    jcacPlugin.configure()
    File renamed without changes.
  2. @fishi0x01 fishi0x01 revised this gist Feb 9, 2019. 1 changed file with 12 additions and 0 deletions.
    12 changes: 12 additions & 0 deletions user-public-keys.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    #! groovy

    def getFileContent(filePath) {
    return new File(filePath).text
    }

    def user = hudson.model.User.get('admin')

    def pubKey = new org.jenkinsci.main.modules.cli.auth.ssh.UserPropertyImpl(getFileContent('/var/jenkins_home/jenkins-ssh-keys/ssh-jenkins-cli.pub'))
    user.addProperty(pubKey)

    user.save()
  3. @fishi0x01 fishi0x01 revised this gist Feb 9, 2019. 1 changed file with 28 additions and 4 deletions.
    32 changes: 28 additions & 4 deletions init.groovy
    Original file line number Diff line number Diff line change
    @@ -13,6 +13,8 @@ import jenkins.model.Jenkins
    import com.cloudbees.plugins.credentials.domains.Domain
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
    import com.cloudbees.plugins.credentials.CredentialsScope
    import hudson.security.FullControlOnceLoggedInAuthorizationStrategy
    import hudson.security.HudsonPrivateSecurityRealm

    // Add deploy key for the centrally shared pipeline and configuration repository
    def domain = Domain.global()
    @@ -24,12 +26,34 @@ def privateKey = new BasicSSHUserPrivateKey(
    "root",
    new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(keyFileContents),
    "",
    "SSH key for shared-libraries"
    "SSH key for shared-library"
    )
    store.addCredentials(domain, privateKey)

    // Create the configuration pipeline from a jobDSL script
    def jobDslScript = new File('/var/jenkins_home/init-dsl/ConfigurationPipelineDSL.groovy')
    // Create the configuration job interface from a jobDSL script
    def jobDslScript = new File('/var/jenkins_home/init-dsl/ConfigurationAndSeedingPipelineDSL.groovy')
    def workspace = new File('.')
    def jobManagement = new JenkinsJobManagement(System.out, [:], workspace)
    new DslScriptLoader(jobManagement).runScript(jobDslScript.text)
    new DslScriptLoader(jobManagement).runScript(jobDslScript.text)

    // Disable Setup Wizards
    if(Jenkins.instance.getSecurityRealm().getClass().getSimpleName() == 'None') {
    def instance = Jenkins.getInstance()

    // Those files should be mounted into the jenkins master container
    def setupUser = new File("/var/jenkins_home/jenkins-basic-auth-credentials/default-setup-user").text.trim()
    def setupPass = new File("/var/jenkins_home/jenkins-basic-auth-credentials/default-setup-password").text.trim()

    def hudsonRealm = new HudsonPrivateSecurityRealm(false)
    instance.setSecurityRealm(hudsonRealm)
    def user = instance.getSecurityRealm().createAccount(setupUser, setupPass)
    user.save()

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

    instance.save()

    println("SetupWizard Disabled")
    }
  4. @fishi0x01 fishi0x01 revised this gist Jan 22, 2019. 1 changed file with 13 additions and 7 deletions.
    20 changes: 13 additions & 7 deletions theme.groovy
    Original file line number Diff line number Diff line change
    @@ -6,12 +6,18 @@
    * Tested with simple-theme-plugin:0.5.1
    *
    * Use http://afonsof.com/jenkins-material-theme/ to generate a new jenkins theme.
    * Place the theme at the userContent directory of Jenkins to be publicly available
    * Upload the theme to a CDN or place it directly at the userContent directory of
    * Jenkins to be publicly available.
    */

    for (pd in PageDecorator.all()) {
    if (pd instanceof org.codefirst.SimpleThemeDecorator) {
    pd.setCssUrl('https://my-jenkins.devtail.io/userContent/fishi0x01.css')
    pd.load()
    }
    }
    import jenkins.model.Jenkins
    import org.jenkinsci.plugins.simpletheme.CssUrlThemeElement


    def themeDecorator = Jenkins.instance.getExtensionList(org.codefirst.SimpleThemeDecorator.class).first()

    themeDecorator.setElements([
    new CssUrlThemeElement('https://fishi.devtail.io/content-images/jenkins-devtail-theme.css')
    ])

    Jenkins.instance.save()
  5. @fishi0x01 fishi0x01 revised this gist Jan 21, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion credentials.groovy
    Original file line number Diff line number Diff line change
    @@ -81,5 +81,5 @@ sshKeys = [
    ]

    for(sshKey in sshKeys) {
    getStore().addCredentials(domain, getKeyCredential(sshKey.id, sshKey.path, sshKey.user))
    getStore().addCredentials(domain, getSSHKeyCredential(sshKey.id, sshKey.path, sshKey.user))
    }
  6. @fishi0x01 fishi0x01 revised this gist Jan 21, 2019. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions credentials.groovy
    Original file line number Diff line number Diff line change
    @@ -53,7 +53,7 @@ userPasswords = [

    for(userPassword in userPasswords) {
    Credentials cred = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, userPassword.id, userPassword.description, getContent(userPassword.userNameFile), getContent(userPassword.userPasswordFile))
    getStore().addCredentials(domain, registryCreds)
    getStore().addCredentials(domain, cred)
    }

    /////////////
    @@ -67,7 +67,7 @@ secretTokens = [
    ]

    for(secretToken in secretTokens) {
    Credentials token = (Credentials) new StringCredentialsImpl(CredentialsScope.GLOBAL, tokenSecret.id, tokenSecret.description, Secret.fromString(getContent(tokenSecret.tokenFile)))
    Credentials token = (Credentials) new StringCredentialsImpl(CredentialsScope.GLOBAL, secretToken.id, secretToken.description, Secret.fromString(getContent(secretToken.tokenFile)))
    getStore().addCredentials(domain, token)
    }

  7. @fishi0x01 fishi0x01 revised this gist Jan 19, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion baseURL.groovy
    Original file line number Diff line number Diff line change
    @@ -7,5 +7,5 @@
    import jenkins.model.JenkinsLocationConfiguration

    JenkinsLocationConfiguration location = Jenkins.instance.getExtensionList('jenkins.model.JenkinsLocationConfiguration')[0]
    location.url = 'https://my-jenkins.devtail.io/'
    location.url = 'https://jenkins-as-code-poc.devtail.io/'
    location.save()
  8. @fishi0x01 fishi0x01 revised this gist Jan 19, 2019. 1 changed file with 0 additions and 7 deletions.
    7 changes: 0 additions & 7 deletions init.groovy
    Original file line number Diff line number Diff line change
    @@ -13,13 +13,6 @@ import jenkins.model.Jenkins
    import com.cloudbees.plugins.credentials.domains.Domain
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
    import com.cloudbees.plugins.credentials.CredentialsScope
    import jenkins.install.InstallState

    // Disable Setup Wizard
    if (!Jenkins.instance.installState.isSetupComplete()) {
    println '--> Neutering SetupWizard'
    InstallState.INITIAL_SETUP_COMPLETED.initializeState()
    }

    // Add deploy key for the centrally shared pipeline and configuration repository
    def domain = Domain.global()
  9. @fishi0x01 fishi0x01 revised this gist Jan 19, 2019. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions init.groovy
    Original file line number Diff line number Diff line change
    @@ -13,7 +13,13 @@ import jenkins.model.Jenkins
    import com.cloudbees.plugins.credentials.domains.Domain
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
    import com.cloudbees.plugins.credentials.CredentialsScope
    import jenkins.install.InstallState

    // Disable Setup Wizard
    if (!Jenkins.instance.installState.isSetupComplete()) {
    println '--> Neutering SetupWizard'
    InstallState.INITIAL_SETUP_COMPLETED.initializeState()
    }

    // Add deploy key for the centrally shared pipeline and configuration repository
    def domain = Domain.global()
  10. @fishi0x01 fishi0x01 revised this gist Jan 13, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion globalSharedLibrary.groovy
    Original file line number Diff line number Diff line change
    @@ -20,7 +20,7 @@ List libraries = [] as ArrayList
    def remote = '[email protected]:<my-org>/<my-shared-library>.git'
    def credentialsId = 'ssh-global-shared-library'

    name = 'pipeline-lib'
    name = 'lib-name'
    defaultVersion = 'master'

    if (remote != null) {
  11. @fishi0x01 fishi0x01 renamed this gist Jan 12, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  12. @fishi0x01 fishi0x01 renamed this gist Jan 12, 2019. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions manageTools.groovy → maven.groovy
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,10 @@
    #!groovy

    /*
    * This script makes the maven tool available on all Jenkins nodes.
    * Requires the maven plugin to be installed.
    */

    import hudson.tasks.Maven.MavenInstallation;
    import hudson.tools.InstallSourceProperty;
    import hudson.tools.ToolProperty;
  13. @fishi0x01 fishi0x01 revised this gist Jan 12, 2019. 10 changed files with 118 additions and 89 deletions.
    11 changes: 11 additions & 0 deletions baseURL.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    #!groovy

    /*
    * This script configures the Jenkins base URL.
    */

    import jenkins.model.JenkinsLocationConfiguration

    JenkinsLocationConfiguration location = Jenkins.instance.getExtensionList('jenkins.model.JenkinsLocationConfiguration')[0]
    location.url = 'https://my-jenkins.devtail.io/'
    location.save()
    20 changes: 20 additions & 0 deletions github.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    #!groovy

    /*
    * This script configures the GitHub Plugin.
    * Requires the GitHub Plugin to be installed.
    * Tested with github:1.29.3
    */

    import jenkins.model.Jenkins
    import org.jenkinsci.plugins.github.config.GitHubPluginConfig
    import org.jenkinsci.plugins.github.config.GitHubServerConfig

    def githubConfig = new GitHubServerConfig("github-ci-user-token") // credential ID for our user token for the GitHub CI User
    githubConfig.setManageHooks(true)
    githubConfig.setName("GitHub")
    def github = Jenkins.instance.getExtensionList(GitHubPluginConfig.class)[0]
    github.setConfigs([
    githubConfig,
    ])
    github.save()
    36 changes: 36 additions & 0 deletions globalEnvVars.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    #!groovy

    /*
    * This script configures global environment variables in Jenkins
    */

    import jenkins.model.Jenkins
    import hudson.EnvVars;
    import hudson.slaves.EnvironmentVariablesNodeProperty;
    import hudson.slaves.NodeProperty;
    import hudson.slaves.NodePropertyDescriptor;
    import hudson.util.DescribableList;

    def createGlobalEnvironmentVariables(String key, String value){

    Jenkins instance = Jenkins.getInstance();

    DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
    List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);

    EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
    EnvVars envVars = null;

    if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
    newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
    globalNodeProperties.add(newEnvVarsNodeProperty);
    envVars = newEnvVarsNodeProperty.getEnvVars();
    } else {
    envVars = envVarsNodePropertyList.get(0).getEnvVars();
    }
    envVars.put(key, value)
    instance.save()
    }

    createGlobalEnvironmentVariables('MY_ENV_VAR_A', 'A')
    createGlobalEnvironmentVariables('MY_ENV_VAR_B', 'B')
    27 changes: 0 additions & 27 deletions manageGlobalEnvVars.groovy
    Original file line number Diff line number Diff line change
    @@ -1,27 +0,0 @@
    #!groovy

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

    instance = Jenkins.getInstance()
    globalNodeProperties = instance.getGlobalNodeProperties()

    envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)

    newEnvVarsNodeProperty = null
    envVars = null

    if (envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0) {
    newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
    globalNodeProperties.add(newEnvVarsNodeProperty)
    envVars = newEnvVarsNodeProperty.getEnvVars()
    } else {
    envVars = envVarsNodePropertyList.get(0).getEnvVars()
    }

    envVars.put("MY_ENV_VAR", "MyEnvVar")
    envVars.put("MY_ENV_VAR_FROM_HOST_SYSTEM", System.getenv()['HOST_SYSTEM_ENV_VAR'])

    instance.save()
    44 changes: 0 additions & 44 deletions managePlugins.groovy
    Original file line number Diff line number Diff line change
    @@ -1,44 +0,0 @@
    #!groovy

    import jenkins.model.*
    import java.util.logging.Logger

    /*
    FIXME: This script still triggers a lot of restarts until everything is
    properly installed...
    */

    def logger = Logger.getLogger("")
    def installed = false
    def initialized = false

    def pluginParameter="plugin-id-1 plugin-id-2 plugin-id-3"
    def plugins = pluginParameter.split()
    logger.info("" + plugins)
    def instance = Jenkins.getInstance()
    def pm = instance.getPluginManager()
    def uc = instance.getUpdateCenter()
    uc.updateAllSites()

    plugins.each {
    logger.info("Checking " + it)
    if (!pm.getPlugin(it)) {
    logger.info("Looking UpdateCenter for " + it)
    if (!initialized) {
    uc.updateAllSites()
    initialized = true
    }
    def plugin = uc.getPlugin(it)
    if (plugin) {
    logger.info("Installing " + it)
    plugin.deploy()
    installed = true
    }
    }
    }

    if (installed) {
    logger.info("Plugins installed, initializing a restart!")
    instance.save()
    instance.doSafeRestart()
    }
    18 changes: 0 additions & 18 deletions manageSecurity.groovy
    Original file line number Diff line number Diff line change
    @@ -1,18 +0,0 @@
    #!groovy

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

    def instance = Jenkins.getInstance()

    // Create user account
    def hudsonRealm = new HudsonPrivateSecurityRealm(false)
    hudsonRealm.createAccount("my_user", "my_pass")
    instance.setSecurityRealm(hudsonRealm)

    // Enable matrix auth strategy and set my_user as admin
    def strategy = new GlobalMatrixAuthorizationStrategy()
    strategy.add(Jenkins.ADMINISTER, "my_user")
    instance.setAuthorizationStrategy(strategy)

    instance.save()
    15 changes: 15 additions & 0 deletions slack.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    #!groovy

    /*
    * This script configures the Jenkins Slack Plugin.
    * Requires the installation of the Slack Plugin.
    * Tested with slack:2.3
    */

    import jenkins.model.Jenkins

    def slack = Jenkins.instance.getExtensionList('jenkins.plugins.slack.SlackNotifier$DescriptorImpl')[0]
    slack.tokenCredentialId = 'slack-token'
    slack.teamDomain = 'my-slack-team-domain'
    slack.baseUrl = 'https://my-slack-team-domain.slack.com/services/hooks/jenkins-ci/'
    slack.save()
    12 changes: 12 additions & 0 deletions sshd.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    #!groovy

    /*
    * This script configures the Jenkins SSHD Port.
    */

    import jenkins.model.Jenkins

    def sshDesc = Jenkins.instance.getDescriptor("org.jenkinsci.main.modules.sshd.SSHD")
    sshDesc.setPort(6666)
    sshDesc.getActualPort()
    sshDesc.save()
    17 changes: 17 additions & 0 deletions theme.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    #!groovy

    /*
    * This script configures the simple theme plugin.
    * Requires the simple theme plugin to be installed.
    * Tested with simple-theme-plugin:0.5.1
    *
    * Use http://afonsof.com/jenkins-material-theme/ to generate a new jenkins theme.
    * Place the theme at the userContent directory of Jenkins to be publicly available
    */

    for (pd in PageDecorator.all()) {
    if (pd instanceof org.codefirst.SimpleThemeDecorator) {
    pd.setCssUrl('https://my-jenkins.devtail.io/userContent/fishi0x01.css')
    pd.load()
    }
    }
    7 changes: 7 additions & 0 deletions timezone.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    #! groovy

    /*
    * This script configures the timezone in Jenkins
    */

    System.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', 'Europe/Berlin')
  14. @fishi0x01 fishi0x01 revised this gist Jan 12, 2019. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion init.groovy
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,8 @@
    /*
    * This script is designated for the init.groovy.d
    * directory to be executed at startup time of the
    * Jenkins instance.
    * Jenkins instance. This script requires the jobDSL
    * Plugin. Tested with job-dsl:1.70
    */

    import javaposse.jobdsl.dsl.DslScriptLoader
  15. @fishi0x01 fishi0x01 revised this gist Jan 12, 2019. 4 changed files with 57 additions and 8 deletions.
    9 changes: 5 additions & 4 deletions credentials.groovy
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,10 @@
    #!groovy

    /**************
    /*
    * This script loads different kinds
    * of credentials from files into the
    * Jenkins credential store.
    **************/
    */

    import jenkins.model.*
    import com.cloudbees.plugins.credentials.*
    @@ -75,8 +75,9 @@ for(secretToken in secretTokens) {
    // Add ssh keys
    ///////////////
    sshKeys = [
    [id: 'deploy-key-service-a', path: '/var/jenkins_home/.ssh/deploy-key-service-a', user: 'root'],
    [id: 'slave-access', path: '/var/jenkins_home/.ssh/slave-access', user: 'jenkins']
    [id: 'ssh-deploy-key-service-a', path: '/var/jenkins_home/.ssh/deploy-key-service-a', user: 'root'],
    [id: 'ssh-slave-access', path: '/var/jenkins_home/.ssh/slave-access', user: 'jenkins'],
    [id: 'ssh-global-shared-library', path: '/var/jenkins_home/.ssh/global-shared-library', user: 'root'],
    ]

    for(sshKey in sshKeys) {
    4 changes: 2 additions & 2 deletions githubOAuth.groovy
    Original file line number Diff line number Diff line change
    @@ -1,13 +1,13 @@
    #!groovy

    /***********************************************
    /*
    * This script configures Github OAuth access
    * in Jenkins. It uses a global authorization
    * Matrix strategy as authorization configurtion.
    * This script requires the Gibhub Authentication
    * plugin (github-oauth) to be installed. It is
    * tested with github-oauth:0.29
    ***********************************************/
    */

    import hudson.security.SecurityRealm
    import org.jenkinsci.plugins.GithubSecurityRealm
    48 changes: 48 additions & 0 deletions globalSharedLibrary.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    #!groovy

    /*
    * Configure pipeline shared libraries in the global Jenkins configuration.
    * This will safely compare configured libraries and only overwrite the global
    * shared library config if changes have been made.
    * workflow-cps-global-lib 2.9
    *
    * Source: https://github.com/thbkrkr/jks/blob/master/init.groovy.d/11-configure-pipeline-global-shared.groovy
    */
    import jenkins.model.Jenkins
    import jenkins.plugins.git.GitSCMSource
    import jenkins.plugins.git.traits.BranchDiscoveryTrait
    import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
    import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration
    import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever

    List libraries = [] as ArrayList

    def remote = '[email protected]:<my-org>/<my-shared-library>.git'
    def credentialsId = 'ssh-global-shared-library'

    name = 'pipeline-lib'
    defaultVersion = 'master'

    if (remote != null) {

    def scm = new GitSCMSource(remote)
    if (credentialsId != null) {
    scm.credentialsId = credentialsId
    }

    scm.traits = [new BranchDiscoveryTrait()]
    def retriever = new SCMSourceRetriever(scm)

    def library = new LibraryConfiguration(name, retriever)
    library.defaultVersion = defaultVersion
    library.implicit = false
    library.allowVersionOverride = true
    library.includeInChangesets = false

    libraries << library

    def global_settings = Jenkins.instance.getExtensionList(GlobalLibraries.class)[0]
    global_settings.libraries = libraries
    global_settings.save()
    println 'Configured Pipeline Global Shared Libraries:\n ' + global_settings.libraries.collect { it.name }.join('\n ')
    }
    4 changes: 2 additions & 2 deletions init.groovy
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,10 @@
    #!groovy

    /***********************************************
    /*
    * This script is designated for the init.groovy.d
    * directory to be executed at startup time of the
    * Jenkins instance.
    ***********************************************/
    */

    import javaposse.jobdsl.dsl.DslScriptLoader
    import javaposse.jobdsl.plugin.JenkinsJobManagement
  16. @fishi0x01 fishi0x01 revised this gist Jan 12, 2019. 2 changed files with 84 additions and 35 deletions.
    84 changes: 84 additions & 0 deletions credentials.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    #!groovy

    /**************
    * This script loads different kinds
    * of credentials from files into the
    * Jenkins credential store.
    **************/

    import jenkins.model.*
    import com.cloudbees.plugins.credentials.*
    import com.cloudbees.plugins.credentials.common.*
    import com.cloudbees.plugins.credentials.domains.*
    import com.cloudbees.plugins.credentials.impl.*
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
    import org.jenkinsci.plugins.plaincredentials.*
    import org.jenkinsci.plugins.plaincredentials.impl.*
    import hudson.util.Secret

    ///////////////////
    // Helper functions
    ///////////////////
    def getStore() {
    return Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
    }

    def getContent(filePath) {
    return new File(filePath).text
    }

    // This function reads the contents of a key file and returns
    // a Jenkins SSH private key object with the given user as owner
    def getSSHKeyCredential(id, path, user) {
    return new BasicSSHUserPrivateKey(
    CredentialsScope.GLOBAL,
    id,
    user,
    new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(getContent(path)),
    "",
    "SSH key ${id}"
    )
    }

    // Get master credential store
    domain = Domain.global()

    //////////////////////////////
    // Add username/password pairs
    //////////////////////////////
    userPasswords = [
    [id: 'docker-registry', description: 'Docker Registry Credentials', userNameFile: '/var/jenkins_home/secrets/dockerUserName', userPasswordFile: '/var/jenkins_home/secrets/dockerUserPassword'],
    [id: 'github-ci-user', description: 'GitHub CI User Credentials', userNameFile: '/var/jenkins_home/secrets/githubCIUserName', userPasswordFile: '/var/jenkins_home/secrets/githubCIUserToken'],
    ]

    for(userPassword in userPasswords) {
    Credentials cred = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, userPassword.id, userPassword.description, getContent(userPassword.userNameFile), getContent(userPassword.userPasswordFile))
    getStore().addCredentials(domain, registryCreds)
    }

    /////////////
    // Add tokens
    /////////////
    secretTokens = [
    [id: 'slack-token', description: 'Slack Token', tokenFile: '/var/jenkins_home/secrets/slackToken'],
    [id: 'vault-approle-secret', description: 'Vault AppRole Secret', tokenFile: '/var/jenkins_home/secrets/vaultAppRoleSecret'],
    [id: 'vault-approle-id', description: 'Vault AppRole ID', tokenFile: '/var/jenkins_home/secrets/vaultAppRoleID'],
    [id: 'github-ci-user-token', description: 'Github CI User Token', tokenFile: '/var/jenkins_home/secrets/githubCIUserToken']
    ]

    for(secretToken in secretTokens) {
    Credentials token = (Credentials) new StringCredentialsImpl(CredentialsScope.GLOBAL, tokenSecret.id, tokenSecret.description, Secret.fromString(getContent(tokenSecret.tokenFile)))
    getStore().addCredentials(domain, token)
    }

    ///////////////
    // Add ssh keys
    ///////////////
    sshKeys = [
    [id: 'deploy-key-service-a', path: '/var/jenkins_home/.ssh/deploy-key-service-a', user: 'root'],
    [id: 'slave-access', path: '/var/jenkins_home/.ssh/slave-access', user: 'jenkins']
    ]

    for(sshKey in sshKeys) {
    getStore().addCredentials(domain, getKeyCredential(sshKey.id, sshKey.path, sshKey.user))
    }
    35 changes: 0 additions & 35 deletions manageCredentials.groovy
    Original file line number Diff line number Diff line change
    @@ -1,35 +0,0 @@
    #!groovy

    import jenkins.model.*
    import com.cloudbees.plugins.credentials.*
    import com.cloudbees.plugins.credentials.common.*
    import com.cloudbees.plugins.credentials.domains.*
    import com.cloudbees.plugins.credentials.impl.*
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
    import hudson.plugins.sshslaves.*;

    // Get master credential store
    domain = Domain.global()
    store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()


    // Add user/password credentials to global scope
    Credentials registryCreds = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "my-credential-id", "My credential description", "my_user", "my_pass")
    store.addCredentials(domain, registryCreds)


    // Add private ssh keys from master fs to global scope
    privateRepoKeys = ["my-key-1", "my-key-2"]

    privateRepoKeys.each {
    privateKey = new BasicSSHUserPrivateKey(
    CredentialsScope.GLOBAL,
    "jenkins-${it}",
    "jenkins",
    new BasicSSHUserPrivateKey.FileOnMasterPrivateKeySource("/var/jenkins_home/.ssh/${it}"),
    "",
    "Jenkins ${it} Key"
    )

    store.addCredentials(domain, privateKey)
    }
  17. @fishi0x01 fishi0x01 revised this gist Jan 12, 2019. 1 changed file with 9 additions and 9 deletions.
    18 changes: 9 additions & 9 deletions githubOAuth.groovy
    Original file line number Diff line number Diff line change
    @@ -2,30 +2,30 @@

    /***********************************************
    * This script configures Github OAuth access
    * in Jenkins.
    * in Jenkins. It uses a global authorization
    * Matrix strategy as authorization configurtion.
    * This script requires the Gibhub Authentication
    * plugin (github-oauth) to be installed. It is
    * tested with github-oauth:0.29
    ***********************************************/

    import hudson.security.SecurityRealm
    import org.jenkinsci.plugins.GithubSecurityRealm
    import jenkins.model.*
    import hudson.security.*
    import hudson.model.User
    import hudson.model.UserProperty

    // OAUTH Realm
    // Setup OAUTH Realm
    String githubWebUri = GithubSecurityRealm.DEFAULT_WEB_URI
    String githubApiUri = GithubSecurityRealm.DEFAULT_API_URI
    String oauthScopes = 'read:org,user:email' //GithubSecurityRealm.DEFAULT_OAUTH_SCOPES
    String clientID = System.getenv()['GITHUB_OAUTH_CLIENT_ID']
    String clientSecret = System.getenv()['GITHUB_OAUTH_CLIENT_SECRET']
    String clientID = System.getenv()['GITHUB_OAUTH_CLIENT_ID'] // TODO: get from credential store
    String clientSecret = System.getenv()['GITHUB_OAUTH_CLIENT_SECRET'] // TODO: get from credential store

    SecurityRealm github_realm = new GithubSecurityRealm(githubWebUri, githubApiUri, clientID, clientSecret, oauthScopes)
    Jenkins.instance.setSecurityRealm(github_realm)


    // Auth Matrix
    // Create global authorization matrix
    def strategy = new GlobalMatrixAuthorizationStrategy()
    strategy.add(Jenkins.ADMINISTER, "admin")

    // Give admin access to fishi0x01 user
    strategy.add(Jenkins.ADMINISTER, "fishi0x01")
  18. @fishi0x01 fishi0x01 revised this gist Jan 12, 2019. 2 changed files with 39 additions and 1 deletion.
    38 changes: 38 additions & 0 deletions githubOAuth.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #!groovy

    /***********************************************
    * This script configures Github OAuth access
    * in Jenkins.
    ***********************************************/

    import hudson.security.SecurityRealm
    import org.jenkinsci.plugins.GithubSecurityRealm
    import jenkins.model.*
    import hudson.security.*
    import hudson.model.User
    import hudson.model.UserProperty

    // OAUTH Realm
    String githubWebUri = GithubSecurityRealm.DEFAULT_WEB_URI
    String githubApiUri = GithubSecurityRealm.DEFAULT_API_URI
    String oauthScopes = 'read:org,user:email' //GithubSecurityRealm.DEFAULT_OAUTH_SCOPES
    String clientID = System.getenv()['GITHUB_OAUTH_CLIENT_ID']
    String clientSecret = System.getenv()['GITHUB_OAUTH_CLIENT_SECRET']

    SecurityRealm github_realm = new GithubSecurityRealm(githubWebUri, githubApiUri, clientID, clientSecret, oauthScopes)
    Jenkins.instance.setSecurityRealm(github_realm)


    // Auth Matrix
    def strategy = new GlobalMatrixAuthorizationStrategy()
    strategy.add(Jenkins.ADMINISTER, "admin")

    // Give admin access to fishi0x01 user
    strategy.add(Jenkins.ADMINISTER, "fishi0x01")

    // Give admin access to my_team_name
    strategy.add(Jenkins.ADMINISTER, "my_company_id*my_team_name")

    // wrap up
    Jenkins.instance.setAuthorizationStrategy(strategy)
    Jenkins.instance.save()
    2 changes: 1 addition & 1 deletion init.groovy
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    #!groovy

    /***********************************************
    * This file is desiganted for the init.groovy.d
    * This script is designated for the init.groovy.d
    * directory to be executed at startup time of the
    * Jenkins instance.
    ***********************************************/
  19. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 2 changed files with 0 additions and 83 deletions.
    37 changes: 0 additions & 37 deletions ConfigurationAndSeedingPipeline.groovy
    Original file line number Diff line number Diff line change
    @@ -1,37 +0,0 @@
    node('master') {
    stage('Checkout') {
    // Clean workspace and checkout shared library repository on the jenkins master
    cleanWs()
    checkout scm
    }

    stage('Credentials') {
    // groovy script to configure and load credentials such as ssh keys
    load('resources/config/credentials.groovy')
    }

    stage('Auth') {
    // groovy script to configure the authentication (e.g., OAuth)
    load('resources/config/auth.groovy')
    }

    stage('Slaves') {
    // groovy script to configure the jenkins slaves
    load('resources/config/slaves.groovy')
    }

    stage('Shared Pipelines') {
    // groovy script to configure the shared library repository as a global shared library within jenkins
    load('resources/config/globalSharedPipelines.groovy')
    }

    stage('General Settings') {
    // groovy script for some general settings (e.g., UI theme)
    load('resources/config/generalSettings.groovy')
    }

    stage('Seed') {
    // seed the jobs
    jobDsl(targets: 'resources/jobDSL/*.groovy', sandbox: false)
    }
    }
    46 changes: 0 additions & 46 deletions ConfigurationPipelineDSL.groovy
    Original file line number Diff line number Diff line change
    @@ -1,46 +0,0 @@
    #!groovy

    // This jobDSL script creates and Admin/Configure pipeline, which will act as
    // our seeding and configuration pipeline for Jenkins. The Admin/Configure
    // pipeline uses a shared central library hosted on GitHub.

    folder('Admin') {
    description('Folder containing configuration, bootstrapping and seed jobs')
    }

    pipelineJob("Admin/Configure") {
    parameters {
    // We can select a branch of the shared library which we want to use for seeding/configuration
    gitParam('revision') {
    type('BRANCH_TAG')
    sortMode('ASCENDING_SMART')
    defaultValue('origin/master')
    }
    }

    triggers {
    githubPush()
    }

    logRotator {
    numToKeep(50)
    }

    definition {
    cpsScm {
    scm {
    git {
    remote {
    github("my-org/jenkins-shared-libraries", "ssh")
    credentials("shared-libraries-deploy-key")
    }

    branch('$revision')
    }
    }

    // This is the config/seed pipeline within the shared repo
    scriptPath('resources/init/ConfigurationAndSeedingPipeline.groovy')
    }
    }
    }
  20. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions ConfigurationAndSeedingPipeline.groovy
    Original file line number Diff line number Diff line change
    @@ -6,22 +6,27 @@ node('master') {
    }

    stage('Credentials') {
    // groovy script to configure and load credentials such as ssh keys
    load('resources/config/credentials.groovy')
    }

    stage('Auth') {
    // groovy script to configure the authentication (e.g., OAuth)
    load('resources/config/auth.groovy')
    }

    stage('Slaves') {
    // groovy script to configure the jenkins slaves
    load('resources/config/slaves.groovy')
    }

    stage('Shared Pipelines') {
    // groovy script to configure the shared library repository as a global shared library within jenkins
    load('resources/config/globalSharedPipelines.groovy')
    }

    stage('General Settings') {
    // groovy script for some general settings (e.g., UI theme)
    load('resources/config/generalSettings.groovy')
    }

  21. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 1 changed file with 32 additions and 0 deletions.
    32 changes: 32 additions & 0 deletions ConfigurationAndSeedingPipeline.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    node('master') {
    stage('Checkout') {
    // Clean workspace and checkout shared library repository on the jenkins master
    cleanWs()
    checkout scm
    }

    stage('Credentials') {
    load('resources/config/credentials.groovy')
    }

    stage('Auth') {
    load('resources/config/auth.groovy')
    }

    stage('Slaves') {
    load('resources/config/slaves.groovy')
    }

    stage('Shared Pipelines') {
    load('resources/config/globalSharedPipelines.groovy')
    }

    stage('General Settings') {
    load('resources/config/generalSettings.groovy')
    }

    stage('Seed') {
    // seed the jobs
    jobDsl(targets: 'resources/jobDSL/*.groovy', sandbox: false)
    }
    }
  22. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 3 changed files with 47 additions and 47 deletions.
    46 changes: 46 additions & 0 deletions ConfigurationPipelineDSL.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    #!groovy

    // This jobDSL script creates and Admin/Configure pipeline, which will act as
    // our seeding and configuration pipeline for Jenkins. The Admin/Configure
    // pipeline uses a shared central library hosted on GitHub.

    folder('Admin') {
    description('Folder containing configuration, bootstrapping and seed jobs')
    }

    pipelineJob("Admin/Configure") {
    parameters {
    // We can select a branch of the shared library which we want to use for seeding/configuration
    gitParam('revision') {
    type('BRANCH_TAG')
    sortMode('ASCENDING_SMART')
    defaultValue('origin/master')
    }
    }

    triggers {
    githubPush()
    }

    logRotator {
    numToKeep(50)
    }

    definition {
    cpsScm {
    scm {
    git {
    remote {
    github("my-org/jenkins-shared-libraries", "ssh")
    credentials("shared-libraries-deploy-key")
    }

    branch('$revision')
    }
    }

    // This is the config/seed pipeline within the shared repo
    scriptPath('resources/init/ConfigurationAndSeedingPipeline.groovy')
    }
    }
    }
    46 changes: 0 additions & 46 deletions configurationPipelineDSL.groovy
    Original file line number Diff line number Diff line change
    @@ -1,46 +0,0 @@
    #!groovy

    // This jobDSL script creates and Admin/Configure pipeline, which will act as
    // our seeding and configuration pipeline for Jenkins. The Admin/Configure
    // pipeline uses a shared central library hosted on GitHub.

    folder('Admin') {
    description('Folder containing configuration, bootstrapping and seed jobs')
    }

    pipelineJob("Admin/Configure") {
    parameters {
    // We can select a branch of the shared library which we want to use for seeding/configuration
    gitParam('revision') {
    type('BRANCH_TAG')
    sortMode('ASCENDING_SMART')
    defaultValue('origin/master')
    }
    }

    triggers {
    githubPush()
    }

    logRotator {
    numToKeep(50)
    }

    definition {
    cpsScm {
    scm {
    git {
    remote {
    github("fishi0x01/my-shared-jenkins-libs", "ssh")
    credentials("shared-libraries-deploy-key")
    }

    branch('$revision')
    }
    }

    // This is the config/seed pipeline within the shared repo
    scriptPath('resources/init/ConfigurationAndSeedingPipeline.groovy')
    }
    }
    }
    2 changes: 1 addition & 1 deletion init.groovy
    Original file line number Diff line number Diff line change
    @@ -29,7 +29,7 @@ def privateKey = new BasicSSHUserPrivateKey(
    store.addCredentials(domain, privateKey)

    // Create the configuration pipeline from a jobDSL script
    def jobDslScript = new File('/var/jenkins_home/init-dsl/admin.groovy')
    def jobDslScript = new File('/var/jenkins_home/init-dsl/ConfigurationPipelineDSL.groovy')
    def workspace = new File('.')
    def jobManagement = new JenkinsJobManagement(System.out, [:], workspace)
    new DslScriptLoader(jobManagement).runScript(jobDslScript.text)
  23. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions init.groovy
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    #!groovy

    /***********************************************
    * This file is desiganted for the init.groovy.d
    * directory to be executed at startup time of the
  24. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 1 changed file with 46 additions and 0 deletions.
    46 changes: 46 additions & 0 deletions configurationPipelineDSL.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    #!groovy

    // This jobDSL script creates and Admin/Configure pipeline, which will act as
    // our seeding and configuration pipeline for Jenkins. The Admin/Configure
    // pipeline uses a shared central library hosted on GitHub.

    folder('Admin') {
    description('Folder containing configuration, bootstrapping and seed jobs')
    }

    pipelineJob("Admin/Configure") {
    parameters {
    // We can select a branch of the shared library which we want to use for seeding/configuration
    gitParam('revision') {
    type('BRANCH_TAG')
    sortMode('ASCENDING_SMART')
    defaultValue('origin/master')
    }
    }

    triggers {
    githubPush()
    }

    logRotator {
    numToKeep(50)
    }

    definition {
    cpsScm {
    scm {
    git {
    remote {
    github("fishi0x01/my-shared-jenkins-libs", "ssh")
    credentials("shared-libraries-deploy-key")
    }

    branch('$revision')
    }
    }

    // This is the config/seed pipeline within the shared repo
    scriptPath('resources/init/ConfigurationAndSeedingPipeline.groovy')
    }
    }
    }
  25. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. No changes.
  26. @fishi0x01 fishi0x01 revised this gist Jan 5, 2019. 1 changed file with 33 additions and 0 deletions.
    33 changes: 33 additions & 0 deletions init.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    /***********************************************
    * This file is desiganted for the init.groovy.d
    * directory to be executed at startup time of the
    * Jenkins instance.
    ***********************************************/

    import javaposse.jobdsl.dsl.DslScriptLoader
    import javaposse.jobdsl.plugin.JenkinsJobManagement
    import jenkins.model.Jenkins
    import com.cloudbees.plugins.credentials.domains.Domain
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
    import com.cloudbees.plugins.credentials.CredentialsScope


    // Add deploy key for the centrally shared pipeline and configuration repository
    def domain = Domain.global()
    def store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
    def keyFileContents = new File("/var/jenkins_home/.ssh/shared-libraries-deploy-key").text
    def privateKey = new BasicSSHUserPrivateKey(
    CredentialsScope.GLOBAL,
    "shared-libraries-deploy-key",
    "root",
    new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(keyFileContents),
    "",
    "SSH key for shared-libraries"
    )
    store.addCredentials(domain, privateKey)

    // Create the configuration pipeline from a jobDSL script
    def jobDslScript = new File('/var/jenkins_home/init-dsl/admin.groovy')
    def workspace = new File('.')
    def jobManagement = new JenkinsJobManagement(System.out, [:], workspace)
    new DslScriptLoader(jobManagement).runScript(jobDslScript.text)
  27. @fishi0x01 fishi0x01 created this gist Jan 30, 2017.
    35 changes: 35 additions & 0 deletions manageCredentials.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    #!groovy

    import jenkins.model.*
    import com.cloudbees.plugins.credentials.*
    import com.cloudbees.plugins.credentials.common.*
    import com.cloudbees.plugins.credentials.domains.*
    import com.cloudbees.plugins.credentials.impl.*
    import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
    import hudson.plugins.sshslaves.*;

    // Get master credential store
    domain = Domain.global()
    store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()


    // Add user/password credentials to global scope
    Credentials registryCreds = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "my-credential-id", "My credential description", "my_user", "my_pass")
    store.addCredentials(domain, registryCreds)


    // Add private ssh keys from master fs to global scope
    privateRepoKeys = ["my-key-1", "my-key-2"]

    privateRepoKeys.each {
    privateKey = new BasicSSHUserPrivateKey(
    CredentialsScope.GLOBAL,
    "jenkins-${it}",
    "jenkins",
    new BasicSSHUserPrivateKey.FileOnMasterPrivateKeySource("/var/jenkins_home/.ssh/${it}"),
    "",
    "Jenkins ${it} Key"
    )

    store.addCredentials(domain, privateKey)
    }
    27 changes: 27 additions & 0 deletions manageGlobalEnvVars.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    #!groovy

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

    instance = Jenkins.getInstance()
    globalNodeProperties = instance.getGlobalNodeProperties()

    envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)

    newEnvVarsNodeProperty = null
    envVars = null

    if (envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0) {
    newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
    globalNodeProperties.add(newEnvVarsNodeProperty)
    envVars = newEnvVarsNodeProperty.getEnvVars()
    } else {
    envVars = envVarsNodePropertyList.get(0).getEnvVars()
    }

    envVars.put("MY_ENV_VAR", "MyEnvVar")
    envVars.put("MY_ENV_VAR_FROM_HOST_SYSTEM", System.getenv()['HOST_SYSTEM_ENV_VAR'])

    instance.save()
    44 changes: 44 additions & 0 deletions managePlugins.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    #!groovy

    import jenkins.model.*
    import java.util.logging.Logger

    /*
    FIXME: This script still triggers a lot of restarts until everything is
    properly installed...
    */

    def logger = Logger.getLogger("")
    def installed = false
    def initialized = false

    def pluginParameter="plugin-id-1 plugin-id-2 plugin-id-3"
    def plugins = pluginParameter.split()
    logger.info("" + plugins)
    def instance = Jenkins.getInstance()
    def pm = instance.getPluginManager()
    def uc = instance.getUpdateCenter()
    uc.updateAllSites()

    plugins.each {
    logger.info("Checking " + it)
    if (!pm.getPlugin(it)) {
    logger.info("Looking UpdateCenter for " + it)
    if (!initialized) {
    uc.updateAllSites()
    initialized = true
    }
    def plugin = uc.getPlugin(it)
    if (plugin) {
    logger.info("Installing " + it)
    plugin.deploy()
    installed = true
    }
    }
    }

    if (installed) {
    logger.info("Plugins installed, initializing a restart!")
    instance.save()
    instance.doSafeRestart()
    }
    18 changes: 18 additions & 0 deletions manageSecurity.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    #!groovy

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

    def instance = Jenkins.getInstance()

    // Create user account
    def hudsonRealm = new HudsonPrivateSecurityRealm(false)
    hudsonRealm.createAccount("my_user", "my_pass")
    instance.setSecurityRealm(hudsonRealm)

    // Enable matrix auth strategy and set my_user as admin
    def strategy = new GlobalMatrixAuthorizationStrategy()
    strategy.add(Jenkins.ADMINISTER, "my_user")
    instance.setAuthorizationStrategy(strategy)

    instance.save()
    33 changes: 33 additions & 0 deletions manageSlaves.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    #!groovy

    import jenkins.model.*
    import hudson.model.*
    import hudson.slaves.*
    import hudson.plugins.sshslaves.*
    import java.util.ArrayList;
    import hudson.slaves.EnvironmentVariablesNodeProperty.Entry;

    // Prepare env vars for slave node
    List<Entry> env = new ArrayList<Entry>();
    env.add(new Entry("key1","value1"))
    env.add(new Entry("key2","value2"))
    EnvironmentVariablesNodeProperty envPro = new EnvironmentVariablesNodeProperty(env);

    // Define slave to be bootstrapped by master
    Slave slave = new DumbSlave(
    "my-slave-id",
    "My slave description",
    "/path/to/slave/workdir",
    "4", // # of executors
    Node.Mode.EXCLUSIVE,
    "slave-label",
    new SSHLauncher(System.getenv()['MY_SLAVE_ADDRESS'], 22, SSHLauncher.lookupSystemCredentials("my-slave-ssh-key-credential-id"), "", null, null, "", "", 60, 3, 15),
    new RetentionStrategy.Always(),
    new LinkedList()
    )

    // Add env vars to slave
    slave.getNodeProperties().add(envPro)

    // Save slave
    Jenkins.instance.addNode(slave)
    22 changes: 22 additions & 0 deletions manageTools.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    #!groovy

    import hudson.tasks.Maven.MavenInstallation;
    import hudson.tools.InstallSourceProperty;
    import hudson.tools.ToolProperty;
    import hudson.tools.ToolPropertyDescriptor;
    import hudson.util.DescribableList;

    // Install maven tool
    def mavenDesc = jenkins.model.Jenkins.instance.getExtensionList(hudson.tasks.Maven.DescriptorImpl.class)[0]

    def isp = new InstallSourceProperty()
    def autoInstaller = new hudson.tasks.Maven.MavenInstaller("3.3.9")
    isp.installers.add(autoInstaller)

    def proplist = new DescribableList<ToolProperty<?>, ToolPropertyDescriptor>()
    proplist.add(isp)

    def installation = new MavenInstallation("M3", "", proplist)

    mavenDesc.setInstallations(installation)
    mavenDesc.save()