Terraform Random Password
Here’s a quick way to generate random passwords with Terraform. This comes in handy when you’re setting up RDS, AWS Secret Manager, MSK, or anything else that needs authentication. The approach works across cloud providers, not just AWS.
Terraform has two resources for this: random_string and random_password. They do the same thing, but random_password keeps the value out of your console output, which is what you usually want for passwords.
Terraform Random Password
Here’s how to create a random password and store it in Secret Manager:
resource "random_password" "secret" {
length = 16
special = true
override_special = "!#$%&*()-_=+[]{}:?"
}
resource "aws_secretsmanager_secret_version" "app-secret-version-bitslovers" {
secret_id = aws_secretsmanager_secret.app-secret-version-bitslovers.id
secret_string = jsonencode({ username = var.user_admin, password = random_password.secret.result })
}
A couple of things worth knowing about override_special: it replaces the default special character set, but special must be true for it to work. Access the generated value with .result.
When you run terraform plan, the password shows as (sensitive value) instead of the actual string, which is the behavior you’d expect.
Generating Random Names
What if you also need a random username? That’s where random_pet comes in.
What is random_pet?
It generates random pet names. You can use these as identifiers for resources, or if you have a dog, pick a name from the generated list.
Terraform Random Pet Example
resource "random_pet" "username" {}
Yep, no required arguments. To use it in a secret:
resource "aws_secretsmanager_secret_version" "app-secret-version-bitslovers" {
secret_id = aws_secretsmanager_secret.app-secret-version-bitslovers.id
secret_string = jsonencode({ username = random_pet.username, password = random_password.secret.result })
}
Terraform Random Number
If you need a random number, there’s random_integer. I wouldn’t use it for passwords though: it only produces integers, which makes for weak passwords, and it prints the value in your console output.
Here’s how it works for cases where numbers are actually what you need:
resource "random_integer" "priority" {
min = 1
max = 99999
}
Comments