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, ]
}
}