From 8aef6b4dc7922f966f2096a06f67fa594b48a661 Mon Sep 17 00:00:00 2001 From: Maxat Sangerbayev Date: Wed, 27 Nov 2024 16:19:51 +0500 Subject: [PATCH] Use kubernetes_job_v1 to create DB in AWS RDS --- aws/postgresql/postgresql.tf | 108 +++++++++++++++++------------------ 1 file changed, 52 insertions(+), 56 deletions(-) diff --git a/aws/postgresql/postgresql.tf b/aws/postgresql/postgresql.tf index 19b2d0f..9fa8b84 100644 --- a/aws/postgresql/postgresql.tf +++ b/aws/postgresql/postgresql.tf @@ -134,68 +134,64 @@ resource "random_password" "database" { special = true } -# TODO: use kubernetes_job resource with ttl_seconds_after_finished argument when -# upgraded to Kubernetes 1.21. -# Since 1.21 TTL Controller is enabled by default. -# -# If the job pod fails with error, see logs for failed pod: -# kubectl -n get pods -# and destroy the job for proper recreation later: -# kubectl -n delete jobs/database-creator -resource "null_resource" "database" { +resource "kubernetes_job_v1" "database_creator" { depends_on = [ module.rds, random_password.database ] - - triggers = { - rds_instance_id = module.rds.db_instance_resource_id + + metadata { + generate_name = "${var.app}-database-creator" } - provisioner "local-exec" { - command = <<-EOC - set -e - - aws eks --region ${var.region} update-kubeconfig --name ${var.eks.cluster_name} - - cat << JOB | kubectl -n default apply -f - - apiVersion: batch/v1 - kind: Job - metadata: - name: database-creator - spec: - template: - spec: - containers: - - name: database-creator - image: postgres:latest - command: - - psql - - "--echo-errors" - - "-c" - - "CREATE DATABASE ${var.app};" - - "-c" - - | - CREATE USER ${var.app} WITH PASSWORD '${random_password.database.result}'; - GRANT ALL PRIVILEGES ON DATABASE ${var.app} TO ${var.app}; - env: - - name: PGHOST - value: "${module.rds.db_instance_address}" - - name: PGPORT - value: "${module.rds.db_instance_port}" - - name: PGUSER - value: "${module.rds.db_instance_username}" - - name: PGPASSWORD - value: "${module.rds.db_master_password}" - - name: PGDATABASE - value: "${module.rds.db_instance_name}" - restartPolicy: Never - backoffLimit: 0 - JOB - - kubectl -n default wait --for=condition=complete jobs/database-creator - kubectl -n default delete jobs/database-creator - EOC + spec { + template { + metadata {} + spec { + container { + name = "database-creator" + image = "postgres:latest" + command = [ + "psql", + "--echo-errors", + "-c", + "CREATE DATABASE ${var.app};", + "-c", + <