@@ -35,6 +35,7 @@ import (
3535
3636 "contrib.go.opencensus.io/exporter/prometheus"
3737 "contrib.go.opencensus.io/exporter/stackdriver"
38+ "cloud.google.com/go/compute/metadata"
3839 "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/cloudsql"
3940 "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/healthcheck"
4041 "github.com/GoogleCloudPlatform/cloud-sql-proxy/v2/internal/log"
@@ -598,6 +599,11 @@ status code.`)
598599 `If set, the Proxy will skip any instances that are invalid/unreachable (
599600only applicable to Unix sockets)` )
600601
602+ localFlags .StringVar (& c .conf .InstancesMetadata , "instances-metadata" , "" ,
603+ `If provided, it is treated as a path to a metadata value which
604+ contains a comma-separated list of instance connection names.
605+ Only supported when running on Google Compute Engine.` )
606+
601607 // Global and per instance flags
602608 localFlags .StringVarP (& c .conf .Addr , "address" , "a" , "127.0.0.1" ,
603609 "(*) Address to bind Cloud SQL instance listeners." )
@@ -644,6 +650,15 @@ func loadConfig(c *Command, args []string, opts []Option) error {
644650 o (c )
645651 }
646652
653+ // If instances-metadata is set, fetch instances from GCE metadata.
654+ if c .conf .InstancesMetadata != "" {
655+ mArgs , err := instanceFromMetadata (c .conf .InstancesMetadata )
656+ if err != nil {
657+ return err
658+ }
659+ args = append (args , mArgs ... )
660+ }
661+
647662 // Handle logger separately from config
648663 if c .conf .StructuredLogs {
649664 c .logger = log .NewStructuredLogger (c .conf .Quiet )
@@ -1270,3 +1285,22 @@ func startHTTPServer(ctx context.Context, l cloudsql.Logger, addr string, mux *h
12701285 l .Errorf ("failed to shutdown HTTP server: %v\n " , err )
12711286 }
12721287}
1288+
1289+ func instanceFromMetadata (path string ) ([]string , error ) {
1290+ if ! metadata .OnGCE () {
1291+ return nil , newBadCommandError ("instances-metadata unsupported outside of Google Compute Engine" )
1292+ }
1293+ val , err := metadata .Get (path )
1294+ if err != nil {
1295+ return nil , fmt .Errorf ("failed to fetch metadata from %q: %v" , path , err )
1296+ }
1297+
1298+ var args []string
1299+ for _ , inst := range strings .Split (val , "," ) {
1300+ inst = strings .TrimSpace (inst )
1301+ if inst != "" {
1302+ args = append (args , inst )
1303+ }
1304+ }
1305+ return args , nil
1306+ }
0 commit comments