Skip to content

Instantly share code, notes, and snippets.

@gkspranger
Last active January 13, 2017 12:39
Show Gist options
  • Save gkspranger/d6ac6e849bb2ab5be85b8c85a9943920 to your computer and use it in GitHub Desktop.
Save gkspranger/d6ac6e849bb2ab5be85b8c85a9943920 to your computer and use it in GitHub Desktop.
# hubot event listener
# can map to a Jenkins instance and job and build it with params if needed
# can be invoked like this:
# robot.emit "jenkins_job", {
# name: "Restart_Tomcat",
# msg: msg,
# success: "Hello .. I went ahead and triggered a restart for Tomcat in the #{env} environment",
# params: "Inventory=#{env}&Group=tomcat"
# }
module.exports = (robot) ->
robot.on "jenkins_job", (job) ->
# because everything we touch is over SSL .. right ??
url = process.env.JENKINS_URL
msg = job.msg
name = job.name
params = job.params
success = job.success
failure = job.failure
path = if params then "#{url}/job/#{name}/buildWithParameters?#{params}" else "#{url}/job/#{name}/build"
req = msg.http(path)
jenkins_user = process.env.JENKINS_USER
jenkins_password = process.env.JENKINS_PASSWORD
if "#{jenkins_user}:#{jenkins_password}"
auth = new Buffer("#{jenkins_user}:#{jenkins_password}").toString("base64")
req.headers Authorization: "Basic #{auth}"
req.header("Content-Length", 0)
logstr = "User '#{msg.message.user.id}/#{msg.message.user.name}' triggered Jenkins job '#{name}' with params'#{params}' using text '#{msg.message.text}'"
req.post() (err, res, body) ->
if err
msg.reply "Sorry .. There was an error processing your command .. Please contact your Bot administrator"
robot.logger.error("ERROR : #{logstr}")
else if 200 <= res.statusCode < 400 # Or, not an error code.
if success
msg.reply "#{success}"
robot.logger.info("SUCCESS : #{logstr}")
else if 404 == res.statusCode
msg.reply "Sorry .. The Jenkins job '#{name}' was not found .. Please check that it exists and/or is spelled correctly"
robot.logger.error("NOT FOUND : #{logstr}")
else
if failure
msg.reply "#{failure}"
robot.logger.warn("FALLBACK : #{logstr}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment