mardi 4 juin 2019

Jenkins pipeline: Execute multiple sh commands If value in parameters is not empty

I want to know how can I execute multiple sh commands in groovy Jenkinsfile depending in the amount of parameters entered in "build with parameters entry" for example If I have this:

enter image description here

Now Im using this code to execute following sh command and it´s working If I enter one URL.:

def urlcf1 = params.URL1
def urlcf2 = params.URL2
node {

      stage('purge URL content in cloudflare') {

        withCredentials([usernamePassword(credentialsId: 'xxxxxxxxx-xxxxxxxx-yyyyyyyyy', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {

        sh ("""curl -X POST "https://api.clo.com/client/v4/zones/xxxxxxxxxxxxxxxxxxxxxxx/purge_cache" \
        -H "X-Auth-Email: $USER" \
        -H "X-Auth-Key: $PASSWORD" \
        -H "Content-Type: application/json" \
        --data '{"files":["${urlcf1}",{"url":"${urlcf1}","headers":{"Origin":"cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}' """)


    }

      }



}

but what if I want to Have more than one URL? "URL 3" "URL 4" "URL 5" in build with parameters and depending the amount of URLs I enter, the command is executed that number of times for each of those URLS. For ex, If I access 2 URL and leave 3 empty, commands executes only 2 times with those 2 URL. Maybe using a "while" statement? or maybe "if not empty"? I tried this last one with only one URL but got error. this is the code:

def urlcf1 = params.URL1
def urlcf2 = params.URL2

node {

      stage('purge URL content in cloudflare') {

        withCredentials([usernamePassword(credentialsId: 'xxxxxxxxxxxxxxxx-xxxxxxxxxxxxx', usernameVariable: 'USER', passwordVariable: 'PASSWORD')]) {

        if (urlcf1 =! null) {

        sh ("""curl -X POST "https://api.cloudflare.com/client/v4/zones/xxxxxxxxxxxxxxxxxxxxx/purge_cache" \
        -H "X-Auth-Email: $USER" \
        -H "X-Auth-Key: $PASSWORD" \
        -H "Content-Type: application/json" \
        --data '{"files":["${urlcf1}",{"url":"${urlcf1}","headers":{"Origin":"cloudflare.com","CF-IPCountry":"US","CF-Device-Type":"desktop"}}]}' """)

        else (echo "Value cannot be empty ")

        }
    }

      }



}

and got:

enter image description here

Aucun commentaire:

Enregistrer un commentaire