|
| 1 | +// rds-iam-psql.go |
| 2 | +package main |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "log" |
| 9 | + "os" |
| 10 | + "os/exec" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 14 | + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| 15 | + "github.com/aws/aws-sdk-go-v2/feature/rds/auth" |
| 16 | +) |
| 17 | + |
| 18 | +func main() { |
| 19 | + var ( |
| 20 | + host = flag.String("host", "", "RDS PostgreSQL endpoint hostname (no port, e.g. mydb.abc123.us-east-1.rds.amazonaws.com)") |
| 21 | + port = flag.Int("port", 5432, "RDS PostgreSQL port (default 5432)") |
| 22 | + user = flag.String("user", "", "Database user name") |
| 23 | + dbName = flag.String("db", "", "Database name") |
| 24 | + region = flag.String("region", "", "AWS region for the RDS instance (e.g. us-east-1). If empty, uses AWS config or tries to infer from host.") |
| 25 | + profile = flag.String("profile", "", "Optional AWS shared config profile (e.g. dev)") |
| 26 | + psqlPath = flag.String("psql", "psql", "Path to psql binary") |
| 27 | + sslMode = flag.String("sslmode", "require", "PGSSLMODE for psql (e.g. require, verify-full)") |
| 28 | + searchPath = flag.String("search-path", "", "Optional PostgreSQL search_path to set (e.g. 'myschema,public')") |
| 29 | + ) |
| 30 | + flag.Parse() |
| 31 | + |
| 32 | + if *host == "" || *user == "" || *dbName == "" { |
| 33 | + log.Fatalf("host, user, and db are required\n\nUsage example:\n %s -host mydb.abc123.us-east-1.rds.amazonaws.com -port 5432 -user myuser -db mydb -search-path \"login,public\" -region us-east-1\n", os.Args[0]) |
| 34 | + } |
| 35 | + |
| 36 | + ctx := context.Background() |
| 37 | + |
| 38 | + // Load AWS config (standard RDS/IAM auth expects your AWS creds, *not* the DB password). |
| 39 | + var cfg aws.Config |
| 40 | + var err error |
| 41 | + if *profile != "" { |
| 42 | + cfg, err = awsconfig.LoadDefaultConfig(ctx, awsconfig.WithSharedConfigProfile(*profile)) |
| 43 | + } else { |
| 44 | + cfg, err = awsconfig.LoadDefaultConfig(ctx) |
| 45 | + } |
| 46 | + if err != nil { |
| 47 | + log.Fatalf("failed to load AWS config: %v", err) |
| 48 | + } |
| 49 | + |
| 50 | + awsRegion := *region |
| 51 | + if awsRegion == "" { |
| 52 | + awsRegion = cfg.Region |
| 53 | + } |
| 54 | + if awsRegion == "" { |
| 55 | + // Last resort: try to infer from the hostname if it looks like a standard RDS endpoint. |
| 56 | + if inferred := inferRegionFromHost(*host); inferred != "" { |
| 57 | + awsRegion = inferred |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if awsRegion == "" { |
| 62 | + log.Fatalf("AWS region is not set; pass -region or set AWS_REGION / configure your AWS profile") |
| 63 | + } |
| 64 | + |
| 65 | + endpointWithPort := fmt.Sprintf("%s:%d", *host, *port) |
| 66 | + |
| 67 | + // Generate the IAM auth token. |
| 68 | + authToken, err := auth.BuildAuthToken(ctx, endpointWithPort, awsRegion, *user, cfg.Credentials) |
| 69 | + if err != nil { |
| 70 | + log.Fatalf("failed to build RDS IAM auth token: %v", err) |
| 71 | + } |
| 72 | + |
| 73 | + // Prepare psql command. We pass the token through PGPASSWORD and SSL mode via PGSSLMODE. |
| 74 | + cmd := exec.Command( |
| 75 | + *psqlPath, |
| 76 | + "--host", *host, |
| 77 | + "--port", fmt.Sprintf("%d", *port), |
| 78 | + "--username", *user, |
| 79 | + "--dbname", *dbName, |
| 80 | + ) |
| 81 | + |
| 82 | + // Attach stdio so it behaves like an interactive shell. |
| 83 | + cmd.Stdin = os.Stdin |
| 84 | + cmd.Stdout = os.Stdout |
| 85 | + cmd.Stderr = os.Stderr |
| 86 | + |
| 87 | + // Inherit existing env and add PG vars. |
| 88 | + env := os.Environ() |
| 89 | + env = append(env, |
| 90 | + "PGPASSWORD="+authToken, |
| 91 | + "PGSSLMODE="+*sslMode, |
| 92 | + ) |
| 93 | + |
| 94 | + // If a search path is provided, wire it through PGOPTIONS. |
| 95 | + if sp := strings.TrimSpace(*searchPath); sp != "" { |
| 96 | + // Build our addition: one -c flag. |
| 97 | + add := "-c search_path=" + sp |
| 98 | + |
| 99 | + // Check if PGOPTIONS already exists; if so, append. |
| 100 | + found := false |
| 101 | + for i, e := range env { |
| 102 | + if strings.HasPrefix(e, "PGOPTIONS=") { |
| 103 | + current := strings.TrimPrefix(e, "PGOPTIONS=") |
| 104 | + if strings.TrimSpace(current) == "" { |
| 105 | + env[i] = "PGOPTIONS=" + add |
| 106 | + } else { |
| 107 | + env[i] = "PGOPTIONS=" + current + " " + add |
| 108 | + } |
| 109 | + found = true |
| 110 | + break |
| 111 | + } |
| 112 | + } |
| 113 | + if !found { |
| 114 | + env = append(env, "PGOPTIONS="+add) |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + cmd.Env = env |
| 119 | + |
| 120 | + if err := cmd.Run(); err != nil { |
| 121 | + // psql will print its own error messages; just propagate the exit code. |
| 122 | + if exitErr, ok := err.(*exec.ExitError); ok { |
| 123 | + os.Exit(exitErr.ExitCode()) |
| 124 | + } |
| 125 | + log.Fatalf("failed to run psql: %v", err) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +// inferRegionFromHost tries to pull the AWS region out of a typical RDS hostname like |
| 130 | +// "mydb.abc123.us-east-1.rds.amazonaws.com". If it can't, it returns "". |
| 131 | +func inferRegionFromHost(host string) string { |
| 132 | + parts := strings.Split(host, ".") |
| 133 | + for i := 0; i < len(parts); i++ { |
| 134 | + if parts[i] == "rds" && i > 0 { |
| 135 | + return parts[i-1] |
| 136 | + } |
| 137 | + } |
| 138 | + return "" |
| 139 | +} |
0 commit comments