Jenkins Quick Start II

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
2
3
4
5
6
// default packages are imported
def svr = Jenkins.instance;
// get existing TEST job
def job = svr.getJob("TEST");
def sched= job.scheduleBuild2(0);
sched.get();

还可以用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
2
3
4
5
6
7
8
9
10
11
12
import jenkins.model.*;
import java.util.logging.Logger
// add change into logs
Logger logger = Logger.getLogger("")
logger.info "Executing init script"

// disable remember me checkbox
Jenkins.instance.setDisableRememberMe(true)
Jenkins.instance.setSystemMessage('Jenkins Server - Automating Jenkins with Groovy')
Jenkins.instance.save()

logger.info "Init script complete"

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 outside
  • Users: for users to login Jenkins

This Groovy script will create, delete and list Jenkins user:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import hudson.model.User;
import hudson.security.*

class UserManager
{
Set allUsers()
{
return User.getAll();
}

void createUser(String userName, String password){
if (!this.userExists(userName))
{
Jenkins instance = Jenkins.getInstance();
def realm = new HudsonPrivateSecurityRealm(false);

realm.createAccount(userName, password);
instance.setSecurityRealm(realm);
instance.save();
}
}

Boolean userExists(userName)
{
return User.get(userName) != null;
}

void deleteUser(String userId)
{
if (this.userExists(userId))
{
User u = User.get(userId);
u.delete();
}
}
}

def mgr = new UserManager();

mgr.createUser("test", "user");
mgr.deleteUser("test");

println(mgr.userExists("cbehrens"));

for (user in mgr.allUsers()){
println(user.id);
}

Create credentials in script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.common.*;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;

class CredentialManager
{
Set getAll()
{
return CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, Jenkins.instance, null, null);
}

void changePassword(String credentialId, String password){
println 'change password';
def creds = CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, Jenkins.instance, null, null);

def credential = creds.findResult { it.id == credentialId ? it : null };

if (credential != null)
{
def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()

def success = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
credential,
new UsernamePasswordCredentialsImpl(credential.scope, credential.id, credential.description, credential.username, password)
)

if (!success)
{
throw new RuntimeException("Changing password failed.");
}

println("password change complete");
}
}
}

def mgr = new CredentialManager()
mgr.changePassword("githubcreds", "password");
0%