I need to execute a script (groovy) and use the content generated by the script for sending an email. The body of the email is the content. I am not sure how to do this as $DEFAULT_CONTENT is mentioned to be a token (enabled by token plugin). Can some one help me on how to achieve this. I am using the execute groovy script and Email-ext plugin. Thanks and appreciate any help.
According to the documentation of Email-ext+plugin
https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin
$DEFAULT_CONTENT should be a variable filled from the Default Content field from the global configuration page
I haven't used Email-Ext in plain groovy, but in pipeline I use it like the following:
emailext attachLog: true, compressLog: true, recipientProviders: [culprits()],
subject: "Issue on branch ${env.BRANCH_NAME}",
body: """<p>Job ${env.JOB_NAME} #${env.BUILD_NUMBER} failed</p>
<p>Result of my Script ${MY_SCRIPT_RESULT}</p>
<p>Check console output at <a href='${env.BUILD_URL}'>${env.JOB_NAME} #${env.BUILD_NUMBER}</a></p>"""
Here ${MY_SCRIPT_RESULT} would be the value of variable MY_SCRIPT_RESULT.
MY_SCRIPT_RESULT could be a variable I exported to variable environment for instance
Related
My question is basically the title. I couldn't find such information reading this page and searching the web.
My scenario is the following: whenever I create a PR to master I add a tag with some information, like the lib version seen here:
Then, during the build process, I generate the release notes and would like to access that PR tag inside a task like I do with $(Build.BuildId) here:
How can I accomplish that? Something like $(PullRequest.Tag)
Thanks!
How can I accomplish that? Something like $(PullRequest.Tag) Thanks!
There's no predefined variable for Pull Request tag. (I use printenv command in CMD task to confirm this!)
Here're my workaround:
Use Powershell task to call this rest api, the response would contain the tag of specific PR
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/git/repositories/$($env:BUILD_REPOSITORY_NAME)/pullRequests/$($env:SYSTEM_PULLREQUEST_PULLREQUESTID)/labels?api-version=5.1-preview.1"
$response = Invoke-RestMethod -Uri $url -Method Get -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "##vso[task.setvariable variable=PullRequestTag;isOutput=true]$($response.value.name)"
Then pass the variable $response.value.name(come from rest api response, the name represents the tag name) to output variable PullRequestTag(custom variable) so that next tasks can access the returned tag name.
Notes:
1.Make sure the job which contains the Powershell task allow scripts to access the OAuth token cause my script uses OAuth token instead of PAT to call rest api. (Click Agent Job Name=>Additional options)
2.Since it's a output variable, we should use format $(referenceName.variablename).
After that, we can use $(PS.PullRequestTag) in next tasks to access the tag name.
3.Since your scenario is in a pipeline run triggered by PR, so actually the Powershell task should only run when current pipeline is triggered by PR instead of manual run/CI.
Use and(succeeded(), eq(variables['Build.Reason'], 'PullRequest')) in PS task's control options. See conditions and Build.Reason variable.
Update:
If I added several tags when creating the PR:
The $(PS.PullRequestTag)'s value would be:
I doubt there's a predefined variable for a pull request tag, but you can achieve the goal with the REST API. For example, you can have a build task (e.g. a PowerShell script) which:
gets all tags (aka labels) of a pull request
parses the list of tags to find out the necessary one
set the build variable to the name of the necessary tag
I have a secure string parameter in data fatory
According to another post this is the way to access said parameter
#{pipeline().parameters.ChassisSqlUsername.value}
This use to and still give a validation error within the dynamic content window:
However the pipeline worked like this without issue. This validation error did not block publishing.
Asof today I can no longer publish if that validation error is present
How do I get around this?
Refer it in this way:
#{pipeline().parameters.ChassisSqlUsername}
It will work.
I don't know why the syntax of ADF is so terrible.
#{json(string(pipeline().parameters.ChassisSqlUsername)).value}
I am trying to send an email whenever a boolean value equals. The email needs to contain info from a list that is created in a groovy script earlier in the job. whenever this list isn't empty I will need to create a text/HTML email with the contents of the list.
currently I have the email extension plugin but I can't find a way to integrate it with what I need. Is there anyway I could send the email using groovy or use a plugin that triggers based on what I need?
To anyone who it may concern, I discovered that with the Flexible Publish Plug in you can add conditionals to your post build actions, easiest to use string values and just compare those. this is because you can set up parameters at the start of your build that you plan to use to store info in the build environment, and it can be accessed from other places.
you can set string params using the following code:
def paramTempHolder = new StringParameterValue('PARAM', 'desired value')
build.replaceAction(new ParametersAction(paramTempHolder))
for me I used send to indcate I needed to send my email so my code read:
def paramTempHolder = new StringParameterValue('SendEmail', 'send')
I then used $SendMail as string 1 in flexible publish and just send as string 2. If the condition is meet it will send my email. I can use the same parameter manipulation to get the info I need into my email so that it sends like I want it to.
EDIT: I forgot to mention that inorder to use the replaceAction method you will need to add the following import to your script:
import hudson.model.*
I'm using Jenkins 2.2 and email-ext plugin 2.42 (both current, as are all of the rest of my plugins). I have my global configuration set to have a single, explicit recipient and my project is using default email notification configuration (that is, send to $DEFAULT_RECIPIENTS). I have also set an explicit recipient in the project. In both configurations, the console output for the job says:
An attempt to send an e-mail to empty list of recipients, ignored.
This would seem to be https://issues.jenkins-ci.org/browse/JENKINS-13583 except
1. that was marked as resolved four years ago, and 2. I get e-mail when I use basic, built-in notifications. Does anyone else see this problem with email-ext?
Turns out plugin configuration is somewhat non-intuitive; a necessary setting is buried behind an Advanced button. I got answers in https://issues.jenkins-ci.org/browse/JENKINS-34731 and it is working now as follows:
In the Advanced settings, Triggers -> Failure - Any lists "Developers" by default, but not "Recipient List."
For those using this plugin in combination with Job DSL. I have do add the sendTo { recipientList() } block explicitly to the different triggers.
So my DSL looked like this:
extendedEmail {
recipientList('${EMAIL_RECIPIENTS}')
triggers {
failure {
subject('The subject')
content("The content")
sendTo {
recipientList()
}
}
}
}
Instead of using $DEFAULT_RECIPIENTS use to:
emailext(
to: 'somename#emailprovider.com',
body: '${DEFAULT_CONTENT}',
mimeType: 'text/html',
subject: '${DEFAULT_SUBJECT}',
replyTo: '$DEFAULT_REPLYTO'
)
}
Ref: https://stackoverflow.com/a/39499554/1134084
I finally found the problem through repeated attempts. There is no need for such trouble at all. The reason is that in the advanced Settings of Editable Email Notification trigger condition, the Recipient List is empty by default, and all your Settings outside will be overridden. An attempt to send an e-mail to empty list of recipients was ignored. An attempt to send an E-mail to empty list of recipients ignored.
I am using the Email Ext Jenkins plugin and it was working quite well.
Now I need to set the recipients list dynamically. Basically for each build I get a list of email recipients in a file and I need to use that list. My question is:
Is there a way to set an Environment Variable so that that can be modified and Recipient List will get that consume that environment variable.
I know there is a solution to set programmatically recipients of Jenkins Email-ext plugin in the pre-send script.How To set programmatically recipients of jenkins email ext plugin. However for my case there are some difficulty with that solution as I need to read a file which contains a list of Emails.
If the format of the file is either comma separated or space separated, you could just use the FILE token (see the content token reference in the plugin). That should put the contents of the file into the recipients list.
I can't test this right now so I can't remember if apache commons is available.
Create a file called recipients.groovy with the following contents:
<%
def stream = new FilePath(build.workspace, "yourfile.txt").read();
def recipients = IOUtils.toString(stream, "UTF-8");
%>
${recipients}
And in your jobs configuration, in the recipients list, you put ${SCRIPT, script="recipients.groovy"}
API References:
FilePath
AbstractBuild
Referring to the recipients.groovy in the Recipient List, gives the following exception:
Failed to create e-mail address for Error in script or template: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script1.groovy: 1:
unexpected token: < # line 1, column 1. <% ^ 1 error
Full Exception below:
groovy.lang.MissingPropertyException: No such property: build for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at Script1.run(Script1.groovy:4)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:150)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:122)
at hudson.remoting.LocalChannel.call(LocalChannel.java:45)
at hudson.util.RemotingDiagnostics.executeGroovy(RemotingDiagnostics.java:119)
at jenkins.model.Jenkins._doScript(Jenkins.java:3400)
at jenkins.model.Jenkins.doScript(Jenkins.java:3377)
at sun.reflect.GeneratedMethodAccessor344.invoke(Unknown Source)
You can use the Inject environment variables plugin (https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin) and to create a var during run time, or the Propagate build environment variables (https://wiki.jenkins-ci.org/display/JENKINS/Build+Env+Propagator+Plugin) to change an existing one, and then you can use this var in the Project recipient list when you are using Editable Email Notification (https://wiki.jenkins-ci.org/display/JENKINS/Email-ext+plugin)