Created
January 26, 2021 23:08
-
-
Save AdonousTech/9ca32a011a850c52ef2d2df5ea80ffb9 to your computer and use it in GitHub Desktop.
A Cloud Coach - Tutorial - Serverless Stripe Store - 008 - Pipeline Deploy Function
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 AWS = require('aws-sdk'); | |
exports.handler = (event, context, callback) => { | |
const sourceBucket = process.env.SourceBucket; | |
const destBucket = process.env.DestBucket; | |
const assetPrefix = process.env.AssetPrefix; | |
const s3 = new AWS.S3({params: {Bucket: sourceBucket}, region: 'us-west-2', "signatureVersion":"v4"}); | |
const codepipeline = new AWS.CodePipeline(); | |
//job id passed into fn by CP | |
const jobId = event["CodePipeline.job"].id; | |
let listObjParams = { | |
Bucket: sourceBucket | |
} | |
s3.listObjects(listObjParams, (err, data) => { | |
if (err) { | |
putJobFailure(err); | |
} else { | |
if (data.Contents.length) { | |
data.Contents.forEach((item, index, array) => { | |
let copyParams = { | |
Bucket: destBucket, | |
CopySource: sourceBucket + '/' + item.Key, | |
}; | |
// if there is a value for assetPrefix param, move assets to subdirectory | |
if(item.Key == 'index.html' || item.Key == 'error.html') { | |
copyParams.Key = item.Key; | |
} else { | |
if (assetPrefix) { | |
copyParams.Key = assetPrefix + item.Key; | |
} else { | |
copyParams.Key = item.Key; | |
} | |
} | |
s3.copyObject(copyParams, (copyErr, copyData) => { | |
if (copyErr) { | |
/*If any file fails to copy, fail action in CP*/ | |
putJobFailure('Failed to copy file!', copyData); | |
} | |
else { | |
console.log('Successfully deployed file: ', copyParams.Key); | |
} | |
}); | |
}); | |
//CP job successful after all files copied | |
putJobSuccess('Successfully deployed static site contents!'); | |
} else { | |
//fail pipeline action due to lack of files in source bucket | |
putJobFailure('No files in S3 bucket. Nothing to copy to static site!'); | |
}; | |
}; | |
}); | |
//define job success | |
let putJobSuccess = (jobSuccessMessage) => { | |
let successParams = { | |
jobId: jobId | |
} | |
codepipeline.putJobSuccessResult(successParams, (err, data) => { | |
if (err) { | |
callback(err, null); | |
} else { | |
callback(null, jobSuccessMessage); | |
} | |
}) | |
} | |
//define job failure | |
let putJobFailure = (jobFailureMessage) => { | |
let failureParams = { | |
jobId: jobId, | |
failureDetails: { | |
message: JSON.stringify(jobFailureMessage), | |
type: 'JobFailed', | |
externalExecutionId: context.invokeid | |
} | |
}; | |
codepipeline.putJobFailureResult(failureParams, (err, data) => { | |
callback(jobFailureMessage, null); | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment