Skip to content

Instantly share code, notes, and snippets.

@jewelsjacobs
Created August 15, 2019 20:18
Show Gist options
  • Save jewelsjacobs/8a27147afbb265cbb1c1dd6782c2de44 to your computer and use it in GitHub Desktop.
Save jewelsjacobs/8a27147afbb265cbb1c1dd6782c2de44 to your computer and use it in GitHub Desktop.
github status lambda
const aws = require('aws-sdk');
const axios = require('axios');
const BaseURL = 'https://api.github.com/repos';
const codepipeline = new aws.CodePipeline();
const Password = process.env.ACCESS_TOKEN;
exports.handler = async event => {
console.log(event);
const { region } = event;
const pipelineName = event.detail.pipeline;
const executionId = event.detail['execution-id'];
const state = transformState(event.detail.state);
if (state === null) {
return null;
}
const result = await this.getPipelineExecution(pipelineName, executionId);
const payload = createPayload(pipelineName, region, state);
try {
return await this.postStatusToGitHub(result.owner, result.repository, result.sha, payload);
} catch (error) {
console.log(error);
return error;
}
};
function transformState(state) {
if (state === 'STARTED') {
return 'pending';
}
if (state === 'SUCCEEDED') {
return 'success';
}
if (state === 'FAILED') {
return 'failure';
}
return null;
}
function createPayload(pipelineName, region, status) {
console.log('status', status);
let description;
if (status === 'started') {
description = 'Build started';
} else if (status === 'success') {
description = 'Build succeeded';
} else if (status === 'failure') {
description = 'Build failed!';
}
return {
state: status,
target_url: buildCodePipelineUrl(pipelineName, region),
description,
context: 'continuous-integration/codepipeline',
};
}
function buildCodePipelineUrl(pipelineName, region) {
return `https://${region}.console.aws.amazon.com/codepipeline/home?region=${region}#/view/${pipelineName}`;
}
exports.getPipelineExecution = async (pipelineName, executionId) => {
const params = {
pipelineName,
pipelineExecutionId: executionId,
};
const result = await codepipeline.getPipelineExecution(params).promise();
const artifactRevision = result.pipelineExecution.artifactRevisions[0];
const revisionURL = artifactRevision.revisionUrl;
const sha = artifactRevision.revisionId;
const pattern = /github.com\/(.+)\/(.+)\/commit\//;
const matches = pattern.exec(revisionURL);
return {
owner: matches[1],
repository: matches[2],
sha,
};
};
exports.postStatusToGitHub = async (owner, repository, sha, payload) => {
const url = `/${owner}/${repository}/statuses/${sha}`;
const config = {
baseURL: BaseURL,
headers: {
'Content-Type': 'application/json',
},
auth: {
password: Password,
},
};
try {
const res = await axios.post(url, payload, config);
console.log(res);
return {
statusCode: 200,
body: JSON.stringify(res),
};
} catch (e) {
console.log(e);
return {
statusCode: 400,
body: JSON.stringify(e),
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment