Home > Blockchain >  Map parameter to label
Map parameter to label

Time:05-31

I have a pipeline parameterized by env which takes specific values shown below. The parameter is used in the script and cannot change. But the admin tells me that the labels for the agent have to depend on the parameter env and another fixed one (e.G. LABELX).

The problem I encounter is that, while the script requires exactly the values shown below, the label for the agent is not always ${params.env}, but in one case there's a mapping/translation to be made.

This is the extremely reduced groovy script:

pipeline {
    agent {label "${params.env} && LABELX"}
    parameters {
        choice(
            name: 'env',
            choices: ['development', 'staging', 'production'],
        )
    }
    
    stages {
        stage('Process') {
            steps {
                sh """
                # use ${params.env} in bash script
                """"
            }
        }
    }
}

The mapping I need is as follows:

env label
development development
staging test
production production

How can I replace the parameter staging with the label test before choosing an agent? I cannot do that in a script, because scripts are run by agents... I have to somehow do this before, inside the ${params.env} maybe. Or do I need an additional parameter (params.label)?

CodePudding user response:

One way to solve it is to create a constant label mapping before your pipeline, and then use it in your pipeline to retrieve the needed value.
Something like:

LABELS = ['development':'development', 'staging':'test', 'production':'production']

pipeline {
    agent {
       label "${LABELS[params.env]} && LABELX"
    }
    parameters {
        choice(
            name: 'env',
            choices: ['development', 'staging', 'production'],
        )
    }
    stages {
        stage('Process') {
            steps {
                sh """
                # use ${params.env} in bash script
                """
            }
        }
    }
}

By the way, it is not recommended to call your parameter env as it may override or collide in some cases with the default env map that contains all the environment parameters of the job, including those defined in the environment directive.

  • Related