How to apply SQL Scripts on RDS with Terraform

Ademir Carvalho Jr. picture Ademir Carvalho Jr. · Jul 29, 2017 · Viewed 15k times · Source

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,

Answer

ecoe picture ecoe · May 31, 2018

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.