In the below snippet I am creating an alas for my newly deployed lambda and setting a traffic weight for the previous version of this lambda if it exists, if a previous version of the lambda does not exist then all the traffic would be passed to the latest version.
resource "aws_lambda_alias" "main_alias" {
count = var.publish ? 1 : 0
name = "LATEST"
description = "LATEST lambda alias"
function_name = aws_lambda_function.main.function_name
function_version = aws_lambda_function.main.version
#sets traffic of the previous version if available to a portion out of 100% causing the new version to take the rest
#will set the new version to 100% if no previous version is available or if previous-version-traffic has no value
dynamic "routing_config" {
for_each = (var.previous_version_weight > 0 && var.previous_version_weight < 100) && (tonumber(aws_lambda_function.main.version) - 1 > 0) ? list(var.previous_version_weight) : []
content {
additional_version_weights = {
tostring(tonumber(aws_lambda_function.main.version) - 1) = var.previous_version_weight
}
}
}
}