Created
May 13, 2022 21:14
-
-
Save dewe/ce7dbc2ff83a78d6c7efaa6f8bd6944e to your computer and use it in GitHub Desktop.
Generate EKS k8s api bearer token, for use in api requests or setting up kubeconfig for accessing a remote cluster.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/base64" | |
"flag" | |
"fmt" | |
"strings" | |
"github.com/aws/aws-sdk-go-v2/config" | |
"github.com/aws/aws-sdk-go-v2/service/sts" | |
smithyhttp "github.com/aws/smithy-go/transport/http" | |
) | |
func main() { | |
clusterName := flag.String("c", "", "Cluster name") | |
flag.Parse() | |
if *clusterName == "" { | |
fmt.Println("Missing argument -c cluster name") | |
return | |
} | |
cfg, err := config.LoadDefaultConfig(context.TODO()) | |
if err != nil { | |
panic("config error, " + err.Error()) | |
} | |
client := sts.NewFromConfig(cfg) | |
header := smithyhttp.SetHeaderValue("x-k8s-aws-id", *clusterName) | |
options := sts.WithPresignClientFromClientOptions(sts.WithAPIOptions(header)) | |
psClient := sts.NewPresignClient(client, options) | |
resp, err := psClient.PresignGetCallerIdentity(context.TODO(), nil) | |
if err != nil { | |
fmt.Println("error retrieving pre-signed url:", err) | |
return | |
} | |
encUrl := base64.StdEncoding.EncodeToString([]byte(resp.URL)) | |
// special token prefix, and removed base64 encoding padding | |
fmt.Println("k8s-aws-v1." + strings.TrimRight(encUrl, "=")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment