gcp cloud sql iam - ghdrako/doc_snipets GitHub Wiki

Enable CloudSQL IAM authentication###

resource "google_sql_database_instance" "master" {
  name                   = "demo"
  database_version = "POSTGRES13"

  settings {
    tier = "db-f1-micro"

    database_flags {
      name  = "cloudsql.iam_authentication"
      value = "on"
    }
  }
}

Create a CloudSQL IAM user

resource "google_sql_user" "iam_user" {
  name     = "[email protected]"
  instance = google_sql_database_instance.master.name
  type     = "CLOUD_IAM_USER"
}

resource "google_project_iam_member" "iam_user_cloudsql_instance_user" {
  role   = "roles/cloudsql.instanceUser"
  member = format("user:%s", google_sql_user.iam_user.name)
}

resource "google_project_iam_member" "iam_user_cloudsql_client" {
  role   = "roles/cloudsql.client"
  member = format("user:%s", google_sql_user.iam_user.name)
}

Specify the email address of the Google Cloud identity and specify the type as CLOUD_IAM_USER. The IAM user requires the roles cloudsql.instanceUser and cloudsql.client to connect. For service accounts, specify the type CLOUD_IAM_SERVICE_ACCOUNT.

When an IAM user is added to a database instance, that new user is granted no privileges on any databases, by default.

When a user or service account connects to a database, they can run queries against any database objects whose access has been granted to PUBLIC.

grant select on TABLE_NAME  to "USERNAME";
gcloud sql users delete USERNAME --instance=INSTANCE_NAME; # Remove an IAM user or service account from the database