ext-email plugin, Not sending emails to default recipients from pipeline - jenkins

I am trying to send emails from a Jenkins scripted pipeline with help of the ext-email plugin.
I have configured the plugin with Default Recipients.
Here is my pipeline:
node {
try {
echo "hi"
} catch (e) {
currentBuild.result = "FAILED"
notifyBuild(currentBuild.result)
throw e
}
finally {
notifyBuild(currentBuild.result)
}
}
def notifyBuild(String buildStatus = 'STARTED') {
buildStatus = buildStatus ?: 'SUCCESSFUL'
def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
def summary = "${subject} (${env.BUILD_URL})"
def details = """
<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at "${env.JOB_NAME} [${env.BUILD_NUMBER}]"</p>
"""
emailext (
subject: subject,
body: details,
attachLog: true,
to: ${DEFAULT_RECIPIENTS},
recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider'], [$class: 'CulpritsRecipientProvider']]
)
}
I trying to send the email to a user who triggered the job but I did not get emails to DEFAULT_RECIPIENTS. I also tried with to: env.DEFAULT_RECIPIENTS.
I am getting this error:
groovy.lang.MissingPropertyException: No such property: $DEFAULT_RECIPIENTS for class: groovy.lang.Binding

I also having same problem, just now I got solution on this check the below step:
emailext body: '''${SCRIPT, template="groovy-html.template"}''',
subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - Successful",
mimeType: 'text/html',to: '$DEFAULT_RECIPIENTS'
note down the single qoutes around $DEFAULT_RECIPIENTS that is the key to success here.
I don't know why is not working with double qoutes :(

You should go to Manage Jenkins->Configure System->Extended E-mail Notification. There you should fill the Default Recipient field and Save. (If you do not have the Email Extension Plugin, please install it).
Then you can use the $DEFAULT_RECIPIENT variable in the 'to' clause. Please, remove the braces.
Hope this helps.

Related

Create Okta user via Okta API in Jenkins

Question
I am running Jenkins for job automation and using Okta for authentication. I would like to create a Jenkins job that I can run on demand to create a user in Okta. The user will have the the attributes required by Okta: email, username, etc.
How can I accomplish this in Jenkins?
Initial Setup
I wrote a Jenkinsfile that will create an Okta user via the Okta API Documentation. Before you can run this script you need to install the following plugin's in Jenkins.
Credentials Binding
Pipeline Step Utilities
Http Request Plugin
After installing the aforementioned plugins you will need to create an Okta API Token and save it in Jenkin's Credential Manager of kind Secret Text ( and give it an ID of okta-api-token ).
Proof-of-Concept
The following is a proof-of-concept Jenkinsfile that will use the following plugins to create a user in Okta
pipeline {
agent {
label 'master'
}
options {
buildDiscarder( logRotator( numToKeepStr: "30" ) )
}
parameters {
string(name: 'firstName', description: 'New users first name')
string(name: 'lastName', description: 'New users last name')
string(name: 'email', description: 'New users email')
string(name: 'mobilePhone', description: 'New users phone')
password(name: 'password', description: 'Enter Password')
}
environment {
oktaDomain = "yourdomain.com"
}
stages {
stage('Execute') {
steps {
script {
// Create payload based on https://developer.okta.com/docs/reference/api/users/#request-example-3
def payload = """
{ "profile":{"firstname": "$firstName","lastNAme": "$lastName","email": "$email","login": "$email","mobilePhone": "$mobilePhone"}, "credentials": { "password:{ "value": "$password"}}}
"""
// Send HTTP Post request with API Token saved in credential manager
withCredentials([string(credentialsId: 'apiToken', variable: 'okta-api-token')]) {
def response = httpRequest(
acceptType: 'APPLICATION_JSON',
contentType: 'APPLICATION_JSON',
httpMode: 'POST',
requestBody: payload,
url: "https://${oktaDomain}/api/v1/users?activate=true",
customHeaders: [[Authentication: "SSWS ${apiToken}"]]
)
}
def json = readJSON text: response.content
echo json['id']
}
}
}
}
post {
changed {
emailext subject: 'Your Okta user has been created',
body: 'Your Okta user has been created',
replyTo: '$DEFAULT_REPLYTO',
to: "$email"
}
}
}
Assuming you followed the steps listed above you should only need to change the oktaDomain variable to your Okta domain.

Is it possible to have a Jenkins parameter's name with spaces in it?

