Search code examples
google-cloud-platformterraformgoogle-cloud-sqlterraform-provider-gcpinfrastructure-as-code

Creating Google Cloud sql tables using Terraform


I am trying to create Google cloud sql tables using terraform.

However it seems that only google cloud sql instance and sql database creation is possible through terraform and using cloudshell we can create the sql tables.

But I am trying to create the tables using terraform only whether by directly using the sql script inside my terraform script or just referencing the sql script from the terraform script where thse sql script will be stored somewhere e.g. cloud storage.

Any leads/suggestions on the same would be really helpful.

Thanks in advance.


Solution

  • You can try out the Provisioners

    here is a simple example for Postgres

    resource "google_sql_database_instance" "default" {
      [...]
      provisioner "local-exec" {
        command = "PGPASSWORD=<password> psql -f schema.sql -p <port> -U <username> <databasename>"
      }
    }
    

    Provisioners can be used to model specific actions on the local machine or on a remote machine in order to prepare servers or other infrastructure objects for service.

    schema.sql would hold your table definitions.

    the same way you can update this command for MySQL also. Make sure your local or CI/CD machine has MySQL cli installed so from there it will connect to DB instance and create the table.