This course is from PluralSight Automating Jenkins with Groovy
.
这里不是讲如何编写declarative pipeline, 而是对Jenkins进行本地化配置, by Groovy script.
使用 Groovy 操控Jenkins API 去替代一些重复的UI 操作,就是从API 层面去使用jenkins,比如schedule job等等,甚至改变一些系统设置,毕竟Jenkins 也是Java 应用。
除了对Jenkinsfile 进行 version control, 对Jenkins本身的配置,也可以,这时候就需要Groovy script帮忙了. 在哪里去Run groovy script呢? https://foxutech.com/how-to-run-groovy-script-in-jenkins/
- Groovy Plugin
- Jenkins Script Console
- Scriptler Plugins
第1, 2个接下来👇都提到了。
Jenkins Configure Groovy
Install Groovy plug-in from Jenkins Plugin Manager, search Groovy
in Available section.
You can also run Groovy script in Manage Jenkins
-> Script Console
, you can write system script
here, for example:
1 | // default packages are imported |
还可以用groovy 调用API 去读取设置的Parameters, then use them in script. The jenkins API documention is in: https://javadoc.jenkins.io/ Hudson的名字由来是历史原因.
You can put this inline script in freestyle project
, go to configure -> Build
, there are 2 options about Groovy:
- Execute Groovy Script:
non-system
script, has less security freight, do jobs that out of jenkins internals. - Execute System Groovy Script: To run
system script
, you need to be admin (unchecked use groovy sandbox) or be approved by admin.
Groovy Startup Script
Configuration as code, the startup script will be executed after Jenkins starts immediately to set userful properties.
Create init.groovy.d
folder under /var/lib/jenkins
and put the script 1_config.groovy
in it:
1 | import jenkins.model.*; |
on the browser, type http://localhost:8080/restart
, after restart Jenkins, you will see the difference, the checkbox is gone.
Grape is the package manager for Groovy: http://docs.groovy-lang.org/latest/html/documentation/grape.html
Creating Builds
这里主要说了declarative pipeline 的Jenkinsfile, 如同工作中用到的,大量的Groovy functions.
Credentials and Users
You can do the same job on UI, here show you how to do it via script.
Credentials
: used by Jenkins to access something outsideUsers
: for users to login Jenkins
This Groovy script will create, delete and list Jenkins user:
1 | import hudson.model.User; |
Create credentials in script:
1 | import com.cloudbees.plugins.credentials.*; |