【问题标题】:jenkinsfile to autodetect the gitlab branchjenkinsfile 自动检测 gitlab 分支
【发布时间】:2019-04-02 15:17:42
【问题描述】:

这是我的场景,我在 gitlab 中有两个分支,“master”和 staging。

我需要整合 jenkinsfile,这样我就可以对 staging 和 master 分支使用相同的文件,但需要为每个分支执行不同的操作集

我想要做的是,如果标签推送被提交到暂存分支 jenkins 将构建 docker 文件,将其上传到 aws ecr 并在 aws ecs 暂存集群中启动一个新的 docker 实例,如果标签推送到 master分支它会将其部署到另一个实时集群中。

我使用“JENKINS PIPELINE”项目并在 jenkinsfile 中编写以下代码,但 env.BRANCH_NAME 始终返回空值。

if  (env.BRANCH_NAME == "staging") {


      def  serviceName       = ""
      def  taskFamily        = ""
      def  clusterName       = ""
      } else if  (env.BRANCH_NAME == "master") {

      def  serviceName       = ""
      def  taskFamily        = ""
      def  clusterName       = ""
      }

当使用“JENKINS MULTIBRANCH”管道项目时,它会扫描项目并自动识别所有分支,但似乎每个分支都有自己的 webhook。

我真的对 MULTIBRANCH JENKINS 感到困惑。我们应该在 gitlab 中配置 2 个不同的 webhook 吗?一个用于分期,另一个用于主控?当我们在 gitlab 中将 git tag push 到 staging 分支时,jenkins 会拉取并自动切换到 staging 分支吗?

看起来当我们在 gitlab 中向 staging 分支推送标签时,jenkins 正在从 staging 分支中提取 jenkinsfile,但在 master 分支中处理文件。

我们有什么方法可以使用“JENKINS PIPELINE”项目来代替“MULTI BRANCH”吗?

【问题讨论】:

  • 您使用的是scripted 还是declarative 类型的管道。如果是declarative,您可以尝试在script 块中添加此代码sn-p。
  • @SunilThorat 我猜它是声明性管道,你能不能再粘贴一次代码,因为我看不到它。

标签: jenkins gitlab jenkins-pipeline amazon-ecs


【解决方案1】:

在 GitLab 上看起来不是env.BRANCH_NAME,而是CI_COMMIT_REF_NAME

https://docs.gitlab.com/ee/ci/variables/#predefined-environment-variables

我用来验证 Jenkinsfile 中的环境变量的一个技巧是运行一个 shell 脚本命令来显示您的环境。比如sh printenv(假设你的Jenkins构建代理是基于Linux的)

【讨论】:

  • 谢谢,我会试试的。 env.BRANCH_NAME 在我使用 MULTIBRANCH JENKINS 作业时显示了正确的分支名称(我回显了变量),但是 if 条件不起作用。
【解决方案2】:

您可以使用“等于”函数代替“==”运算符myStringVar.equals(<someOtherValue>)

你的情况看起来像这样:-

if  (env.BRANCH_NAME.equals('staging')) {
  def  serviceName       = ""
  def  taskFamily        = ""
  def  clusterName       = ""
  } else if  (env.BRANCH_NAME.equals('master')) {
  def  serviceName       = ""
  def  taskFamily        = ""
  def  clusterName       = ""
  }

Ans 变量 env.BRANCH_NAME 将在多分支管道的情况下可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多