Vasyl Stepulo
Vasyl Stepulo

Reputation: 1603

Jenkins pipeline assign variable multiple times

Is it possible to re-assign the variable value a few times inside IF in one script block? I have a script block where I need to pass variable values to different environments:

script {
    if (env.DEPLOY_ENV == 'staging') {
        echo 'Run LUX-staging build'
        def ENV_SERVER = ['192.168.141.230']
        def UML_SUFFIX = ['stage-or']
        sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
        
        echo 'Run STAGE ADN deploy'
        def ENV_SERVER = ['192.168.111.30']
        def UML_SUFFIX = ['stage-sg']
        sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'                      
        
        echo 'Run STAGE SG deploy'
        def ENV_SERVER = ['stage-sg-pbo-api.example.com']
        def UML_SUFFIX = ['stage-ba']
        sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'                                              
    }
}

But I receive an error in Jenkins job on second variable assignment:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 80: The current scope already contains a variable of the name ENV_SERVER
@ line 80, column 11.
                    def ENV_SERVER = ['192.168.111.30']
         ^

WorkflowScript: 81: The current scope already contains a variable of the name UML_SUFFIX
 @ line 81, column 11.
                    def UML_SUFFIX = ['stage-sg']
         ^

Or perhaps any other ways to multiple assignment inside one IF part of script block.

Upvotes: 0

Views: 786

Answers (1)

apr_1985
apr_1985

Reputation: 1962

Using def defines the variable. This is only needed on the first call. so removing the def on the other calls should work

script {
  if (env.DEPLOY_ENV == 'staging') {
      echo 'Run LUX-staging build'
      def ENV_SERVER = ['192.168.141.230']
      def UML_SUFFIX = ['stage-or']
      sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'
      
      echo 'Run STAGE ADN deploy'
      ENV_SERVER = ['192.168.111.30']
      UML_SUFFIX = ['stage-sg']
      sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'                      
      
      echo 'Run STAGE SG deploy'
      ENV_SERVER = ['stage-sg-pbo-api.example.com']
      UML_SUFFIX = ['stage-ba']
      sh 'ansible-playbook nginx_depl.yml --limit 127.0.0.1'                                              
  }
}

The variables will only be scoped to the if block, so you wont have access to them outside that block.

Upvotes: 1

Related Questions