How can I authenticate to GCP using a service account key that was uploaded (not generated)?
To authenticate to GCP using a service account key that was uploaded, you need to use the projects.serviceAccounts.keys.upload method.
Steps:
- Generate a new service account key. You can do this in the Google Cloud console or using the
gcloud
command-line tool. When you generate the key, select the "JSON" format. - Upload the service account key to your GCP project. You can do this using the
projects.serviceAccounts.keys.upload
method. - Configure your application to use the service account key. You can do this by setting the
GOOGLE_APPLICATION_CREDENTIALS
environment variable to the path of the service account key file.
Example:
The following code sample shows you how to use theprojects.serviceAccounts.keys.upload
method to upload a service account key:
// Imports the Google Cloud client libraries.
import (
"context"
"fmt"
"io"
iam "google.golang.org/api/iam/v1"
)
// uploadServiceAccountKey uploads a service account key to a project.
func uploadServiceAccountKey(w io.Writer, projectID, serviceAccountEmail, pathToKeyFile string) error {
// projectID := "my-project-id"
// serviceAccountEmail := "service-account@my-project.iam.gserviceaccount.com"
// pathToKeyFile := "/path/to/key.json"
ctx := context.Background()
service, err := iam.NewService(ctx)
if err != nil {
return fmt.Errorf("iam.NewService: %v", err)
}
// Get the service account.
serviceAccount, err := service.Projects.ServiceAccounts.Get(fmt.Sprintf("projects/%s/serviceAccounts/%s", projectID, serviceAccountEmail)).Do()
if err != nil {
return fmt.Errorf("Projects.ServiceAccounts.Get: %v", err)
}
// Create the service account key.
key := &iam.ServiceAccountKey{
PrivateKeyData: "YOUR_PRIVATE_KEY_DATA",
}
// Upload the service account key.
key, err = service.Projects.ServiceAccounts.Keys.Upload(serviceAccount.Name, key).Do()
if err != nil {
return fmt.Errorf("Projects.ServiceAccounts.Keys.Upload: %v", err)
}
fmt.Fprintf(w, "Service account key uploaded: %v\n", key.Name)
return nil
}