@@ -19,15 +19,16 @@ limitations under the License.
1919package main
2020
2121import (
22+ "context"
2223 "encoding/json"
2324 "fmt"
2425 "os"
2526
27+ "sigs.k8s.io/aws-iam-authenticator/pkg/endpoints"
2628 "sigs.k8s.io/aws-iam-authenticator/pkg/token"
2729
28- "github.com/aws/aws-sdk-go/aws/ec2metadata"
29- "github.com/aws/aws-sdk-go/aws/endpoints"
30- "github.com/aws/aws-sdk-go/aws/session"
30+ "github.com/aws/aws-sdk-go-v2/config"
31+ "github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
3132 "github.com/spf13/cobra"
3233 "github.com/spf13/viper"
3334)
@@ -54,12 +55,7 @@ var verifyCmd = &cobra.Command{
5455 os .Exit (1 )
5556 }
5657
57- sess := session .Must (session .NewSession ())
58- ec2metadata := ec2metadata .New (sess )
59- instanceRegion , err := ec2metadata .Region ()
60- if err != nil {
61- fmt .Printf ("[Warn] Region not found in instance metadata, err: %v" , err )
62- }
58+ instanceRegion := getInstanceRegion (context .Background ())
6359
6460 id , err := token .NewVerifier (clusterID , partition , instanceRegion ).Verify (tok )
6561 if err != nil {
@@ -86,14 +82,27 @@ func init() {
8682 viper .BindPFlag ("token" , verifyCmd .Flags ().Lookup ("token" ))
8783 viper .BindPFlag ("output" , verifyCmd .Flags ().Lookup ("output" ))
8884
89- partitionKeys := []string {}
90- for _ , p := range endpoints .DefaultPartitions () {
91- partitionKeys = append (partitionKeys , p .ID ())
92- }
93-
9485 verifyCmd .Flags ().String ("partition" ,
9586 endpoints .AwsPartitionID ,
96- fmt .Sprintf ("The AWS partition. Must be one of: %v" , partitionKeys ))
87+ fmt .Sprintf ("The AWS partition. Must be one of: %v" , endpoints . PARTITIONS ))
9788 viper .BindPFlag ("partition" , verifyCmd .Flags ().Lookup ("partition" ))
9889
9990}
91+
92+ // Uses EC2 metadata to get the region. Returns "" if no region found.
93+ func getInstanceRegion (ctx context.Context ) string {
94+ cfg , err := config .LoadDefaultConfig (ctx )
95+ if err != nil {
96+ fmt .Fprintf (os .Stderr , "[Warn] Unable to create config for metadata client, err: %v" , err )
97+ panic (err )
98+ }
99+
100+ imdsClient := imds .NewFromConfig (cfg )
101+ getRegionOutput , err := imdsClient .GetRegion (ctx , & imds.GetRegionInput {})
102+ if err != nil {
103+ fmt .Fprintf (os .Stderr , "[Warn] Region not found in instance metadata, err: %v\n " , err )
104+ return ""
105+ }
106+
107+ return getRegionOutput .Region
108+ }
0 commit comments