Search code examples
bashjenkinsgroovyjenkins-pipeline

jenkinsfile if statement not using wildcard statement


I'm trying to work out the correct syntax based on the below if statement in a jenkinsfile, however it's not passing the wildcard as expected and trying to match the syntax including the wildcard symbol:

stage('stage c') {
  steps {
    container('tf-jenkins') {
      script {
      sh """
      if [[ \$(gcloud container clusters list --format='value(name)' --project ${project_id} --filter=d-kcl-${short_region} ) = *d-kcl* ]]; then
        echo "cluster already exists, progressing to application deployment"
      else
        echo "no cluster found, a new cluster needs to be deployed"
      fi
      """
      }
    }

With the above stage block, the following is returned:

+ gcloud container clusters list '--format=value(name)' --project prpject-id '--filter=d-kcl'
+ '[[' paas-gcp-d-kcl-euwe2 '=' '*paas-gcp-d-kcl*' ]]
+ echo 'no cluster found, a new cluster needs to be deployed'
no cluster found, a new cluster needs to be deployed

When running in a normal shell this works as expected but not in the jenkinsfile.


Solution

  • I would recommend using groovy code instead of a shell script.

    stage('stage c') {
     steps {
       container('tf-jenkins') {
         script {
             def commandOutput = sh (
                                      script: "gcloud container clusters list --format='value(name)' --project ${project_id} --filter=d-kcl-${short_region}", 
                                      returnStdout: true,
                                      label: "Check if container exists"
                                   ).trim()
    
            if(commandOutput.contains("d-kcl")){
                echo "cluster already exists, progressing to application deployment"
            } else{
               echo "no cluster found, a new cluster needs to be deployed"
            }
          }
        }
      }
    }