Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Last active May 6, 2021 23:01
Show Gist options
  • Save farhad-taran/ec9f50378787d772ad0a0acc0c344965 to your computer and use it in GitHub Desktop.
Save farhad-taran/ec9f50378787d772ad0a0acc0c344965 to your computer and use it in GitHub Desktop.
Implementing lambda aliasing, versioning and traffic shifting for AWS Lambda using Terraform

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
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment