I have a problem with Jenkins Pipeline script. No such property for class WorkFlowScript

Viewed 7408

When I create new job, results of this job jenkins send on emails of all teams, but when we create test job(we can understand it by name of job), we should send email only to creator of job. It was so and it works:

pipe(..){
 timeout(..){
  BuildEmailExt email = new BuilEmailExt(this, Emails.allTeams())
  someCode..
  }
}

Then i add if:

  pipe(..){
   timeout(..){
   if(env.JOB_NAME =~ /somePattern/){
    BuildEmailExt email = new BuilEmailExt(this, SENDER)
   }
   else{
    BuildEmailExt email = new BuilEmailExt(this, Emails.allTeams())
   }
   someCode..
  }
}

And I get Exception : No such property email for class: WorkFlowScript What am I doing wrong?

1 Answers

By defining the variable inside the if and else, it doesn't exist outside of that scope, so is not accessible outside of the conditional.

You can move the definition outside of the if, and then set it like so:

pipe(..){
    timeout(..){
        BuildEmailExt email
        if(env.JOB_NAME =~ /somePattern/){
            email = new BuilEmailExt(this, SENDER)
        }
        else {
            email = new BuilEmailExt(this, Emails.allTeams())
        }
        someCode..
    }
}

You could also do this which may look cleaner (ymmv)

pipe(..){
    timeout(..){
        BuildEmailExt email = new BuilEmailExt(this, (env.JOB_NAME =~ /somePattern/) ? SENDER : Emails.allTeams())
        someCode..
    }
}
Related