func getToken()

in cmd/ar-token/main.go [53:96]


func getToken(ctx context.Context) (string, error) {
	var ts oauth2.TokenSource
	switch {
	case *serviceAccountJSON != "":
		debug("Obtain credentials using service account JSON")
		json, err := os.ReadFile(*serviceAccountJSON)
		if err != nil {
			return "", fmt.Errorf("unable to read service account JSON file: %v", err)
		}

		creds, err := google.CredentialsFromJSON(ctx, json, cloudPlatformScope)
		if err != nil {
			return "", fmt.Errorf("unable to obtain creds from service account JSON: %v", err)
		}

		ts = creds.TokenSource

	case *serviceAccountEmail != "":
		debug("Obtain credentials using specific service account email attached to VM")
		ts = google.ComputeTokenSource(*serviceAccountEmail)

	default:
		debug("Obtain credentials using default lookup path")
		creds, err := google.FindDefaultCredentials(ctx, cloudPlatformScope)
		if err != nil {
			return "", fmt.Errorf("unable to find default creds: %v", err)
		}

		ts = creds.TokenSource
	}

	if ts == nil {
		return "", fmt.Errorf("got nil token source")
	}

	token, err := ts.Token()
	if err != nil {
		return "", fmt.Errorf("unable to obtain token from token source: %v", err)
	}

	debug("Got a token")

	return token.AccessToken, nil
}