Last active
November 9, 2017 19:44
-
-
Save nabilfreeman/2fe7f12a671e4c6d12ce77d257a2356e to your computer and use it in GitHub Desktop.
Restart Codeship build from AWS Lambda
This file contains hidden or 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 https = require('https'); | |
| const { CODESHIP_KEY, PROJECT_ID } = process.env; | |
| const getBuilds = () => { | |
| console.time('Fetching builds...'); | |
| return new Promise((resolve, reject) => { | |
| const host = 'codeship.com'; | |
| const path = `/api/v1/projects/${PROJECT_ID}.json?api_key=${CODESHIP_KEY}`; | |
| const options = { | |
| method: 'GET', | |
| host, | |
| path, | |
| } | |
| const req = https.request(options, function(res){ | |
| var body = ''; | |
| res.on('data', chunk => { | |
| body += chunk; | |
| }); | |
| res.on('end', () => { | |
| const result = JSON.parse(body); | |
| const { error, builds } = result; | |
| if(error) return reject(new Error(error)); | |
| console.timeEnd('Fetching builds...'); | |
| console.log(`Found ${builds.length} builds.`); | |
| resolve(builds); | |
| }); | |
| }) | |
| req.on('error', reject); | |
| req.end(); | |
| }) | |
| } | |
| const restartBuild = build_id => { | |
| return new Promise((resolve, reject) => { | |
| const host = `codeship.com`; | |
| const path = `/api/v1/builds/${build_id}/restart.json?api_key=${CODESHIP_KEY}`; | |
| console.time(`Restarting ${build_id}...`); | |
| const options = { | |
| method: 'POST', | |
| host, | |
| path, | |
| } | |
| const req = https.request(options, function(res){ | |
| var body = ''; | |
| res.on('data', chunk => { | |
| body += chunk; | |
| }); | |
| res.on('end', () => { | |
| const result = JSON.parse(body); | |
| const { error } = result; | |
| if(error) return reject(new Error(error)); | |
| console.timeEnd(`Restarting ${build_id}...`); | |
| console.log(`Succesfully restarted build!`); | |
| resolve(result); | |
| }); | |
| }) | |
| req.on('error', reject); | |
| req.end(); | |
| }) | |
| } | |
| const run = () => { | |
| console.time('Function finished in '); | |
| return getBuilds().then(builds => { | |
| if(!builds.length) throw new Error('No builds on this project yet.'); | |
| //most recent build | |
| const build_id = builds[0].id; | |
| return restartBuild(build_id); | |
| }).then(() => { | |
| console.timeEnd('Function finished in '); | |
| }) | |
| } | |
| exports.handler = (event, context, callback) => { | |
| if(!CODESHIP_KEY) throw new Error('You need to supply CODESHIP_KEY as an environment variable.'); | |
| if(!PROJECT_ID) throw new Error('You need to supply PROJECT_ID as an environment variable.'); | |
| return run().then(callback).catch(error => { throw error; }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment