我正在尝试配置 Jenkins Pipeline 来执行以下任务:
Git 实验室使用 Web Hook 启动 Jenkins 作业。
从 git 存储库中提取数据。 (完成)
启动 Docker 容器来测试 Angular 应用程序。 (完成)
下载 Google chrome 并安装在 docker 容器中。 (完成)
使用 Karma 运行 Angular 测试。 (完成)
检查提交是否已被标记为
Release
。 如果情况并非如此,请停止。
如果是这种情况,则部署应用程序来测试环境。
阻碍进展的因素:
我不知道如何检查 Git 提交是否被标记为
Release
或不。 如果标签中不存在标签,如何停止构建?
我还通过输出
GIT_COMMIT
env 变量注意到它始终为 null
echo "Commit: ${env.GIT_COMMIT}"
管道{
agent none
stages {
// Starge 1: Get the data from git
stage('Preparation') {
agent any
steps {
git branch: 'master', credentialsId: 'MY_CREDENTIALS', url: 'http://gitlab/root/test2.git'
}
}
// Stage 2: Build the image and test the repo
stage("Start docker and run the tests") {
agent {
//dockerfile true
docker {
//image 'node:latest'
image 'teracy/angular-cli'
args '-u root --network=gitlab_inet'
}
}
steps {
echo "Tag: ${env.BUILD_TAG}"
sh 'wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb &>/dev/null'
sh 'dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install'
sh 'rm -f google-chrome-stable_current_amd64*'
sh 'export CHROME_BIN=/usr/bin/google-chrome'
sh 'ng -v'
sh 'npm install && npm run test'
}
}
}
}
配置注意事项:
我正在使用 gitlab 并在 Jenkins 上使用 gitlab 插件。
管道注意事项
我知道使用自由样式构建我可以在
Refspec
字段内指定标签。但是我想构建一个管道并为每个构建生成一个 docker 容器。
我想这可以帮助你
pipeline {
agent any
stages {
stage ('Checkout') {
steps {
git branch: 'master', credentialsId: 'xxx', url: 'url-to-my-gitrepo.git'
}
}
stage ('Optional Deploy') {
when {
expression {
TAG = sh returnStdout: true, script: 'git tag --contains ' + "\$(git log --pretty=format:%h -n 1)" + ''
return TAG == 'Release'
}
}
steps {
echo 'Commit contains a tag RELEASE'
echo 'Deploying'
}
}
}
post {
always {
cleanWs()
}
}
}
这将首先检查您的主分支。然后它会经过一个表达式。我创建了一个变量
TAG
。该标签包含您提交上的标签。因此,为了理解,首先我将获取我的存储库的最后一次提交:
git log --pretty=format:%h -n 1
然后我将检查该特定提交上是否有标签,并修剪输出:
git tag --contains COMMITHASH.trim()
最后我要比较一下是否
TAG == 'Release'
。
如果是,它将进入下一个 steps
部分和 echo
这两件事,您可以开始部署。如果它与管道不匹配,则完成并清理帖子部分中的所有内容。
自 2018-04 起,有一个特殊的“stage-when-tag”指令:
标签
如果
变量与给定模式匹配,则执行该阶段。例如:TAG_NAME
如果提供了空模式,则如果when { tag "release-*" }
变量存在(与TAG_NAME
相同),该阶段将执行。buildingTag()