I'm trying to make my Jenkins UI more clean.
My Jenkins file calls a function which in turn runs the following:
properties ([
[$class: 'GitLabConnectionProperty', gitLabConnection: 'GitlabConnection'],
[$class: 'ParametersDefinitionProperty', parameterDefinitions: [
[$class: 'BooleanParameterDefinition', defaultValue: false, description: '', name: 'activateInTest'],
[$class: 'ChoiceParameterDefinition', choices: 'false\ntrue\n', description: 'If running newBuild, skip unit tests', name: 'skipUnitTests']
]]
])
Currently, I can access these parameters like this:
if(activateInTest == 'true') {
//Do something
}
After going through other docs and examples. It looked as if I could also access parameters by doing something like params.activateInTest, which did not work. I also tried doing something like params["activateInTest"], but that didn't work either.
The reason I want to access it this way params["..."], is because I would like to have the name of my parameter be "Activate in Test" rather than "activateInTest".
In this example I see the person does use "BooleanParameterDefinition" with spaces in the name. But I can't seem to figure out how to use spaces in the name. Having spaces in the name is my only goal here.
yes, its possible, just use following notation:
${params['Name with space']}
tested on old Jenkins: 2.149
Indeed it is possible, user "string reference" to access it, i.e. params."Activate in Test"
For example:
properties([parameters([
string(name: 'Activate in Test', defaultValue: 'default value')
])])
echo params."Activate in Test"
In Java and Groovy space in a variable does not support! and it's not recommended but Jenkins supports it with 'String referencing'
But If you want to decorate the parameter Display Name it would be something like this
Jenkins Declarative Pipeline
pipeline {
agent any
parameters {
string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
text(name: 'BIOGRAPHY', defaultValue: '', description: 'Enter some information about the person')
booleanParam(name: 'TOGGLE', defaultValue: true, description: 'Toggle this value')
choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'Enter a password')
}
stages {
stage('Example') {
steps {
echo "Hello ${params.PERSON}"
echo "Biography: ${params.BIOGRAPHY}"
echo "Toggle: ${params.TOGGLE}"
echo "Choice: ${params.CHOICE}"
echo "Password: ${params.PASSWORD}"
}
}
}
}
Scripted Pipeline
node {
properties(
[
parameters(
[string(defaultValue: '/data', name: 'Directory', description: "Directort Path"),
string(defaultValue: 'Dev', name: 'DEPLOY_ENV', description: "Deploy Environment")
]
)
]
)
stage('debug') {
echo "${params}"
}
}

emailext jenkinsfile attachment readme

Trying to get jenkins to include the readme as an attachment with a pipeline
stage('email Alex!'){
mail(
body: 'your component is released',
attachmentsPattern: '**/*.md',
from: env.DEFAULT_REPLYTO,
replyTo: env.DEFAULT_REPLYTO,
subject: 'README',
to: 'alexander.lovett#bt.com'
)
}
In this test the dir stucture is:
--currentDir
|--Project
|--README.md
I just get an email with the body and no attachment though :/
Does anyone know how to do this?
You should install this plugin :
https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin
And replace your code with this :
stage('email Alex!'){
emailext(
body: 'your component is released',
attachmentsPattern: '**/*.md',
from: env.DEFAULT_REPLYTO,
replyTo: env.DEFAULT_REPLYTO,
subject: 'README',
to: 'alexander.lovett#bt.com'
)
}

Jenkins pipeline emailext emailextrecipients: Can I also add specific, individual email address?

In Jenkins pipeline I'm using email-ext with emailextrecipients as follows:
emailext(
subject: email_subject,
mimetype: 'text/html',
to: emailextrecipients([[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']]),
body: email_body
)
And I want to add a specific email address, e.g. admin#myshop.com, to the list generated using emailextrecipients. I want that addressee (me or a manager or admin) to always get the email, but the addressee might be a culprit or requester and I don't want emailext to send two emails to that addressee.
Is there a way to merge 'admin#myshop.com' with emailextrecipients?
I don't know how I missed this, but the answer is in the email-ext doc. Use the to: for the additional email addresses, and use recipientProviders: instead of to: emailextrecipients:
emailext(
subject: email_subject,
mimetype: 'text/html',
to: 'admin#myshop.com',
recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']],
body: email_body
)
A slight variation to Generic Ratzlaugh's answer, in case you need to use conditional logic for email destinations:
def recipientProviders = [];
recipientProviders.add([$class: 'CulpritsRecipientProvider']);
recipientProviders.add([$class: 'DevelopersRecipientProvider']);
recipientProviders.add([$class: 'RequesterRecipientProvider']);
emailext(
subject: email_subject,
mimetype: 'text/html',
to: 'admin#myshop.com',
recipientProviders: recipientProviders,
body: email_body
)

When using a Jenkins pipeline, is there a way to get the user that responded to an input() action?

Consider the following example
node {
stage('Build') {
echo "do buildy things"
}
stage('Deploy') {
hipchatSend(
color: "PURPLE",
message: "Holding for deployment authorization: ${env.JOB_NAME}, job ${env.BUILD_NUMBER}. Authorize or cancel at ${env.BUILD_URL}",
)
input('Push to prod?') //Block here until okayed.
echo "Deployment authorized by ${some.hypothetical.env.var}"
echo "do deploy things"
}
}
When responding to the input, the user name that clicked the button is stored in the build log.
Is this username made available in a variable that I could use in, say, another hipChatSend?
Supply the field submitterParameter to input:
def userName = input message: '', submitterParameter: 'USER'
echo "Accepted by ${userName}"
The value of submitterParameter doesn't matter if you doesn't have any parameters. But if you have parameters, then it will specify the name of the array element which holds the value:
def ret = input message: '', parameters: [string(defaultValue: '', description: '', name: 'para1')], submitterParameter: 'USER'
echo "Accepted by ${ret['USER']}"

Resources