1
0
Fork 0
distrust-stack/terraform_modules/digitalocean_database_cluster/main.tf

75 lines
1.9 KiB
Terraform
Raw Permalink Normal View History

terraform {
required_providers {
digitalocean = {
source = "digitalocean/digitalocean"
version = "~> 2.0"
}
}
}
resource "digitalocean_database_cluster" "main" {
name = var.cluster_name
engine = var.db_engine
size = var.size
region = var.digitalocean_region
node_count = var.node_count
version = var.db_version
private_network_uuid = var.vpc_id
}
resource "digitalocean_database_db" "main" {
for_each = { for db in var.databases: db.name => db }
cluster_id = digitalocean_database_cluster.main.id
name = each.key
}
locals {
base_connection_string = trimsuffix(digitalocean_database_cluster.main.uri,
"/defaultdb?sslmode=require")
}
resource "digitalocean_database_user" "default_users" {
for_each = {
for db in [for db in var.databases: db if db.create_default_superuser]:
db.name => db.name
}
cluster_id = digitalocean_database_cluster.main.id
name = each.key
provisioner "local-exec" {
command = var.dbcli_name == "psql" ? "GRANT ALL ON DATABASE ${each.key} TO ${each.key};" : "GRANT ALL PRIVILEGES ON ${each.key} TO '${each.key}'@'%';"
interpreter = var.dbcli_name == "psql" ? [
"${var.dbcli_name}",
"${local.base_connection_string}/${each.key}",
"-c"
] : [
"${var.dbcli_name}",
"-u",
"${digitalocean_database_cluster.main.user}",
"-p",
"-h",
"${digitalocean_database_cluster.main.host}",
"-P",
"25060",
"-D",
"${each.key}",
"-e"
]
}
provisioner "local-exec" {
command = var.dbcli_name == "psql" ? "GRANT ALL ON SCHEMA public TO ${each.key}" : "true"
interpreter = var.dbcli_name == "psql" ? [
"${var.dbcli_name}",
"-v", "ON_ERROR_STOP=1",
"${local.base_connection_string}/${each.key}",
"-c"
] : ["true"]
}
# Note: provisioners depend on databases existing
depends_on = [digitalocean_database_db.main]
}