How to Manage Secrets in AWS with Secrets Manager and Terraform

Guillermo Musumeci
5 min readJun 20, 2022


AWS Secrets Manager helps us to create, manage, rotate and retrieve database credentials, API keys, and other secrets through their lifecycle

In this story, we will learn how to create and consume secrets using AWS Secrets Manager and Terraform.

Creating a Secret for a Variable

In this first example, we will create a secret using a variable for an API username.

The first step is to define the variable, and we are using sensitive = true to protect the values of the variable from being printed in the logs and console output.

# Secret Variables
variable "api_username" {
description = "API service username"
type = string
sensitive = true

then we will create the secret:

# Creating a AWS Secret for API Service User 
resource "aws_secretsmanager_secret" "service_user" {
name = "service_user"
description = "Service Account Username for the API"
recovery_window_in_days = 0 tags = {
Name = "service_user"
Environment = var.app_environment
resource "aws_secretsmanager_secret_version" "service_user" {
secret_id =
secret_string = var.api_username

Define the username in the “terraform.tfvars” file:

api_username = "srv_apiprod"

Note: the “recovery_window_in_days” is an optional setting for the number of days that AWS Secrets Manager waits before it can delete the secret. The default value is 30. This value can be 0 to force deletion without recovery (recommended for development) or range from 7 to 30 days.

Creating a Secret for a Password

In this second example, we will create a secret for an API password.

The first step is using the “randon_password” resource to create a random password. This function is identical to “random_string” except that the result is treated as sensitive and not displayed in console output.

resource "random_password" "service_password" {
length = 16…



Guillermo Musumeci

Certified AWS, Azure & GCP Architect | HashiCorp Ambassador | Terraform SME | KopiCloud Founder | ex-AWS | Entrepreneur | Book Author | Husband & Dad of ✌

Recommended from Medium


See more recommendations