Jenkins Startup Hook Scripts - chaitanyavangalapudi/devops-scripts GitHub Wiki

Jenkins supports Groovy startup hook scripts to be set up that are executed during startup or if jenkins experiences boot failure. Since these scripts use the same JVM as Jenkins, we can set up a script that set up system properties directly or load from file.

The Groovy scripts are to be kept in the init.groovy.d directory and add jenkins.properties to your $JENKINS_HOME.

Copy the following groovy file under init.groovy.d:

load-properties.groovy file

import jenkins.model.Jenkins
import java.util.logging.LogManager

def logger = LogManager.getLogManager().getLogger("")

/* JENKINS_HOME environment variable is not reliable */
def jenkinsHome = Jenkins.instance.getRootDir().absolutePath

def propertiesFile = new File("${jenkinsHome}/jenkins.properties")

if (propertiesFile.exists()) {
    logger.info("Loading system properties from ${propertiesFile.absolutePath}")
    propertiesFile.withReader { r ->
        /* Loading java.util.Properties as defaults makes empty Properties object */
        def props = new Properties()
        props.load(r)
        props.each { key, value ->
            System.setProperty(key, value)
        }
    }
}

jenkins.properties file:

java.awt.headless=true
mail.smtp.starttls.enable=true
http_proxy=http://1.3.2.9:1234
https_proxy=http://1.3.2.9:1234

After this, restart jenkins and you can see the properties loaded by visiting $JENKINS_URL/systemInfo (e.g. http://localhost:8080/systemInfo) and see your system property defined.

This feature can be used for the scenarios where you need to configure TLS for SMTP. This is equilvalent to configuring JAVA OPTIONS using

JAVA_OPTIONS=-Dmail.smtp.starttls.enable=true

or

edit /etc/default/jenkins with

JAVA_ARGS="-Djava.awt.headless=true -Dmail.smtp.starttls.enable=true"

With Jenkins 2 SMTP Configuration, Uncheck Use SSL checkbox and configure init hook as stated above and your SMTP connections will work properly.

References: