Last active
February 1, 2019 00:14
-
-
Save ejlp12/bdb216225f56c8cb293a3aa5f606a8dc to your computer and use it in GitHub Desktop.
Lambda (python 2.7) to start Jenkins job
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http') | |
exports.handler = (event, context, callback) => { | |
var auth = 'Basic ' + Buffer.from('JenkinsUserId:JenkinsAPIToken').toString('base64'); | |
var options = { | |
host: 'example.com or ip address', | |
path: '/jenkins/job/MyJenkinsJobName/job/RepoName/job/master/build?delay=0sec', | |
port: '80', | |
method: 'POST', | |
headers: { 'Authorization': auth } | |
}; | |
const req = http.request(options, (res) => { | |
res.setEncoding('utf8'); | |
res.on('data', (chunk) => { | |
// if you need the returned data modify here | |
}); | |
res.on('end', () => { | |
callback(null, 'Jenkins job triggered successfully') | |
}); | |
}); | |
req.on('error', (e) => { | |
console.log(e) | |
callback(null, "An error occurred while triggering Jenkins job."); | |
}); | |
req.end(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use python 2.7 as your Lambda runtime | |
# Set higher timeout, if the function is timeout.. it will retries 3 times. | |
# In this example, job name is "mytest-codecommit/job/spring-boot-rest-example/job/master" | |
# This script is based on this code [https://github.com/michelleXIE2014/aws-lambda-examples/blob/master/trigger-jenkins-job.py] | |
from __future__ import print_function | |
import base64 | |
import string | |
import httplib | |
import boto3 | |
import datetime | |
import json | |
import time | |
def trigger_jenkins_job(): | |
print("----trigger jenkins job start-------") | |
conn = httplib.HTTPConnection("ec2-13-229-223-4.ap-southeast-1.compute.amazonaws.com", "8080") | |
# Your Jenkins crentials | |
auth = base64.b64encode("admin:mytest123!").decode("ascii") | |
head = { 'Authorization' : 'Basic %s' % auth } | |
conn.request("GET", "/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)", headers = head) | |
res = conn.getresponse() | |
print('Reponse status: ' + str(res.status) + ' ' + res.reason) | |
resp_str = res.read(); | |
print('Reponse body: '+ resp_str) | |
head = { 'Authorization' : 'Basic %s' % auth, resp_str.split(":")[0] : resp_str.split(":")[1]} | |
conn.request("POST", "/job/mytest-codecommit/job/spring-boot-rest-example/job/master/build", headers = head) | |
res = conn.getresponse() | |
print('Reponse status: ' + str(res.status) + ' ' + res.reason) | |
conn.close() | |
print("----trigger jenkins job end-------") | |
time.sleep(20) | |
def get_latest_jenkins_job_build_id(job_name): | |
conn = httplib.HTTPConnection("ec2-13-229-223-4.ap-southeast-1.compute.amazonaws.com", "8080") | |
# Your Jenkins crentials | |
auth = base64.b64encode("admin:mytest123!").decode("ascii") | |
head = { 'Authorization' : 'Basic %s' % auth } | |
conn.request("GET", "/job/mytest-codecommit/job/spring-boot-rest-example/job/master/api/json?pretty=true", headers = head) | |
res = conn.getresponse() | |
print('Reponse status: ' + str(res.status) + ' ' + res.reason) | |
resp_str = res.read(); | |
print(resp_str) | |
resp_dict = json.loads(resp_str) | |
print('Return: ' + str(resp_dict['lastBuild']['number'])) | |
conn.close() | |
return resp_dict['lastBuild']['number'] | |
def get_jenkins_job_status(buildId): | |
print("----get jenkins job status start-------") | |
conn = httplib.HTTPConnection("ec2-13-229-223-4.ap-southeast-1.compute.amazonaws.com", "8080") | |
# Your Jenkins crentials | |
auth = base64.b64encode("admin:mytest123!").decode("ascii") | |
head = { 'Authorization' : 'Basic %s' % auth } | |
conn.request("GET", "/job/mytest-codecommit/job/spring-boot-rest-example/job/master/"+str(buildId)+"/api/json?pretty=true", headers = head) | |
res = conn.getresponse() | |
print(res.status) | |
print(res.reason) | |
resp_str = res.read(); | |
#print(resp_str) | |
resp_dict = json.loads(resp_str) | |
#print(resp_dict['result']) | |
conn.close() | |
print("----get jenkins job status end-------") | |
return resp_dict['result'] | |
def set_aws_job_status(aws_job_id, jenkins_job_status): | |
try: | |
client = boto3.client('codepipeline') | |
if jenkins_job_status == "SUCCESS": | |
print("SUCCESS?????") | |
response = client.put_job_success_result(jobId=aws_job_id) | |
print(response) | |
else: | |
print("FAILED?????") | |
response = client.put_job_failure_result(jobId=aws_job_id, failureDetails={'type': 'JobFailed', 'message': 'Test failed', 'externalExecutionId': str(aws_job_id)}) | |
print(response) | |
except Exception as e: | |
print('Function failed due to exception.') | |
print(e) | |
def lambda_handler(event, context): | |
# print('--> 0. get latest jenkins job id') | |
# current_jenkins_build_number = get_latest_jenkins_job_build_id("mytest-codecommit/job/spring-boot-rest-example/job/master") | |
# print(current_jenkins_build_number) | |
print('--> 1. triggering the jekins job') | |
trigger_jenkins_job() | |
# print('--> 2. get latest jenkins job id') | |
# current_jenkins_build_number = get_latest_jenkins_job_build_id("mytest-codecommit/job/spring-boot-rest-example/job/master") | |
# print(current_jenkins_build_number) | |
# still got timeout error here | |
# print('--> 3. get latest jenkins job status') | |
# current_status = get_jenkins_job_status(current_jenkins_build_number) | |
# print(current_status) | |
# | |
# for i in range(0,100): | |
# print("in the loop?") | |
# print(i) | |
# current_status = get_jenkins_job_status(current_jenkins_build_number) | |
# print(current_status) | |
# if str(current_status) in "None": | |
# time.sleep(1) | |
# print('waiting for job to be triggered') | |
# else: | |
# break | |
# current_status = get_jenkins_job_status(current_jenkins_build_number) | |
# print(current_status) | |
#print('--> 4. get aws job id') | |
#jobId = event.get("CodePipeline.job").get("id"); | |
#print(jobId) | |
#print('--> 5. set aws job status') | |
#set_aws_job_status(jobId, current_status) | |
return "--> Complete." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/govindsh/a15fa7c502ff7559b28d43eee675af23
https://cuneyt.aliustaoglu.biz/en/triggering-jenkins-from-aws-codecommit-using-lambda/