实现目标

  • 提交代码自动构建,并把文件放到指定目录 (也可以上传到运维服务器,这里看自己选择)

前期准备

安装 gitlab_runner (二进制安装)

sudo chmod +x gitlab-runner

sudo ./gitlab-runner install --user=当前用户 --working-directory=/home/当前用户/gitlabRunner

sudo ./gitlab-runner start

工程目录

  • 目录
├── .gitlab-ci.yml
├── main.go
└── Makefile
  • .gitlab-ci.yml 内容
# 在每个任务执行前运行
before_script:
  - export VERSION=`echo ${CI_COMMIT_TAG} | awk -F"_" '{print $1}'`
stages:
  - test
  - build
# 定义 job
test:
  stage: test
  tags:
    - test
  script:
    - echo "我是 tast 任务"
    - echo "git 提交的 tag"
    - echo ${CI_COMMIT_TAG}
    - echo ${CI_PROJECT_NAME}
    - echo ${VERSION}
    - echo $GOPATH
  only:
    - tags
# 定义 job
build:
  stage: build
  tags:
    - test
  script:
    - echo "开始构建程序"
    - make pack ENV="prod" VERSION=${VERSION}
    - pwd
    - if [ ! -d "/home/当前用户/data/code/test_cli/tags/${VERSION}" ]; then
      mkdir -p "/home/当前用户/data/code/test_cli/tags/${VERSION}/";
      fi
    - mv ${CI_PROJECT_NAME}_${VERSION}.tar.gz /home/当前用户/data/code/test_cli/tags/${VERSION}/
  only:
    - tags
  • Makefile 内容
#环境变量
export VERSION=1.0.0
export ENV=prod
export PROJECT=test_ci
#变量
PWD=$(shell pwd)
OUT_DIR=$(PWD)/cmd
OUT_NAME=$(PROJECT)_$(VERSION)
OUT_FILE=$(OUT_DIR)/$(OUT_NAME)
MAIN_FILE=main.go
PACK_FILE=$(OUT_NAME).tar.gz

build:
	@echo "移除老项目"
	@ rm -rf $(OUT_DIR)/*
	@go build -o $(OUT_FILE) $(MAIN_FILE)
	@echo "构建项目成功 : " $(OUT_FILE)

run:build
	@# 执行pack前先执行一次build
	@echo "运行项目"
	@$(OUT_FILE)

pack:build
	@# 执行pack前先执行一次build
	tar -czvf $(PACK_FILE) -C $(OUT_DIR) .
	@echo "打包结束 :"

注册 gitlab_runner

  • 在要构建的项目里面找到 token

  • 注册一个 runner

[pc gitlabRunner]$ sudo ./gitlab-runner register
Runtime platform                                    arch=amd64 os=linux pid=5901 revision=4c96e5ad version=12.9.0
Running in system-mode.                            
                                                   
Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/):
http://192.168.2.28/   //gitlab 地址
Please enter the gitlab-ci token for this runner:
52KL2wic1AwfxffvRrRs   //项目Token
Please enter the gitlab-ci description for this runner:
ci                     //项目描述
Please enter the gitlab-ci tags for this runner (comma separated):
test                   //给当前runner 添加 tags 在 .gitlab-ci.yml中会用到
Registering runner... succeeded                     runner=52KL2wic
Please enter the executor: docker-ssh, parallels, ssh, docker-ssh+machine, kubernetes, custom, docker, shell, virtualbox, docker+machine:
shell
Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded! 
  • gitlab runner信息

运行代码

git commit -a -m "test"
git push
​
## 打tag
git tag -a "1.1.1" -m "test ci"
git push origin 1.1.1

结语

  • 发布流程有很多种,这里只是提供了一个简单的发布模式,其实发布方法不一定要最厉害最好,要最适合自己的团队才是最好的
  • 欢迎添加QQ一起讨论

联系 QQ: 3355168235