目的:每提交一次代码即触发一次sonarqube完成代码扫描
一、基本认知
1、gitlab-ci
GitLab-CI就是一套配合GitLab使用的持续集成系统(当然,还有其它的持续集成系统,同样可以配合GitLab使用,比如Jenkins)。而且GitLab8.0以后的版本是默认集成了GitLab-CI并且默认启用的。
2、gitlab-runner
GitLab-Runner是配合GitLab-CI进行使用的。一般地,GitLab里面的每一个工程都会定义一个属于这个工程的软件集成脚本,用来自动化地完成一些软件集成工作。当这个工程的仓库代码发生变动时,比如有人push了代码,GitLab就会将这个变动通知GitLab-CI。这时GitLab-CI会找出与这个工程相关联的Runner,并通知这些Runner把代码更新到本地并执行预定义好的执行脚本。
Runner类型
GitLab-Runner可以分类两种类型:Shared Runner(共享型)和Specific Runner(指定型)。
Shared Runner:这种Runner(工人)是所有工程都能够用的。只有系统管理员能够创建Shared Runner。
Specific Runner:这种Runner(工人)只能为指定的工程服务。拥有该工程访问权限的人都能够为该工程创建specific runner。
二、安装gitlab-runner(可以在gitlab服务器上,也可以在别的服务器上)
1、下载包 gitlab-runner-12.7.0-1.x86_64.rpm ,地址:https://mirrors.tuna.tsinghua.edu.cn/gitlab-runner/yum/el7/
# yum install -y gitlab-runner-12.7.0-1.x86_64.rpm
或者直接下载源,在线安装。
# curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh | sudo bash # yum install gitlab-runner
2、注册gitlab-runner
① Shared Runner注册的url和token:
② Specific Runner注册的url和token:
③ 注册(shared runner)
# gitlab-runner register
[root@test2 SHELL]# gitlab-runner register Runtime platform arch=amd64 os=linux pid=53435 revision=d0b76032 version=12.0.2 Running in system-mode. Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/): http://172.16.19.104:10081/ #输入URL Please enter the gitlab-ci token for this runner: -rwbBw2y7GmL7smxuoxt #输入TOKEN Please enter the gitlab-ci description for this runner: [test2.laozios.com]: my-runner #后面脚本需要用到 Please enter the gitlab-ci tags for this runner (comma separated): sonar #后面脚本需要用到 Registering runner... succeeded runner=-rwbBw2y Please enter the executor: parallels, kubernetes, virtualbox, docker+machine, docker-ssh+machine, docker, docker-ssh, shell, ssh: shell #通过shell Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded!
④ 查看已注册的runner
三、编写.gitlab-ci.yml文件
sonar_preview: stage: test script: - /usr/local/sonar-scanner/bin/sonar-scanner -Dsonar.projectKey=java -Dsonar.sources=. -Dsonar.host.url=http://172.16.68.154:9000 -Dsonar.login=13585323c4c8ac257c590d6e49c7b59dda5192f8 only: - master tags: - my-runner
四、提交代码测试