Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply SQL Scripts on RDS with Terraform

Tags:

terraform

I´m using Terraform to create a script that builds some EC2 Servers and a MySQL RDS (using AWS Amazon Provider).

Is there a way to execute a SQL script on this created RDS (i want to create users, tables, etc)?

Thanks in advance,

Att,

like image 744
Ademir Carvalho Jr. Avatar asked Jul 29 '17 21:07

Ademir Carvalho Jr.


People also ask

Can terraform run SQL script?

This Terraform configuration allows running a set of SQL commands on a new AWS RDS database instance that's operating within an AWS VPC.


2 Answers

Like this solution, You can also avoid instance setup time/cost by using your own machine with local-exec IF your RDS database is publicly available and you have setup ingress to allow your machine to connect. Then, with credentials stored securely in your environment, you would just do something like:

resource "null_resource" "db_setup" {

  # runs after database and security group providing external access is created
  depends_on = ["aws_db_instance.your_database_instance", "aws_security_group.sg_allowing_external_access"]

    provisioner "local-exec" {
        command = "database connection command goes here"
        environment {
          # for instance, postgres would need the password here:
          PGPASSWORD = "${var.database_admin_password}"
        }
    }
}

Keep in mind that passwords and other sensitive variables can be input into terraform separately.

like image 165
ecoe Avatar answered Oct 21 '22 00:10

ecoe


Building upon ecoe's answer:

For future readers using a Postgres RDS instance, this is what worked for me (you must have psql installed on your machine):

variable "db_username" {
  type = string
}

variable "db_password" {
  type = string
}

resource "null_resource" "db_setup" {

  provisioner "local-exec" {

    command = "psql -h host_name_here -p 5432 -U \"${var.db_username}\" -d database_name_here -f \"path-to-file-with-sql-commands\""

    environment = {
      PGPASSWORD = "${var.db_password}"
    }
  }
}
like image 44
rishikarri Avatar answered Oct 21 '22 02:10

rishikarri