wawawa
wawawa

Reputation: 3345

Issue when using Terraform to manage credentials that access RDS database

I created a secret via Terraform, the secret is for accessing an RDS database which is also defined in Terraform, and in the secret, I don't want to include username and password, so I created an empty secret then add the credentials manually in AWS console.

Then in the RDS definition:

resource "aws_rds_cluster" "example_db_cluster" {
  cluster_identifier = local.db_name
  engine             = "aurora-mysql"
  engine_version     = "xxx"
  engine_mode        = "xxx"
  availability_zones = [xxx]
  database_name   = "xxx"
  master_username = jsondecode(aws_secretsmanager_secret_version.db_secret_string.secret_string)["username"]
  master_password = jsondecode(aws_secretsmanager_secret_version.db_secret_string.secret_string)["password"]
.....

The problem is that when I apply terraform, because the secret is empty so Terraform won't find the string for username and password which will cause error, does anyone have a better way to implement this? Feels like it's easier to just create the secret in Secret Manager manually.

Upvotes: 2

Views: 1888

Answers (1)

matheusopedro
matheusopedro

Reputation: 149

You can generate a random_password and add to your secret using a aws_secretsmanager_secret_version.

Here's an example:

resource "random_password" "default_password" {
 length  = 20
 special = false
}

variable "secretString" {
 default = {
  usernae = "dbuser"
  password = random_password.default_password.result
 }

 type = map(string)
}

resource "aws_secretsmanager_secret" "db_secret_string" {
 name = "db_secret_string"
}

resource "aws_secretsmanager_secret_version" "secret" {
 secret_id = aws_secretsmanager_secret.db_secret_string.id
 secret_string = jsonencode(var.secretString)
}

Upvotes: 2

Related Questions