Gitlab14从搭建到落地CICD(一)

前期准备

参考我的上一篇文章: https://blog.csdn.net/qq_27070443/article/details/119824967

# 已知路径
/usr/local/apache-maven-3.6.3
/usr/local/jdk8u262-b10

# 配置路径
cd /usr/local && ln -s ./apache-maven-3.6.3 maven3
cd /usr/local && ln -s ./jdk8u262-b10 jdk8

vi /etc/profile.d/maven3.sh
-----
MAVEN_HOME=/usr/local/maven3
export PATH=${MAVEN_HOME}/bin:$PATH

vi /etc/profile.d/jdk8.sh
-----
JAVA_HOME=/usr/local/jdk8
export PATH=${JAVA_HOME}/bin:$PATH

# 配置生效
source /etc/profile

# 注意了!!! runner所在的机器, 上面相关的编译环境一定要安装全

GitLab:安装

# 前提依赖
yum install policycoreutils-python -y

# 路径说明
/var/opt/gitlab		应用数据
/var/log/gitlab		日志
/etc/gitlab	    	配置文件

# 默认密码所在路径
cat /etc/gitlab/initial_root_password

# 美化汉化配置
User Settings -> Preferences

## Syntax highlighting theme -> Solarized Light
## Behavior -> Layout width -> fluid
## Localization -> Language -> Chinese

Gitlab: 注册Runner(和我的上一篇文章一致)

cat /etc/gitlab-runner/config.toml

image.png

Gitlab: 初始化编译环境(和我的上一篇文章一致)

强烈建议先看我的上一篇文章, 仔细看完再来看这篇文章, 不然你可能会不知道你是谁你在哪

我擦, 14的admin控制台不见了, 怎么找Runner注册地址?

image.png
image.png

Gitlab: Runner运行

gitlab-runner start

# 查看各个Runner的状态
gitlab-runner list

Gitlab: 获取个人访问令牌, 也就是9.x版本里头的AccessToken(我这里为了避免出bug直接用的root)

image.png
image.png

这样我们就获得了这个gitlab节点内所有api的访问权限, token=s99mpKjDsKKwBshv5JMg

Gitlab: 外部可控

<dependency>
    <groupId>org.gitlab4j</groupId>
    <artifactId>gitlab4j-api</artifactId>
    <version>4.17.0</version>
</dependency>

代码预览

gitlab:
  host-url: http://192.168.200.120
  access-token: s99mpKjDsKKwBshv5JMg
@Data
@Component
@ConfigurationProperties(prefix = "gitlab")
public class GitlabConnectProperties {
    /**
     * Gitlab服务器地址
     */
    private String hostUrl;
    /**
     * (个人/项目)访问令牌
     */
    private String accessToken;
}

@Slf4j
@RestController
@RequestMapping("/api/gitlab")
public class GitlabTestController {
    @Autowired
    private GitlabConnectProperties properties;

    @GetMapping(value = "/test")
    public ResponseEntity<Object> test() throws GitLabApiException {
        // Create a GitLabApi instance to communicate with your GitLab server
        GitLabApi gitLabApi = new GitLabApi(properties.getHostUrl(), properties.getAccessToken());
        // Get the list of projects your account has access to
        List<Project> projects = gitLabApi.getProjectApi().getProjects();
        log.info("项目列表: {}", JSON.toJSONString(projects));
        return new ResponseEntity<>(HttpStatus.OK);
   }
}

完整思路如下

public class App {
    private final static String HOST_URL = "http://192.168.75.128";
    private final static String TOKEN = "S7cSWQHGzEQUund3XNdS";

    public static void main(String[] args) {
        GitLabApi gitLabApi = new GitLabApi(HOST_URL, TOKEN);
        try {
            // 项目
            List<Project> projects = gitLabApi.getProjectApi().getProjects();
            projects.forEach(o -> {
                System.out.println(o.getId());
                System.out.println(o.getName());
                System.out.println(o.getWebUrl());
                System.out.println(o.getHttpUrlToRepo());
                System.out.println(o.getSshUrlToRepo());
                System.out.println(o.getDescription());
                System.out.println(o.getVisibility());
            });
            System.out.println("\n\n==================== 分割线 ========================\n\n");
            int projectId = projects.stream().findFirst().get().getId();
            // 开发分支 dev, gitlab-ci触发部署; 生产分支 master/other, dev -> master -> GA
            // 合并
            MergeRequestParams mergeRequestParams = new MergeRequestParams();
            mergeRequestParams.withTitle("这里是标题1");
            mergeRequestParams.withDescription("这里是描述1");
            mergeRequestParams.withSourceBranch("dev");
            mergeRequestParams.withTargetBranch("master");
            MergeRequest mergeRequest = gitLabApi.getMergeRequestApi().createMergeRequest(projectId, mergeRequestParams);
            System.out.println(mergeRequest.getId());
            System.out.println(mergeRequest.getTitle());
            System.out.println(mergeRequest.getDescription());
            System.out.println(mergeRequest.getSourceBranch());
            System.out.println(mergeRequest.getTargetBranch());
            System.out.println(mergeRequest.getState());
            if (!"opened".equalsIgnoreCase(mergeRequest.getState())) {
                System.out.println("合并请求失败,冲突");
                return;
            }
            Thread.sleep(3000);
            // 确认合并
            MergeRequest mergeRequest1 = gitLabApi.getMergeRequestApi().acceptMergeRequest(projectId, mergeRequest.getIid());
            System.out.println(JSON.toJSONString(mergeRequest1));
            System.out.println("\n\n==================== 分割线 ========================\n\n");
            // 拉GA分支
            String branchName = String.format("GA_%s", DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss"));
            Branch branch = gitLabApi.getRepositoryApi().createBranch(projectId, branchName, "master");
            System.out.println(JSON.toJSONString(branch));
            System.out.println("\n\n==================== 分割线 ========================\n\n");
            // GA流水线(N个作业步骤)
            Pipeline pipeline = gitLabApi.getPipelineApi().createPipeline(projectId, branchName);
            System.out.println(pipeline.getId());
            System.out.println(pipeline.getCreatedAt());
            while (true) {
                // 结合多线程和websocket,即可实现实时"状态机"
                Pipeline currentPipeline = gitLabApi.getPipelineApi().getPipeline(projectId, pipeline.getId());
                if (PipelineStatus.PENDING.equals(currentPipeline.getStatus())) {
                    System.out.println("Pipeline Pending!");
                    Thread.sleep(2000);
                }
                if (PipelineStatus.RUNNING.equals(currentPipeline.getStatus())) {
                    System.out.println("Pipeline Running!");
                    Thread.sleep(2000);
                }
                if (PipelineStatus.SUCCESS.equals(currentPipeline.getStatus())) {
                    System.out.println("Pipeline Success!");
                    System.out.println(currentPipeline.getStartedAt());
                    System.out.println(currentPipeline.getFinishedAt());
                    System.out.println(currentPipeline.getDuration());
                    System.out.println(currentPipeline.getStatus());
                    break;
                }
            }
            System.out.println("\n\n==================== 分割线 ========================\n\n");
        } catch (GitLabApiException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

runner打包地址

/app/build/[runner名称]/0/[执行job的用户名称]/[项目名称]/[项目模块名称]/target/[项目模块jar、war包]

gitlab-ci环境变量参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌 烨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值