Question

How to retrieve database credentials and certificate in Terraform?

Posted August 30, 2021 72 views
MongoDBTerraformDatabases

I’m using the DigitalOcean Terraform Provider to set up my infrastructure, and I would like to set up a MongoDB database inside a cluster for each environment I’m running.

When applying a config like this:

variable "db-cluster-name" {
  default = "cluster"
  type = string
}

data "digitalocean_database_cluster" "db-cluster" {
  name = var.db-cluster-name
}

resource "digitalocean_database_db" "db" {
  cluster_id = data.digitalocean_database_cluster.db-cluster.id
  name       = var.environment
}

resource "digitalocean_database_user" "db-user" {
  cluster_id = data.digitalocean_database_cluster.db-cluster.id
  name       = var.environment
}

output "database-url" {
  value = "mongodb+srv://${digitalocean_database_user.db-user.name}:${digitalocean_database_user.db-user.password}@${data.digitalocean_database_cluster.db-cluster.host}/${resource.digitalocean_database_db.db.name}?tls=true&authSource=admin"
  sensitive = true
}

I would expect a database and user to be created and managed by Terraform, and a MongoDB connection URL to be outputted by Terraform with the user credentials baked in. Unfortunately the password field is always either empty (“”) or null, depending on if I create a new user or try to retrieve the default user doadmin. I understand it’s a secret, but on creation of a user the password should be retrievable somehow, else the automation of infrastructure will be impossible. Is there any way to retrieve this using the Terraform Provider?
Also, how do I retrieve the certificate authority file (.crt) associated with the database, that is needed for connection?

Submit an answer

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!