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,
This Terraform configuration allows running a set of SQL commands on a new AWS RDS database instance that's operating within an AWS VPC.
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.
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}"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With