Jenkins: Cannot define variable in pipeline stage Jenkins: Cannot define variable in pipeline stage jenkins jenkins

Jenkins: Cannot define variable in pipeline stage


The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... } block, but as a result, you'll lose validation of syntax, parameters, etc within the script block.


I think error is not coming from the specified line but from the first 3 lines. Try this instead :

node {   stage("first") {     def foo = "foo"     sh "echo ${foo}"   }}

I think you had some extra lines that are not valid...

From declaractive pipeline model documentation, it seems that you have to use an environment declaration block to declare your variables, e.g.:

pipeline {   environment {     FOO = "foo"   }   agent none   stages {       stage("first") {           sh "echo ${FOO}"       }   }}


Agree with @Pom12, @abayer. To complete the answer you need to add script block

Try something like this:

pipeline {    agent any    environment {        ENV_NAME = "${env.BRANCH_NAME}"    }    // ----------------    stages {        stage('Build Container') {            steps {                echo 'Building Container..'                script {                    if (ENVIRONMENT_NAME == 'development') {                        ENV_NAME = 'Development'                    } else if (ENVIRONMENT_NAME == 'release') {                        ENV_NAME = 'Production'                    }                }                echo 'Building Branch: ' + env.BRANCH_NAME                echo 'Build Number: ' + env.BUILD_NUMBER                echo 'Building Environment: ' + ENV_NAME                echo "Running your service with environemnt ${ENV_NAME} now"            }        }    }}