Last active
February 22, 2022 22:45
-
-
Save alexcasalboni/b259d0a08ea9eba839b0637df94bc821 to your computer and use it in GitHub Desktop.
AWS CodePilpeline - Lambda stage (Node.js)
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'); | |
const AWS = require('aws-sdk'); | |
const codepipeline = new AWS.CodePipeline(); | |
exports.handler = async (event, context) => { | |
// Retrieve event data | |
const jobData = event["CodePipeline.job"]; | |
const jobId = jobData.id; | |
const url = jobData.data.actionConfiguration.configuration.UserParameters; | |
// validate URL | |
if(!url || !url.includes('http://') || !url.includes('https://')) { | |
return await putJobFailure(jobId, 'Invalid URL: ' + url, context.invokeid); | |
} | |
try { | |
const page = await fetchPage(url); | |
if (page.statusCode === 200) { | |
return await putJobSuccess(jobId, "Tests passed."); | |
} else { | |
return await putJobFailure(jobId, "Invalid status code: " + page.statusCode, context.invokeid); | |
} | |
} catch (error) { | |
return await putJobFailure(jobId, "Couldn't fetch page", context.invokeid); | |
} | |
}; | |
const fetchPage = (url) => { | |
let page = { | |
body: '', | |
statusCode: 0 | |
}; | |
return new Promise((resolve, reject) => { | |
http.get(url, function(response) { | |
page.statusCode = response.statusCode; | |
response.on('data', function (chunk) { | |
page.body += chunk; | |
}); | |
response.on('end', function () { | |
resolve(page); | |
}); | |
response.on('error', (error) => { | |
reject(error); | |
}); | |
response.resume(); | |
}); | |
}); | |
} | |
const putJobSuccess = async (jobId, message) => { | |
await codepipeline.putJobSuccessResult({ | |
jobId: jobId | |
}).promise(); | |
return message; | |
}; | |
const putJobFailure = async (jobId, message, executionId) => { | |
await codepipeline.putJobFailureResult({ | |
jobId: jobId, | |
failureDetails: { | |
message: JSON.stringify(message), | |
type: 'JobFailed', | |
externalExecutionId: executionId | |
} | |
}).promise(); | |
return message; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Super, await is needed for nodejs aws sdk methods