gants
gants

Reputation: 183

Add batch variable to groovy email-ext pipeline

Not a pro on groovy or batch, but here goes.

I have a groovy script where a small part of it sends email when something fails in jenkins pipleine. Here is the catch code which sends email if something goes wrong.

catch (Exception e){
    def buildNumber = env.BUILD_NUMBER
    def buildurl = env.BUILD_URL        
    def buildjobname = env.JOB_NAME

    bat 'for /f "delims=" %%a in (user_id.txt) do set USER_ID=%%a'

    emailext body: "Failure in build number $buildNumber for the job name $buildjobname. See URL for more detail: $buildurl",
    subject: "Failure in build number $buildNumber for the job name $buildjobname",
    to: 
}

As you can see I have a line which does some bat shell script where it stores the user_id content into the USER_ID variable by reading a file. Now I want to use the USER_ID variable in my to attribute (something like this: to: USER_ID) but it seems this is not the way to do it.

What am I misisng

Edit: I guess I have to use EnvInject plugin?

Upvotes: 0

Views: 1903

Answers (3)

gants
gants

Reputation: 183

Solved it by using the a jenkins plugin

readFile 'user_id.txt'

Upvotes: 1

Pom12
Pom12

Reputation: 7880

In a Jenkins pipelines code, you could use bat output to get your userId as a variable. Example :

catch (Exception e){
    def buildNumber = env.BUILD_NUMBER
    def buildurl = env.BUILD_URL        
    def buildjobname = env.JOB_NAME

    def userId = bat script: 'for /f "delims=" %%a in (user_id.txt) do echo %%a', returnStdout: true

    emailext body: "Failure in build number $buildNumber for the job name $buildjobname. See URL for more detail: $buildurl",
    subject: "Failure in build number $buildNumber for the job name $buildjobname",
    to: "${userId}"
}

I'm not so sure about how to output your userId using bat script (more familiar with shell script, sorry) but you get the idea...

Upvotes: 1

susi
susi

Reputation: 493

in groovy, you could acces environment variables like the following:

groovy -e "println System.env.LOGNAME"

so it might be possible (if USER_ID is an environment variable) that you could access the content of the variable like

to: System.env.USER_ID

but maybe in your jenkins env, the variable is already present?

to: env.USER_ID

?

Another possibility could be:

to: new File("user_id.txt").text.replace("\n", "")

Upvotes: 0

Related Questions