# Groovy Hook Script and Jenkins Configuration as Code

This post discusses Groovy Hook Scripts and how to use them for full configuration-as-code in Jenkins with Docker, Pipeline. This can help us to set up local environment for developing Jenkins Pipeline libraries and to evaluate various Jenkins features.

### Groovy Hook Scripts

These scripts are written in Groovy, and get executed inside the same JVM as Jenkins, allowing full access to the domain model of Jenkins. For a given hook HOOK, the following locations are searched:

The init is the most commonly used hook (i.e., HOOK=init). The following sections show how some of the most common tasks and configurations in Jenkins can be achieved by using such Groovy scripts. For example, in this project, many of such scripts are added into a Dockerized Jenkins master and executed when starting a container to replicate configurations of the Jenkins instance in production. It will give us ability to quickly spin up local Jenkins instances for development or troubleshooting issues in production Jenkins.

On a side note, IntelliJ IDEA is probably the best development tool for working with these Groovy Scripts. Check out these instructions on how to set it up in IntelliJ. UPDATED ON 2018/09/29: More on IntelliJ setup is discussed in this blog post.

### Authorization

This section shows how to enable different authorization strategies in Groovy code.

Matrix-based authorization: Gives all authenticated users admin access:

For importing GlobalMatrixAuthorizationStrategy class, make sure that matrix-auth plugin is installed. For full list of standard permissions in the matrix, see this code snippet. Note that the matrix can be different if different plugins are installed. For example, the “Replay” permission for Runs is not simply hudson.model.Run.REPLAY since there is no such static constant. Such permission is only available after Workflow CPS plugin is installed. Therefore, we can only set “Replay” permission for Runs with the following:

References

### Basic Jenkins security

In addition to enable authorization strategy, we should also set some basic configurations for hardening Jenkins. Those includes various options that you see in Jenkins UI when going to Manage Jenkins > Configure Global Security.

• Disable Jenkins CLI
• Limit Jenkins agent protocols.
• “Enable Slave -> Master Access Control”
• “Prevent Cross Site Request Forgery exploits”

Some are not working for versions before 2.46, according to this. For disabling Jenkins CLI, you can simply add the java argument -Djenkins.CLI.disabled=true on Jenkins startup.

References

### Create different kinds of Credentials

Adding Credentials to a new, local Jenkins for development or troubleshooting can be a daunting task. However, with the following scripts and the right setup (NEVER commit your secrets into VCS), developers can automate adding the required Credentials into the new Jenkins.