I am looking to connect to a gcp managed db (running on GCP) via a cloud proxy (jump box with local port to connect to managed instance) with go-sql-driver but everything I've tried gcp MySQL instance is rejecting my login. i am able to connect, but when trying to query it returns an error.
this is the code I'm using (note it works if i have a "normal user/password", tested from gcp and local database):
package main
import (
"database/sql"
"fmt"
"log"
"os"
"github.com/go-sql-driver/mysql"
_ "github.com/go-sql-driver/mysql"
)
func connectTCPSocket() (*sql.DB, error) {
mustGetenv := func(k string) string {
v := os.Getenv(k)
if v == "" {
log.Fatalf("Fatal Error in connect_tcp.go: %s environment variable not set.", k)
}
return v
}
c := mysql.Config{
User: mustGetenv("DB_USER"),
Passwd: mustGetenv("DB_PASS"),
Net: "tcp",
Addr: mustGetenv("INSTANCE_HOST") + ":" + mustGetenv("DB_PORT"),
DBName: mustGetenv("DB_NAME"),
ParseTime: true, // demo option
AllowNativePasswords: true,
AllowOldPasswords: true,
AllowCleartextPasswords: true,
}
dbPool, err := sql.Open("mysql", c.FormatDSN())
if err != nil {
return nil, fmt.Errorf("sql.Open: %w", err)
}
// ...
return dbPool, nil
}
func main() {
fmt.Println("Starting")
db, err := connectTCPSocket()
if err != nil {
log.Fatal(err)
}
// fmt.Println(db)
rows, err2 := db.Query("Select field1 from table")
if err2 != nil {
log.Fatal(err2)
}
}
when calling it i get Access denied for user ‘user’@‘ipaddress’ (using password: YES)
the auth token/password is from: gcloud sql generate-login-token command. and i have been able to use this in normal DB Utilities (intellij, dbbeaver, ect).
any suggestions on what i need to use to get it to work?
Edit to answer comments:
- using "gcloud compute ssh cloudsql-jump" not gcloud shell.
- gcloud compute ssh cloudsql-jump --project projectName --zone us-east4-c --internal-ip -- -L 1234:1.0.0.1:3306
- gcloud sql generate-login-token - for the auth token
- INSTANCE_HOST = localhost
- DB_PORT = 1234 (see #1 for jump box port forwarding)
- from intellij using
jdbc:mysql://localhost:1234works with the auth token from #3.
- for code running, i see:
Starting
2025/03/27 06:42:47 Error 1045 (28000): Access denied for user 'user'@'10.0.0.1' (using password: YES)
https://cloud.google.com/sql/docs/mysql/iam-loginsINSTANCE_HOSTandDB_PORTwill usually (!) belocalhost(127.0.0.1) and3306when proxied. Please include the commands that you're running and the output they're generating.