Why? 我们为何需要这样的实践
在CI/CD实践中,我们的CD流水线往往分为多种环境,团队各个角色分别控制不同的环境。这就导致整个流水线经常需要向不同的环境部署不同版本的应用。
例如,测试人员需要把控QA环境,以便根据实际情况,决定测试任意一个版本(或分支)。
如果能够查看各环境下,当前所部署的应用的git分支、提交id、等与git记录有关的信息,便可以方便团队成员掌控各个部署环境的情况。
如果能够查看各环境下,当前所部署的应用的git分支、提交id、等与git记录有关的信息,便可以方便团队成员掌控各个部署环境的情况。
效果:
/info路径可以以json格式显示git相关的信息:
{
"git": {
"build": {
"host": "myserver-1",
"version": "0.0.1-SNAPSHOT",
"time": "2018-03-28T05:34:35Z",
"user": {
"name": "First Last",
"email": "username1@example.com"
}
},
"branch": "Fix_issue_68",
"commit": {
"message": {
"short": "Fix issue #68",
"full": "Fix issue #68"
},
"id": {
"describe": "v1.4.21-28-g32ff212-dirty",
"abbrev": "32ff212",
"full": "32ff212b9e2873fa4672f1b5dd41f67aca6e0731"
},
"time": "2018-03-28T05:13:53Z",
"user": {
"email": "username1@example.com",
"name": "First Last"
}
},
"closest": {
"tag": {
"name": "v1.4.21",
"commit": {
"count": "28"
}
}
},
"dirty": "true",
"remote": {
"origin": {
"url": "git@github.com:n0mer/gradle-git-properties.git"
}
},
"tags": "",
"total": {
"commit": {
"count": "93"
}
}
}
}
What? 原理解释:
- 利用gradle/maven 插件在build时读取.git目录下面的git记录信息, 根据信息生成git.properties文件并存放到resources根路径
- Springboot框架在启动时,如果发现resources根路径下有git.properties文件,则会自动生成并注入一个包含这些信息的bean,并且利用actuator机制将信息显示到/info。
How? 实操说明
1. 配置springboot
- 引入Actuator 的starter(以maven为例)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- git基本信息会默认开启,并可以在/info显示
如果需要显示全部git信息,需要在springboot配置中开启:
management.info.git.mode=full
actuator的/info配置
2. 配置gradle
引入gradle插件:
https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties
- 引入plugin:
plugins {
id "com.gorylenko.gradle-git-properties" version "2.0.0"
}
- 开启plugin:
apply plugin: "com.gorylenko.gradle-git-properties"
- 自定义显示内容
gitProperties {
//时间的显示格式
dateFormat = "yyyy-MM-dd'T'HH:mm Z"
//时区
dateFormatTimeZone = "GMT+8"
//自定义需要显示的信息
keys = ['git.branch','git.commit.id','git.commit.time','git.commit.user.name','git.build.version']
}