diff --git a/cmd/aws/create.go b/cmd/aws/create.go index f549e4e7..3625fb07 100644 --- a/cmd/aws/create.go +++ b/cmd/aws/create.go @@ -11,11 +11,13 @@ import ( "encoding/json" "errors" "fmt" + "net/http" "os" "slices" "strings" "github.com/aws/aws-sdk-go-v2/aws" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ec2" ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types" @@ -301,7 +303,16 @@ func createKubernetesAdminRole(ctx context.Context, clusterName string, iamClien // Check if the IAM policy exists cp, err := iamClient.GetPolicy(ctx, &iam.GetPolicyInput{PolicyArn: aws.String(fmt.Sprintf("arn:aws:iam::%s:policy/%s", *callerIdentity.Account, policyName))}) - if err == nil && cp.Policy != nil { + if err != nil { + var newError *awshttp.ResponseError + if errors.As(err, newError) && newError.HTTPStatusCode() == http.StatusNotFound { + // Policy does not exist, continue + } else { + return "", fmt.Errorf("failed to get policy %q: %w", policyName, err) + } + } + + if cp.Policy != nil { return "", fmt.Errorf("policy %q already exists: please delete the policy and try again", policyName) } @@ -342,7 +353,12 @@ func createKubernetesAdminRole(ctx context.Context, clusterName string, iamClien // Check if a role with this name already exists role, err := iamClient.GetRole(ctx, &iam.GetRoleInput{RoleName: aws.String(roleName)}) if err != nil { - return "", fmt.Errorf("failed to get role %q: %w %T %#v", roleName, err, err, err) + var newError *awshttp.ResponseError + if errors.As(err, newError) && newError.HTTPStatusCode() == http.StatusNotFound { + // Role does not exist, continue + } else { + return "", fmt.Errorf("failed to get role %q: %w", roleName, err) + } } if role.Role != nil { diff --git a/cmd/aws/create_test.go b/cmd/aws/create_test.go index a32e1bc4..b82fb917 100644 --- a/cmd/aws/create_test.go +++ b/cmd/aws/create_test.go @@ -271,9 +271,10 @@ func TestValidateCredentials(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + clusterName := "foobar" checker := &internalaws.Checker{IAMClient: &mockAWSSimulator{FnSimulatePrincipalPolicy: fnGenerateSimulator(tt.simulator)}} - credentials, err := convertLocalCredsToSession(ctx, tt.mockStsClient, tt.mockIamClient, checker, tt.roleARN) + credentials, err := convertLocalCredsToSession(ctx, tt.mockStsClient, tt.mockIamClient, checker, tt.roleARN, clusterName) if tt.wantErr { require.Error(t, err) } else {