Easy Passwords in Terraform

It’s a common use case to want to create a random password for a new service – such as an RDS database – inside of terraform. Terraform actually allows for a very simple way to handle these using the random provider. This will create a new password only on resource creation saving the value into the statefile. This means the password will be created the first time you run terraform apply, and each subsequent time the password will not change.

Heres an example using AWS Systems Manager which adds a secure way to store secrets.

resource "random_password" "password" {
  length  = 63
  special = false
}

resource "aws_ssm_parameter" "db_password" {
  name  = "/prd/db-password"
  type  = "SecureString"
  value = random_password.password.result
}

resource "aws_db_instance" "db" {
  username               = "great new db"
  password               = aws_ssm_parameter.db_password.value
}

Now I don’t really need to store the db password in SSM, I could just pass it directly to the db instance. But SSM provides a way for me to easily update the parameter after it is created. Additionally, I will probably need to view the paramter later on. SSM is a great way to securely provide secrets to your application running on AWS as well.

Additional References