terraform local-exec command for executing mysql script

家住魔仙堡 提交于 2019-12-07 16:33:12

问题


I created the aws_db_instance to provision the RDS MySQL database using Terraform configuration. I need to execute the SQL Scripts (CREATE TABLE and INSERT statements) on the RDS. I'm stuck on what command to use here?? Anyone has the sample code in my use case? Please advise. Thanks.

resource "aws_db_instance" "mydb" {
  # ...

    provisioner "local-exec" {
      command = "command to execute script.sql"

    }
}

回答1:


This is possible using a null_resource that depends on the aws_db_instance.my_db. This way the host is available when you run the command, it will only work if there aren't rules preventing you from accessing the DB such as security group ingress or not publicly accessible.

Example:

resource "null_resource" "setup_db" {
  depends_on = ["aws_db_instance.my_db"] #wait for the db to be ready
  provisioner "local-exec" {
    command = "mysql -u ${aws_db_instance.my_db.username} -p${var.my_db_password} -h ${aws_db_instance.my_db.address} < file.sql"
  }
}



回答2:


I don't believe you can use a provisioner with that type of resource. One option you could explore is having an additional step that takes the address of the RDS instance from a Terraform output and runs the SQL script.

So, for instance in a CI environment, you'd have Create Database -> Load Database -> Finished.

Below would be you Terraform to create and output the resource address.

resource "aws_db_instance" "mydb" {
  # ...
    provisioner "local-exec" {
      command = "command to execute script.sql"
    }
}

output "username" {
    value = "${aws_db_instance.mydb.username}"
}

output "address" {
    value = "${aws_db_instance.mydb.address}"
}

The Load Database step would then run a shell script with the SQL logic and the following to obtain the address of the instance - terraform output address



来源:https://stackoverflow.com/questions/49563301/terraform-local-exec-command-for-executing-mysql-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!