2023-05-12 04:33:41 +00:00
|
|
|
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
|
2023-05-13 05:04:48 +00:00
|
|
|
private_network_uuid = var.vpc_id
|
2023-05-12 04:33:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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" {
|
2024-03-31 09:11:40 +00:00
|
|
|
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}",
|
2023-05-15 04:03:44 +00:00
|
|
|
"${local.base_connection_string}/${each.key}",
|
|
|
|
"-c"
|
2024-03-31 09:11:40 +00:00
|
|
|
] : [
|
|
|
|
"${var.dbcli_name}",
|
|
|
|
"-u",
|
|
|
|
"${digitalocean_database_cluster.main.user}",
|
|
|
|
"-p",
|
|
|
|
"-h",
|
|
|
|
"${digitalocean_database_cluster.main.host}",
|
|
|
|
"-P",
|
|
|
|
"25060",
|
|
|
|
"-D",
|
|
|
|
"${each.key}",
|
|
|
|
"-e"
|
2023-05-15 04:03:44 +00:00
|
|
|
]
|
2023-05-12 04:33:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
provisioner "local-exec" {
|
2024-03-31 09:11:40 +00:00
|
|
|
command = var.dbcli_name == "psql" ? "GRANT ALL ON SCHEMA public TO ${each.key}" : "true"
|
|
|
|
interpreter = var.dbcli_name == "psql" ? [
|
|
|
|
"${var.dbcli_name}",
|
2023-05-15 04:03:44 +00:00
|
|
|
"-v", "ON_ERROR_STOP=1",
|
|
|
|
"${local.base_connection_string}/${each.key}",
|
|
|
|
"-c"
|
2024-03-31 09:11:40 +00:00
|
|
|
] : ["true"]
|
2023-05-12 04:33:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
# Note: provisioners depend on databases existing
|
|
|
|
depends_on = [digitalocean_database_db.main]
|
|
|
|
}
|