Skip to content

Instantly share code, notes, and snippets.

@samratshaw
Last active May 21, 2019 05:57
Show Gist options
  • Save samratshaw/8bd007a22cbdb71854b6fe95b3537fc1 to your computer and use it in GitHub Desktop.
Save samratshaw/8bd007a22cbdb71854b6fe95b3537fc1 to your computer and use it in GitHub Desktop.
Medium: Function for retrieving the Jenkins Api Token
import * as request from 'request';
import * as fs from 'fs';
import * as cheerio from 'cheerio';
/**
* Retrieve the Jenkins Api Token.
*/
async function getJenkinsApiToken(): Promise<string> {
return new Promise<string>((resolve, reject) => {
request(
{
method: "POST",
uri: <JENKINS_CONFIGURE_URL: i.e. http://your-jenkins-url/me/configure>,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: <ACCOUNT_USERNAME>,
password: <ACCOUNT_PASSWORD>,
},
agentOptions: { // Only use if your jenkins has ssl configured
ca: fs.readFileSync(<PATH_TO_YOUR_CERTIFICATE>)
}
},
(error, httpResponse, body) => {
if (error) {
reject(error);
}
const apiToken = cheerio(body)
.find("#apiToken")
.attr('value');
apiToken ? resolve(apiToken) : reject(new Error('API Token not found'));
}
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment