首页 > 解决方案 > Jenkins groovy 中的关系运算符

问题描述

我正在尝试在 Jenkins 中进行数值比较并基于此执行操作。COUNT是一个字符串类型参数。但它给出了以下错误。

WorkflowScript: 24: Expected a step @ line 24, column 14.
                if ( params.COUNT > 10 ) {
                ^
1 error
pipeline {
  agent {
    label "${node_label}"
  }
  parameters {
    string(defaultValue: "1", description: "Number of VM's to be Added", name: "COUNT")
  }
  stages {
    stage('Parameter Validation') {
      steps {
             if ( params.COUNT > 10 ) {
             error("Instance count should be less than 10 and it is ${COUNT}")
        } 
      }
    }
    stage('Clone Latest Repo') {
      steps {
        echo "Pull latest code"
        build 'gitpull'
      }
  }

我尝试了不同的方法,但没有运气

steps {
script {    
sh '''#!/bin/bash
if [[ "${COUNT}" -gt "10" ]]; then  
error("Instance count should be less than 10")
fi
'''
}
} 

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


我找到了一种将字符串变量类型转换为 INT 的方法def intValue = COUNT as int。此解决方案按预期工作

def intValue = COUNT as int
pipeline {
  stages {
    stage('Parameter Validation') {
      steps {
          script {
             if ( intValue > 10 ) {
             error("Instance count should be less than 10 and it is ${COUNT}")
            } 
        }
      }
    }
    stage('Clone Latest Repo') {
      steps {
        echo "Pull latest code"
        build 'gitpull'
      }
  }
}
}

推荐阅读