Skip to content

Instantly share code, notes, and snippets.

@kunal15145
Last active February 19, 2021 12:39
Show Gist options
  • Save kunal15145/43e5018852e593dc725ce07afd9b8af4 to your computer and use it in GitHub Desktop.
Save kunal15145/43e5018852e593dc725ce07afd9b8af4 to your computer and use it in GitHub Desktop.
Update lambda Function arn at cloudfront using a script
var cloudfront = require("aws-sdk/clients/cloudfront");
var cloudfrontClient = new cloudfront({ apiVersion: "2020-05-31" });
const distributionId = process.argv[2];
const lambdaEdgeEvent = process.argv[3];
const lambdaEdgeArn = process.argv[4];
function updateLambdaFunction(lambdaFunctionAssociations) {
if (lambdaFunctionAssociations["Quantity"] < 0) return [];
lambdaFunctionAssociations["Items"].forEach(function (item) {
if (item["EventType"] === lambdaEdgeEvent) {
item["LambdaFunctionARN"] = lambdaEdgeArn;
}
});
return lambdaFunctionAssociations;
}
cloudfrontClient.getDistributionConfig(
{
Id: distributionId,
},
function (err, data) {
if (!err) {
lambdaFunctionAssociations =
data["DistributionConfig"]["DefaultCacheBehavior"][
"LambdaFunctionAssociations"
];
if (lambdaFunctionAssociations) {
data["DistributionConfig"]["DefaultCacheBehavior"][
"LambdaFunctionAssociations"
] = updateLambdaFunction(lambdaFunctionAssociations);
}
if (
data["DistributionConfig"]["CacheBehaviors"] &&
data["DistributionConfig"]["CacheBehaviors"]["Quantity"] > 0
) {
data["DistributionConfig"]["CacheBehaviors"].Items.forEach(function (
item
) {
item.LambdaFunctionAssociations = updateLambdaFunction(
item.LambdaFunctionAssociations
);
});
}
cloudfrontClient.updateDistribution({
Id: distributionId,
DistributionConfig: data['DistributionConfig'],
IfMatch: data['ETag']
}, function (err, _) {
if (!err) {
console.log('Updated Successfully');
} else {
console.log(err);
}
})
} else {
console.log(err);
}
}
);
@kunal15145
Copy link
Author

usage
node index.js cloudfront-id lambda edge event lambda-arn

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