5.Jenkins自动化

Jenkins 自动化任务

定时任务

比如,每天凌晨1点自动备份数据库。

选择Jenkins作业,进入Configure > Build Triggers > Build periodically
填写cron语法。cron是类Unix的操作系统下的基于时间的任务管理系统。

# 格式
# ┌──分(0 - 59)
# │ ┌──时(0 - 23)
# │ │ ┌──日(1 - 31)
# │ │ │ ┌─月(1 - 12)
# │ │ │ │ ┌─星期(0 - 6,表示从周日到周六)
# │ │ │ │ │
# *  *  *  * 

0 1 * * * # 每日 01:00

# using ‘H 1 * * *’ rather than ‘0 1 * * *’
# 可能有大量的job 被设定在每日01:00执行
#  H - jenkins可以自动安排执行顺序,减轻压力
H 1 * * *


* * * * * # 每分钟执行
# Do you really mean "every minute" when you say "* * * * *"? Perhaps you meant "H * * * *" to poll once per hour

修改任务为echo "hello world"

保存,等待1分钟

从外部触发Jenkins任务

安装 Strict Crumb Issue 插件:
  • Manage Jenkins > Manage Plugins > Available Tab
  • 在filter框内输入Crumb,找到Strict Crumb Issue,点击install
  • Restart Jenkins when installation is complete and no jobs are running
  • 安装完成后进入Installed Tab查看
启动 Strict Crumb Issue:

Manage Jenkins > Configure Global Security > CSRF Protection.

  • 选择 Strict Crumb Issuer.
  • Click on Advanced.
  • Uncheck the Check the session ID box.
  • Save it.

从Bash脚本触发Jenkins任务

右键点击Build Now,获取link:
http://10.0.0.215:8080/job/hello_world/build?delay=0sec

这个URL可以用来触发Jenkins任务,但是我们需要一些额外的token在 Jenkins 中称为crumb,crumb包含了标识发送请求的用户的信息。

# 获取crumb
curl -u "jenkins:1234" 'http://10.0.0.215:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)'
# Jenkins-Crumb:dcaad0c0555a9369b2874d4a6d8870b9f55d34510e9b2d537ef4cbd905ff7825

# 保存crumb
crumb=$(curl -u "jenkins:1234" -s 'http://10.0.0.215:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')

curl -u "jenkins:1234" -H "$crumb" -X POST http://10.0.0.215:8080/job/hello_world/build?delay=0sec

Git server hooks

Git server hook可以在Git服务器上执行自定义的任务。比如我们希望每次有新的代码提交到git repo之后,自动触发maven build & test。

登入Git服务器,定义hook

#找到 gitlab
docker ps

# 进入docker环境,与bash交互
docker exec -ti gitlab bash

# 找到项目对应的目录
cd /var/opt/gitlab/git-data/repositories

Gitlab默认使用了hashed storage,可以在 Main menu > Admin > Overview > Projects下
选中项目,找到 Gitaly relative path

cd @hashed/......git

Git server hooks可以定义 pre-receive, post-receive, update 等多种 Git server-side hooks

  • applypatch-msg
  • pre-applypatch
  • post-applypatch
  • pre-commit
  • prepare-commit-msg
  • commit-msg
  • post-commit
  • pre-rebase
  • post-checkout
  • post-merge
  • pre-receive
  • update
  • post-receive
  • post-update
  • pre-auto-gc
  • post-rewrite
  • pre-push
  • 如果只创建单个的server hook,创建一个名称与hook类型相符的文件。例如,对于一个预接收的server hook,文件名应该是pre-receive,没有扩展名。
  • 如果要创建多个server hook,为hook创建一个与hook类型相匹配的目录。例如,对于一个预接收的server hook,目录名称应该是pre-receive.d
# 新建custom_hooks目录
mkdir custom_hooks

cd  custom_hooks

vi post-receive

post-receive中写入

#! /bin/bash

crumb=$(curl -u "jenkins:1234" -s 'http://10.0.0.215:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')

curl -u "jenkins:1234" -H "$crumb" -X POST http://10.0.0.215:8080/job/maven-job/build?delay=0sec

保存,赋予执行权限

chmod u+x post-receive

Git Hook触发Jenkins任务

回到本地repo

cd workspace/maven

修改src/main/java/com/mycompany/app/App.java(Hello World! -> Hello 2023!)

package com.mycompany.app;

/**
 * Hello 2023!
 */
public class App
{

    private final String message = "Hello 2023!";

    public App() {}

    public static void main(String[] args) {
        System.out.println(new App().getMessage());
    }

    private final String getMessage() {
        return message;
    }

}

同样修改src/test/java/com/mycompany/app/AppTest.java (Hello World! -> Hello 2023!)

package com.mycompany.app;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import static org.junit.Assert.*;

/**
 * Unit test for simple App.
 */
public class AppTest
{

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

    @Test
    public void testAppConstructor() {
        try {
            new App();
        } catch (Exception e) {
            fail("Construction failed.");
        }
    }

    @Test
    public void testAppMain()
    {
        App.main(null);
        try {
            assertEquals("Hello 2023!" + System.getProperty("line.separator"), outContent.toString());
        } catch (AssertionError e) {
            fail("\"message\" is not \"Hello 2023!\"");
        }
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
    }

}

提交修改

git status

git add .

git commit -m "Hello 2023!"

git push origin main

查看Jenkins > maven-job 状态

拦截未通过测试的代码

修改src/test/java/com/mycompany/app/AppTest.java (Hello 2023! -> Hello World!)
故意使测试失败

package com.mycompany.app;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import static org.junit.Assert.*;

/**
 * Unit test for simple App.
 */
public class AppTest
{

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

    @Test
    public void testAppConstructor() {
        try {
            new App();
        } catch (Exception e) {
            fail("Construction failed.");
        }
    }

    @Test
    public void testAppMain()
    {
        App.main(null);
        try {
            assertEquals("Hello World!" + System.getProperty("line.separator"), outContent.toString());
        } catch (AssertionError e) {
            fail("\"message\" is not \"Hello World!\"");
        }
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
    }

}

提交修改

git status

git add .

git commit -m "test failure"

git push origin main

你可能感兴趣的:(jenkins,自动化,运维)