infra_snippets/terraform/modules/cloudsql/cloudsql.tf
2021-07-18 22:58:09 -04:00

105 lines
2.5 KiB
HCL

# For the cloudsql auth proxy grant roles/cloudsql.instanceUser and
# roles/cloudsql.client roles to the service account for the proxy.
variable "project" {
description = "Project ID."
type = string
}
variable "region" {
description = "Region."
type = string
}
variable "tier" {
description = "DB machine type."
type = string
default = "db-f1-micro"
}
variable "db_version" {
description = "Database version."
type = string
default = "POSTGRES_13"
}
variable "private_network_id" {
description = "Private network id."
type = string
}
variable "postgres_password" {
description = "Password for the default postgres user."
type = string
default = "hunter2"
}
variable "require_tls" {
description = "Whether or not we should require TLS when connecting to cloudsql."
type = bool
default = false
}
output "connection_name" {
description = "The connection string for connecting to the cloudsql instance (for example, through cloudsql proxy)."
value = google_sql_database_instance.instance.connection_name
}
output "instance" {
description = "The google_sql_database_instance object."
value = google_sql_database_instance.instance
}
output "certificate" {
description = "TLS certificate for connecting to the database."
value = google_sql_ssl_cert.client_cert
}
# Needed for CloudSQL Auth Proxy
resource "google_project_service" "sqladmin" {
project = var.project
service = "sqladmin.googleapis.com"
disable_dependent_services = true
}
resource "random_id" "cloudsql" {
byte_length = 4
}
resource "google_sql_database_instance" "instance" {
project = var.project
region = var.region
name = "my-database-instance-${random_id.cloudsql.hex}"
database_version = var.db_version
settings {
tier = var.tier
ip_configuration {
ipv4_enabled = false
private_network = var.private_network_id
require_ssl = var.require_tls
}
database_flags {
name = "cloudsql.iam_authentication"
value = "on"
}
}
deletion_protection = "false"
# deletion_protection = "true"
}
resource "google_sql_user" "postgres" {
project = var.project
name = "postgres"
instance = google_sql_database_instance.instance.name
password = var.postgres_password
}
resource "google_sql_ssl_cert" "client_cert" {
project = var.project
common_name = "client-name"
instance = google_sql_database_instance.instance.name
}