Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sshymko/aa1eb3870ca3cc9e64efd83a43a1f06a to your computer and use it in GitHub Desktop.
Save sshymko/aa1eb3870ca3cc9e64efd83a43a1f06a to your computer and use it in GitHub Desktop.
Invalidate CloudFront distribution from CodePipeline via Lambda function
const aws = require('aws-sdk');
const codepipeline = new aws.CodePipeline();
const cloudfront = new aws.CloudFront();
exports.handler = async (event, context) => {
let job = event['CodePipeline.job'];
let config = job.data.actionConfiguration.configuration.UserParameters;
try {
let params = JSON.parse(config);
if (!params || !params.distributionId) {
throw new Error('Missing CloudFront distributionId.');
}
let paths = (params.paths && params.paths.length)
? params.paths
: ['/*'];
await cloudfront.createInvalidation({
DistributionId: params.distributionId,
InvalidationBatch: {
CallerReference: String(Date.now()),
Paths: {
Quantity: paths.length,
Items: paths
}
}
}).promise();
return codepipeline.putJobSuccessResult({
jobId: job.id
}).promise();
} catch (error) {
return codepipeline.putJobFailureResult({
jobId: job.id,
failureDetails: {
type: 'JobFailed',
message: error.message,
externalExecutionId: context.awsRequestId
}
}).promise();
}
};
@sshymko
Copy link
Author

sshymko commented Jan 8, 2021

Usage

Invalidate Distribution

Configure CloudFront distribution ID in JSON format in CodePipeline Action:
aws_codepipeline_action_lambda_invalidate_cloudfront_distribution

Invalidate Paths

Specify invalidation path(s):
aws_codepipeline_action_lambda_invalidate_cloudfront_path

Permissions

Lambda function needs to have an IAM Role with the following Policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "cloudfront:CreateInvalidation"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "codepipeline:PutJobFailureResult",
                "codepipeline:PutJobSuccessResult"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        }
    ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment