Created
April 16, 2021 13:39
-
-
Save maxpeterson/7bbf38355a3eac7835b974a68810ae4e to your computer and use it in GitHub Desktop.
AWS Lambda function to create CloudFront invalidation for CodePipeline
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'); | |
const getDistribution = async (client, bucket) => { | |
const params = { MaxItems: '100' }; | |
for (;;) { | |
const { DistributionList: { Items: DistributionItems, IsTruncated, NextMarker } } = await client.listDistributions(params).promise(); | |
if (!DistributionItems) continue; | |
for (const distribution of DistributionItems) { | |
const { Origins } = distribution | |
if (!Origins?.Items) continue; | |
for (const { Id } of Origins.Items) { | |
if (Id === `S3-${bucket}`) return distribution; | |
} | |
} | |
if (!IsTruncated) break; | |
params.Marker = NextMarker; | |
} | |
}; | |
exports.handler = async (event, context) => { | |
const codepipeline = new AWS.CodePipeline(); | |
const jobId = event["CodePipeline.job"].id; | |
// Retrieve the AWS bucket name | |
// UserParameters from the Lambda action configuration in AWS CodePipeline. | |
const bucket = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; | |
const putJobSuccess = async (message) => { | |
const params = { | |
jobId: jobId | |
}; | |
return codepipeline | |
.putJobSuccessResult(params) | |
.promise() | |
.then(() => context.succeed(message)) | |
.catch(err => context.fail(err)); | |
}; | |
const putJobFailure = async (message) => { | |
const params = { | |
jobId: jobId, | |
failureDetails: { | |
message: JSON.stringify(message), | |
type: 'JobFailed', | |
externalExecutionId: context.awsRequestId | |
} | |
}; | |
return codepipeline.putJobFailureResult(params).promise().finally(() => context.fail(message)); | |
}; | |
if (!bucket) { | |
await putJobFailure('The UserParameters field must contain a S3 bucket to invalidate'); | |
return; | |
} | |
const cloudfront = new AWS.CloudFront(); | |
let distribution; | |
try { | |
distribution = await getDistribution(cloudfront, bucket); | |
} catch (er) { | |
await putJobFailure(er); | |
return; | |
} | |
if (!distribution) { | |
await putJobFailure(`Unabled to find distribution for bucket ${bucket}`) | |
return; | |
} | |
await cloudfront | |
.createInvalidation({ | |
DistributionId: distribution.Id, | |
InvalidationBatch: { | |
CallerReference: Date.now().toString(), | |
Paths: { | |
Quantity: 1, | |
Items: ['/*'] | |
} | |
} | |
}) | |
.promise() | |
.then(data => | |
putJobSuccess(`Invalidation created ${data.Invalidation.Id}`) | |
) | |
.catch(err => | |
putJobFailure(err) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment