Skip to content

Instantly share code, notes, and snippets.

@samratshaw
Created September 27, 2018 10:35
Show Gist options
  • Save samratshaw/7d944e6a85c7d51309c849ba402225aa to your computer and use it in GitHub Desktop.
Save samratshaw/7d944e6a85c7d51309c849ba402225aa to your computer and use it in GitHub Desktop.
Medium: Invoke Jenkins Build With Parameters Programmatically
import * as fs from 'fs';
import * as queryString from 'query-string';
import * as request from 'request';
import config from '../config/index';
/**************************************************/
// Interface Declaration
/**************************************************/
export interface ISendEmailDetails {
to: string[]; // List of emailId's
cc?: string[];
subject: string;
body: string;
from?: string;
}
/**************************************************/
// Public Functions
/**************************************************/
/**
* Utility function to send email.
* This will invoke a jenkins job, which will then send the email to the users.
* @param details The inputs required for sending the email.
*/
async function sendEmail(details: ISendEmailDetails): Promise<void> {
const { subject, body } = details;
const from = details.from ? details.from : '';
const to = details.to.join();
const cc = details.cc ? details.cc.join() : '';
if (!Boolean(to)) {
throw new Error('to cannot be empty.');
}
if (!Boolean(subject)) {
throw new Error('subject cannot be empty.');
}
if (!Boolean(body)) {
throw new Error('body cannot be empty.');
}
let apiToken = '';
try {
// For more information about how we can retrieve the token,
// read https://medium.com/@samratshaw/programmatically-retrieve-jenkins-rest-api-token-f2c3f0d69483
apiToken = await getJenkinsApiToken();
} catch (error) {
throw new Error('Jenkins authentication failed.');
}
const parameters = queryString.stringify({ to, cc, subject, body, from });
return new Promise<void>((resolve, reject) => {
request(
{
method: 'POST',
uri: `<JENKINS_BASE_URL>/job/<jobName>/buildWithParameters?${parameters}`, // Path to the job + buildWithParameters ...
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: <ACCOUNT_USERNAME>,
password: apiToken,
},
agentOptions: { // Only use if your jenkins has ssl configured
ca: fs.readFileSync(<PATH_TO_YOUR_CERTIFICATE>)
}
},
(error, httpResponse, body) => {
if (error) {
reject(error);
}
resolve();
},
);
});
}
export default sendEmail;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment