Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Last active November 18, 2023 18:54
Show Gist options
  • Save farhad-taran/514c77d3a5bb8b98f3d245680de11d4e to your computer and use it in GitHub Desktop.
Save farhad-taran/514c77d3a5bb8b98f3d245680de11d4e to your computer and use it in GitHub Desktop.
Creating and assigning secrets manager secrets using terraform

When creating a secret initially, most people tend to first create the secret and then add the value manually, below I demonstrate a way to do all of this in one step:

resource "aws_secretsmanager_secret" "order_status_lambda_debug_api_key" {
  name = "order_status_lambda_api_key"
  # makes sure the secret is immediately destroyed and replaced if new value provided
  recovery_window_in_days = 0
  description = "an api key for the purposes of invoking the lambda and api gateway when debugging is neeeded"
}

resource "random_password" "api_key" {
  length           = 60
  special          = false
}

resource "aws_secretsmanager_secret_version" "order_status_lambda_debug_api_key" {
  secret_id     = aws_secretsmanager_secret.order_status_lambda_debug_api_key.id
  secret_string = random_password.api_key.result
  lifecycle {
    # do not replace secret on each TF apply and keep the first generated secret
    # this also is a preferred way to ignore changes as it means the value of secret 
    # will not be copied into the state file
    ignore_changes = [secret_string, ]
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment