diff --git a/cfn-resources/access-list-api-key/cmd/resource/resource.go b/cfn-resources/access-list-api-key/cmd/resource/resource.go index d0df00061..0f820f48b 100644 --- a/cfn-resources/access-list-api-key/cmd/resource/resource.go +++ b/cfn-resources/access-list-api-key/cmd/resource/resource.go @@ -21,16 +21,18 @@ import ( "net/http" "strings" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/profile" "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/logger" progress_events "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var CreateRequiredFields = []string{constants.OrgID, constants.APIUserID} @@ -79,14 +81,14 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: EitherOrMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } if currentModel.CidrBlock != nil && currentModel.IpAddress != nil { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: MutualExclusiveMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } // createReq.ApiService. @@ -140,14 +142,14 @@ func Read(req handler.Request, prevModel *Model, currentModel *Model) (handler.P return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: EitherOrMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } if currentModel.CidrBlock != nil && currentModel.IpAddress != nil { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: MutualExclusiveMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } entry := getEntryAddress(currentModel) @@ -191,14 +193,14 @@ func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: EitherOrMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } if currentModel.CidrBlock != nil && currentModel.IpAddress != nil { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: MutualExclusiveMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } entry := getEntryAddress(currentModel) @@ -294,14 +296,14 @@ func handleError(response *http.Response, method string, err error) (handler.Pro return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: errMsg, - HandlerErrorCode: cloudformation.HandlerErrorCodeInternalFailure}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInternalFailure)}, nil } if response.StatusCode == http.StatusConflict { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: errMsg, - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists}, nil + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists)}, nil } return progress_events.GetFailedEventByResponse(errMsg, response), nil } diff --git a/cfn-resources/alert-configuration/cmd/resource/resource.go b/cfn-resources/alert-configuration/cmd/resource/resource.go index 7e8d1132a..c8e8bf691 100644 --- a/cfn-resources/alert-configuration/cmd/resource/resource.go +++ b/cfn-resources/alert-configuration/cmd/resource/resource.go @@ -21,17 +21,19 @@ import ( "reflect" "strings" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/spf13/cast" + "github.com/mongodb/mongodbatlas-cloudformation-resources/profile" "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/logger" progressevents "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - "github.com/spf13/cast" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var CreateRequiredFields = []string{constants.EventTypeName, constants.ProjectID} @@ -68,12 +70,12 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Resource Already Exists", - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists}, nil + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists)}, nil } notifications, err := expandAlertConfigurationNotification(currentModel.Notifications) if err != nil { - return progressevents.GetFailedEventByCode(err.Error(), cloudformation.HandlerErrorCodeInvalidRequest), err + return progressevents.GetFailedEventByCode(err.Error(), string(types.HandlerErrorCodeInvalidRequest)), err } alertConfigRequest := admin20231115014.GroupAlertsConfig{ @@ -125,7 +127,7 @@ func Read(req handler.Request, prevModel *Model, currentModel *Model) (handler.P return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Resource Not Found", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } alertConfig, resp, err := atlasV2.AlertConfigurationsApi.GetAlertConfiguration(context.Background(), *currentModel.ProjectId, *currentModel.Id).Execute() @@ -165,7 +167,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Resource Not Found", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } // In order to update an alert config it is necessary to send the original alert configuration request again, if not the @@ -229,7 +231,7 @@ func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Resource Not Found", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } res, err := atlasV2.AlertConfigurationsApi.DeleteAlertConfiguration(context.Background(), *currentModel.ProjectId, *currentModel.Id).Execute() @@ -248,7 +250,7 @@ func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.P return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "List operation is not supported", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } func isExist(currentModel *Model, client *admin20231115014.APIClient) bool { diff --git a/cfn-resources/api-key/cmd/resource/resource.go b/cfn-resources/api-key/cmd/resource/resource.go index 028fb73e3..67cbd8630 100644 --- a/cfn-resources/api-key/cmd/resource/resource.go +++ b/cfn-resources/api-key/cmd/resource/resource.go @@ -20,9 +20,12 @@ import ( "net/http" "sort" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/profile" "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" @@ -30,8 +33,6 @@ import ( progress_events "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/secrets" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var CreateRequiredFields = []string{constants.OrgID, constants.Description, constants.AwsSecretName} @@ -285,13 +286,13 @@ func handleError(response *http.Response, method constants.CfnFunctions, err err return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: errMsg, - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists}, nil + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists)}, nil } if response.StatusCode == http.StatusBadRequest { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: errMsg, - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } return progress_events.GetFailedEventByResponse(errMsg, response), nil } diff --git a/cfn-resources/auditing/cmd/resource/resource.go b/cfn-resources/auditing/cmd/resource/resource.go index 6c62e12bf..0900652db 100644 --- a/cfn-resources/auditing/cmd/resource/resource.go +++ b/cfn-resources/auditing/cmd/resource/resource.go @@ -19,15 +19,17 @@ import ( "errors" "net/http" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" log "github.com/mongodb/mongodbatlas-cloudformation-resources/util/logger" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var RequiredFields = []string{constants.ProjectID} @@ -58,9 +60,9 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler return progressevent.GetFailedEventByResponse(err.Error(), res), nil } - if aws.BoolValue(atlasAuditing.Enabled) { + if aws.ToBool(atlasAuditing.Enabled) { return handler.ProgressEvent{ - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists, + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists), OperationStatus: handler.Failed, }, nil } @@ -116,9 +118,9 @@ func Read(req handler.Request, prevModel *Model, currentModel *Model) (handler.P return progressevent.GetFailedEventByResponse(err.Error(), res), nil } - if !aws.BoolValue(atlasAuditing.Enabled) { + if !aws.ToBool(atlasAuditing.Enabled) { return handler.ProgressEvent{ - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound, + HandlerErrorCode: string(types.HandlerErrorCodeNotFound), OperationStatus: handler.Failed, }, nil } @@ -156,7 +158,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (handler } if !resourceEnabled { return handler.ProgressEvent{ - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound, + HandlerErrorCode: string(types.HandlerErrorCodeNotFound), OperationStatus: handler.Failed, Message: "resource not found", }, nil @@ -222,7 +224,7 @@ func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler if !resourceEnabled { return handler.ProgressEvent{ - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound, + HandlerErrorCode: string(types.HandlerErrorCodeNotFound), OperationStatus: handler.Failed, }, nil } @@ -254,7 +256,7 @@ func isEnabled(client admin20231115014.APIClient, currentModel Model) (bool, *ha return false, &er } - return aws.BoolValue(atlasAuditing.Enabled), nil + return aws.ToBool(atlasAuditing.Enabled), nil } func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.ProgressEvent, error) { diff --git a/cfn-resources/cloud-backup-restore-jobs/cmd/resource/resource.go b/cfn-resources/cloud-backup-restore-jobs/cmd/resource/resource.go index 3b5dddaf5..b9bdcbb0c 100644 --- a/cfn-resources/cloud-backup-restore-jobs/cmd/resource/resource.go +++ b/cfn-resources/cloud-backup-restore-jobs/cmd/resource/resource.go @@ -20,14 +20,16 @@ import ( "fmt" "time" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var CreateRequiredFields = []string{constants.SnapshotID, constants.DeliveryType, constants.InstanceType, constants.InstanceName} @@ -53,7 +55,7 @@ func validateModel(fields []string, model *Model) *handler.ProgressEvent { if *model.InstanceType != clusterInstanceType && *model.InstanceType != serverlessInstanceType { pe := progressevent.GetFailedEventByCode(fmt.Sprintf("InstanceType must be %s or %s", clusterInstanceType, serverlessInstanceType), - cloudformation.HandlerErrorCodeInvalidRequest) + string(types.HandlerErrorCodeInvalidRequest)) return &pe } @@ -74,7 +76,7 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler err := currentModel.validateAsynchronousProperties() if err != nil { - return progressevent.GetFailedEventByCode(err.Error(), cloudformation.HandlerErrorCodeInvalidRequest), err + return progressevent.GetFailedEventByCode(err.Error(), string(types.HandlerErrorCodeInvalidRequest)), err } if _, idExists := req.CallbackContext[constants.StateName]; idExists { @@ -110,7 +112,7 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler currentModel.Id = server.Id } - if aws.BoolValue(currentModel.EnableSynchronousCreation) { + if aws.ToBool(currentModel.EnableSynchronousCreation) { return progressevent.GetInProgressProgressEvent( "Create in progress", map[string]interface{}{ @@ -146,11 +148,11 @@ func Read(req handler.Request, prevModel *Model, currentModel *Model) (handler.P return *err, nil } - if aws.BoolValue(currentModel.Cancelled) { + if aws.ToBool(currentModel.Cancelled) { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "The job is in status cancelled, Cannot read a cancelled job", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } return handler.ProgressEvent{ @@ -180,14 +182,14 @@ func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler return *err, nil } - if aws.BoolValue(currentModel.Cancelled) { + if aws.ToBool(currentModel.Cancelled) { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "The job is in status cancelled, Cannot delete a cancelled job", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } - if util.IsStringPresent(currentModel.FinishedAt) || aws.BoolValue(currentModel.Failed) || aws.BoolValue(currentModel.Expired) { + if util.IsStringPresent(currentModel.FinishedAt) || aws.ToBool(currentModel.Failed) || aws.ToBool(currentModel.Expired) { return handler.ProgressEvent{ OperationStatus: handler.Success, Message: "The resource is finished, failed, or expired", @@ -242,7 +244,7 @@ func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.P InstanceName: currentModel.InstanceName, Profile: currentModel.Profile, } - if !aws.BoolValue(job.Cancelled) && !aws.BoolValue(job.Expired) { + if !aws.ToBool(job.Cancelled) && !aws.ToBool(job.Expired) { updateModelServerless(model, job) models = append(models, model) } @@ -262,7 +264,7 @@ func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.P InstanceName: currentModel.InstanceName, Profile: currentModel.Profile, } - if !aws.BoolValue(job.Cancelled) && !aws.BoolValue(job.Expired) { + if !aws.ToBool(job.Cancelled) && !aws.ToBool(job.Expired) { updateModelServer(model, job) models = append(models, model) } @@ -283,11 +285,11 @@ func (model *Model) validateAsynchronousProperties() error { } if model.SynchronousCreationOptions.CallbackDelaySeconds == nil { - model.SynchronousCreationOptions.CallbackDelaySeconds = aws.Int(defaultBackSeconds) + model.SynchronousCreationOptions.CallbackDelaySeconds = util.IntPtr(defaultBackSeconds) } if model.SynchronousCreationOptions.TimeOutInSeconds == nil { - model.SynchronousCreationOptions.TimeOutInSeconds = aws.Int(defaultTimeOutInSeconds) + model.SynchronousCreationOptions.TimeOutInSeconds = util.IntPtr(defaultTimeOutInSeconds) } if model.SynchronousCreationOptions.ReturnSuccessIfTimeOut == nil { @@ -321,7 +323,7 @@ func createCallback(client *util.MongoDBClient, currentModel *Model, jobID, star } } - return progressevent.GetFailedEventByCode("Create failed with Timout", cloudformation.HandlerErrorCodeInternalFailure) + return progressevent.GetFailedEventByCode("Create failed with Timout", string(types.HandlerErrorCodeInternalFailure)) } return progressevent.GetInProgressProgressEvent( diff --git a/cfn-resources/cloud-backup-schedule/cmd/resource/resource.go b/cfn-resources/cloud-backup-schedule/cmd/resource/resource.go index 47e270545..9afe4e2d7 100644 --- a/cfn-resources/cloud-backup-schedule/cmd/resource/resource.go +++ b/cfn-resources/cloud-backup-schedule/cmd/resource/resource.go @@ -18,14 +18,16 @@ import ( "context" "errors" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var RequiredFields = []string{constants.ProjectID, constants.ClusterName} @@ -80,11 +82,11 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (handler } events, _ := Read(req, prevModel, currentModel) - if events.HandlerErrorCode == cloudformation.HandlerErrorCodeNotFound { + if events.HandlerErrorCode == string(types.HandlerErrorCodeNotFound) { return handler.ProgressEvent{ Message: "Not Found", OperationStatus: handler.Failed, - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } return cloudBackupScheduleCreateOrUpdate(req, prevModel, currentModel) @@ -173,12 +175,12 @@ func cloudBackupScheduleCreateOrUpdate(req handler.Request, prevModel *Model, cu func validatePolicies(currentModel *Model) (pe handler.ProgressEvent, err error) { if len(currentModel.Policies) == 0 { msg := "validation error: policies cannot be empty" - return progressevent.GetFailedEventByCode(msg, cloudformation.HandlerErrorCodeInvalidRequest), errors.New(msg) + return progressevent.GetFailedEventByCode(msg, string(types.HandlerErrorCodeInvalidRequest)), errors.New(msg) } for _, policy := range currentModel.Policies { if len(policy.PolicyItems) == 0 { msg := "validation error: policy items cannot be empty" - return progressevent.GetFailedEventByCode(msg, cloudformation.HandlerErrorCodeInvalidRequest), errors.New(msg) + return progressevent.GetFailedEventByCode(msg, string(types.HandlerErrorCodeInvalidRequest)), errors.New(msg) } for _, policyItem := range policy.PolicyItems { if policyItem.FrequencyInterval == nil || policyItem.FrequencyType == nil || @@ -187,7 +189,7 @@ func validatePolicies(currentModel *Model) (pe handler.ProgressEvent, err error) return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, err + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, err } } } @@ -201,7 +203,7 @@ func validateExportDetails(currentModel *Model) (pe handler.ProgressEvent, err e return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, err + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, err } } return handler.ProgressEvent{}, nil @@ -214,7 +216,7 @@ func validateExist(policy *admin20231115014.DiskBackupSnapshotSchedule) *handler return &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Not Found", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound} + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)} } func (m *Model) getParams() *admin20231115014.DiskBackupSnapshotSchedule { @@ -227,7 +229,7 @@ func (m *Model) getParams() *admin20231115014.DiskBackupSnapshotSchedule { UseOrgAndGroupNamesInExportPrefix: m.UseOrgAndGroupNamesInExportPrefix, Policies: expandPolicies(m.Policies), CopySettings: expandCopySettings(m.CopySettings), - Export: expandExport(m.Export, aws.BoolValue(m.AutoExportEnabled)), + Export: expandExport(m.Export, aws.ToBool(m.AutoExportEnabled)), UpdateSnapshots: m.UpdateSnapshots, DeleteCopiedBackups: expandDeleteCopiedBackups(m.DeleteCopiedBackups), } @@ -248,7 +250,7 @@ func (m *Model) newModel(policy *admin20231115014.DiskBackupSnapshotSchedule) *M Policies: flattenPolicies(policy.Policies), Links: flattenLinks(policy.Links), CopySettings: flattenCopySettings(policy.CopySettings), - Export: flattenExport(policy.Export, aws.BoolValue(policy.AutoExportEnabled)), + Export: flattenExport(policy.Export, aws.ToBool(policy.AutoExportEnabled)), } } @@ -302,10 +304,10 @@ func expandPolicyItems(cloudPolicyItems []ApiPolicyItemView) *[]admin20231115014 for _, policyItem := range cloudPolicyItems { cPolicyItem := admin20231115014.DiskBackupApiPolicyItem{ Id: policyItem.ID, - FrequencyInterval: aws.IntValue(policyItem.FrequencyInterval), + FrequencyInterval: util.SafeInt(policyItem.FrequencyInterval), FrequencyType: util.SafeString(policyItem.FrequencyType), RetentionUnit: util.SafeString(policyItem.RetentionUnit), - RetentionValue: aws.IntValue(policyItem.RetentionValue), + RetentionValue: util.SafeInt(policyItem.RetentionValue), } policyItems = append(policyItems, cPolicyItem) } diff --git a/cfn-resources/cloud-backup-snapshot/cmd/resource/resource.go b/cfn-resources/cloud-backup-snapshot/cmd/resource/resource.go index ac1a3481f..87d55b8aa 100644 --- a/cfn-resources/cloud-backup-snapshot/cmd/resource/resource.go +++ b/cfn-resources/cloud-backup-snapshot/cmd/resource/resource.go @@ -19,14 +19,16 @@ import ( "errors" "fmt" + admin20231115002 "go.mongodb.org/atlas-sdk/v20231115002/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115002 "go.mongodb.org/atlas-sdk/v20231115002/admin" ) const ( @@ -171,7 +173,7 @@ func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.P models := make([]interface{}, 0) if *currentModel.InstanceType == clusterInstanceType { - server, resp, err := client.Atlas20231115002.CloudBackupsApi.ListReplicaSetBackups(aws.BackgroundContext(), *currentModel.ProjectId, *currentModel.InstanceName).Execute() + server, resp, err := client.Atlas20231115002.CloudBackupsApi.ListReplicaSetBackups(context.Background(), *currentModel.ProjectId, *currentModel.InstanceName).Execute() if err != nil { return progressevent.GetFailedEventByResponse(err.Error(), resp), nil } @@ -186,7 +188,7 @@ func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.P models = append(models, &model) } } else { - serverless, resp, err := client.Atlas20231115002.CloudBackupsApi.ListServerlessBackups(aws.BackgroundContext(), *currentModel.ProjectId, *currentModel.InstanceName).Execute() + serverless, resp, err := client.Atlas20231115002.CloudBackupsApi.ListServerlessBackups(context.Background(), *currentModel.ProjectId, *currentModel.InstanceName).Execute() if err != nil { return progressevent.GetFailedEventByResponse(err.Error(), resp), nil } @@ -211,7 +213,7 @@ func List(req handler.Request, prevModel *Model, currentModel *Model) (handler.P func validateExist(client *util.MongoDBClient, model *Model) *handler.ProgressEvent { if *model.InstanceType == clusterInstanceType { - server, resp, err := client.Atlas20231115002.CloudBackupsApi.ListReplicaSetBackups(aws.BackgroundContext(), *model.ProjectId, *model.InstanceName).Execute() + server, resp, err := client.Atlas20231115002.CloudBackupsApi.ListReplicaSetBackups(context.Background(), *model.ProjectId, *model.InstanceName).Execute() if err != nil { pe := progressevent.GetFailedEventByResponse(err.Error(), resp) return &pe @@ -222,7 +224,7 @@ func validateExist(client *util.MongoDBClient, model *Model) *handler.ProgressEv } } } else { - serverless, resp, err := client.Atlas20231115002.CloudBackupsApi.ListServerlessBackups(aws.BackgroundContext(), *model.ProjectId, *model.InstanceName).Execute() + serverless, resp, err := client.Atlas20231115002.CloudBackupsApi.ListServerlessBackups(context.Background(), *model.ProjectId, *model.InstanceName).Execute() if err != nil { pe := progressevent.GetFailedEventByResponse(err.Error(), resp) return &pe @@ -237,7 +239,7 @@ func validateExist(client *util.MongoDBClient, model *Model) *handler.ProgressEv return &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Resource Not Found", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound} + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)} } func validateProgress(client *util.MongoDBClient, currentModel *Model, targetState string) (handler.ProgressEvent, error) { diff --git a/cfn-resources/cluster-outage-simulation/cmd/resource/resource.go b/cfn-resources/cluster-outage-simulation/cmd/resource/resource.go index 1680012cc..1404447e9 100644 --- a/cfn-resources/cluster-outage-simulation/cmd/resource/resource.go +++ b/cfn-resources/cluster-outage-simulation/cmd/resource/resource.go @@ -20,17 +20,19 @@ import ( "log" "net/http" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/spf13/cast" + "github.com/mongodb/mongodbatlas-cloudformation-resources/profile" "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/logger" progressevents "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - "github.com/spf13/cast" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) const ( @@ -72,7 +74,7 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: constants.AlreadyExist, - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists}, nil + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists)}, nil } requestBody := admin20231115014.ClusterOutageSimulation{ @@ -131,7 +133,7 @@ func Read(req handler.Request, prevModel *Model, currentModel *Model) (handler.P return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: constants.ResourceNotFound, - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } convertToUIModel(*outageSimulation, currentModel) @@ -172,7 +174,7 @@ func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: constants.ResourceNotFound, - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } simulationObject, res, err := client.Atlas20231115014.ClusterOutageSimulationApi.EndOutageSimulation(context.Background(), projectID, clusterName).Execute() @@ -230,7 +232,7 @@ func validateProgress(client *util.MongoDBClient, currentModel *Model, targetSta return handler.ProgressEvent{ Message: err.Error(), OperationStatus: handler.Failed, - HandlerErrorCode: cloudformation.HandlerErrorCodeServiceInternalError}, nil + HandlerErrorCode: string(types.HandlerErrorCodeServiceInternalError)}, nil } if !isReady { diff --git a/cfn-resources/cluster/cmd/resource/mappings.go b/cfn-resources/cluster/cmd/resource/mappings.go index 61e931539..9fef9ee00 100644 --- a/cfn-resources/cluster/cmd/resource/mappings.go +++ b/cfn-resources/cluster/cmd/resource/mappings.go @@ -22,7 +22,7 @@ import ( admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" "github.com/spf13/cast" "github.com/mongodb/mongodbatlas-cloudformation-resources/util" @@ -595,7 +595,7 @@ func setClusterRequest(currentModel *Model) (*admin20231115014.AdvancedClusterDe return clusterRequest, &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest, + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest), } } clusterRequest.Tags = tags diff --git a/cfn-resources/cluster/cmd/resource/resource.go b/cfn-resources/cluster/cmd/resource/resource.go index d0fe60594..e486448aa 100644 --- a/cfn-resources/cluster/cmd/resource/resource.go +++ b/cfn-resources/cluster/cmd/resource/resource.go @@ -22,13 +22,12 @@ import ( admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" - flex "github.com/mongodb/mongodbatlas-cloudformation-resources/flex-cluster/cmd/resource" - "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" "github.com/spf13/cast" + flex "github.com/mongodb/mongodbatlas-cloudformation-resources/flex-cluster/cmd/resource" "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" @@ -380,7 +379,7 @@ func validateProgress(client *util.MongoDBClient, currentModel *Model, targetSta return handler.ProgressEvent{ Message: err.Error(), OperationStatus: handler.Failed, - HandlerErrorCode: cloudformation.HandlerErrorCodeServiceInternalError}, nil + HandlerErrorCode: string(types.HandlerErrorCodeServiceInternalError)}, nil } if !isReady { diff --git a/cfn-resources/custom-db-role/cmd/resource/resource.go b/cfn-resources/custom-db-role/cmd/resource/resource.go index 611f6fcc8..6325f646f 100644 --- a/cfn-resources/custom-db-role/cmd/resource/resource.go +++ b/cfn-resources/custom-db-role/cmd/resource/resource.go @@ -19,13 +19,15 @@ import ( "fmt" "net/http" + admin20231115002 "go.mongodb.org/atlas-sdk/v20231115002/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" progress_events "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115002 "go.mongodb.org/atlas-sdk/v20231115002/admin" ) func setup() { @@ -58,7 +60,7 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler if err != nil { if apiError, ok := admin20231115002.AsError(err); ok && *apiError.Error == http.StatusConflict { return progress_events.GetFailedEventByCode("Resource already exists", - cloudformation.HandlerErrorCodeAlreadyExists), nil + string(types.HandlerErrorCodeAlreadyExists)), nil } return progress_events.GetFailedEventByResponse(fmt.Sprintf("Error creating resource : %s", err.Error()), diff --git a/cfn-resources/custom-dns-configuration-cluster-aws/cmd/resource/resource.go b/cfn-resources/custom-dns-configuration-cluster-aws/cmd/resource/resource.go index c6503e8c5..1e77a7393 100644 --- a/cfn-resources/custom-dns-configuration-cluster-aws/cmd/resource/resource.go +++ b/cfn-resources/custom-dns-configuration-cluster-aws/cmd/resource/resource.go @@ -19,13 +19,15 @@ import ( "errors" "fmt" + admin20231115002 "go.mongodb.org/atlas-sdk/v20231115002/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115002 "go.mongodb.org/atlas-sdk/v20231115002/admin" ) var RequiredFields = []string{constants.ProjectID} @@ -50,7 +52,7 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler if isCustomAWSDNSSettingExists(currentModel, client) { return progressevent.GetFailedEventByCode(fmt.Sprintf("Custom AWS dns settings already enabled for : %s", *currentModel.ProjectId), - cloudformation.HandlerErrorCodeAlreadyExists), nil + string(types.HandlerErrorCodeAlreadyExists)), nil } // API call to enabled := true @@ -79,7 +81,7 @@ func Read(req handler.Request, prevModel *Model, currentModel *Model) (handler.P enabled := customAWSDNSSetting.Enabled if !enabled { return progressevent.GetFailedEventByCode(fmt.Sprintf("Custom AWS dns settings not found for Project : %s", *currentModel.ProjectId), - cloudformation.HandlerErrorCodeNotFound), nil + string(types.HandlerErrorCodeNotFound)), nil } return handler.ProgressEvent{ @@ -125,7 +127,7 @@ func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler }, nil } return progressevent.GetFailedEventByCode(fmt.Sprintf("Error in disabling Custom AWS DNS settings for Project : %s", *currentModel.ProjectId), - cloudformation.HandlerErrorCodeNotFound), nil + string(types.HandlerErrorCodeNotFound)), nil } // List handles the List event from the Cloudformation service. diff --git a/cfn-resources/go.mod b/cfn-resources/go.mod index 13422660e..84657f404 100644 --- a/cfn-resources/go.mod +++ b/cfn-resources/go.mod @@ -10,6 +10,7 @@ require ( github.com/aws/aws-sdk-go v1.55.7 github.com/aws/aws-sdk-go-v2 v1.40.0 github.com/aws/aws-sdk-go-v2/config v1.32.1 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.39.9 github.com/aws/aws-sdk-go-v2/service/cloudformation v1.71.1 github.com/aws/smithy-go v1.23.2 github.com/dave/jennifer v1.7.1 diff --git a/cfn-resources/go.sum b/cfn-resources/go.sum index f4aee7f7a..27fa3291a 100644 --- a/cfn-resources/go.sum +++ b/cfn-resources/go.sum @@ -24,6 +24,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 h1:x2Ibm/A github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3/go.mod h1:IW1jwyrQgMdhisceG8fQLmQIydcT/jWY21rFhzgaKwo= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.14 h1:FIouAnCE46kyYqyhs0XEBDFFSREtdnr8HQuLPQPLCrY= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.14/go.mod h1:UTwDc5COa5+guonQU8qBikJo1ZJ4ln2r1MkF7Dqag1E= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.39.9 h1:SateVRwzAULF812BCR6+DZ77n8KBlbQoKNiqJvfbAII= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.39.9/go.mod h1:uyJVFSxMat78YTaaz+ROx+FI+K78Qa7VyEQmt8hBSWI= github.com/aws/aws-sdk-go-v2/service/signin v1.0.1 h1:BDgIUYGEo5TkayOWv/oBLPphWwNm/A91AebUjAu5L5g= github.com/aws/aws-sdk-go-v2/service/signin v1.0.1/go.mod h1:iS6EPmNeqCsGo+xQmXv0jIMjyYtQfnwg36zl2FwEouk= github.com/aws/aws-sdk-go-v2/service/sso v1.30.4 h1:U//SlnkE1wOQiIImxzdY5PXat4Wq+8rlfVEw4Y7J8as= diff --git a/cfn-resources/profile/profile.go b/cfn-resources/profile/profile.go index 14c564521..aa06bb21f 100644 --- a/cfn-resources/profile/profile.go +++ b/cfn-resources/profile/profile.go @@ -15,13 +15,16 @@ package profile import ( + "context" "encoding/json" "fmt" "os" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/secretsmanager" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + + "github.com/mongodb/mongodbatlas-cloudformation-resources/util/awsconfig" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" ) @@ -41,12 +44,14 @@ func NewProfile(req *handler.Request, profileName *string, prefixRequired bool) profileName = aws.String(DefaultProfile) } - secretsManagerClient := secretsmanager.New(req.Session) + // Create AWS SDK v2 config using CloudFormation handler's SDK v1 session credentials + cfg := awsconfig.FromHandlerRequest(req) + secretsManagerClient := secretsmanager.NewFromConfig(cfg) secretID := *profileName if prefixRequired { secretID = SecretNameWithPrefix(*profileName) } - resp, err := secretsManagerClient.GetSecretValue(&secretsmanager.GetSecretValueInput{SecretId: &secretID}) + resp, err := secretsManagerClient.GetSecretValue(context.Background(), &secretsmanager.GetSecretValueInput{SecretId: &secretID}) if err != nil { return nil, err } diff --git a/cfn-resources/project/cmd/resource/resource.go b/cfn-resources/project/cmd/resource/resource.go index 36c061e69..f64351366 100644 --- a/cfn-resources/project/cmd/resource/resource.go +++ b/cfn-resources/project/cmd/resource/resource.go @@ -20,13 +20,15 @@ import ( "fmt" "reflect" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) var CreateRequiredFields = []string{constants.OrgID, constants.Name} @@ -86,7 +88,7 @@ func Create(req handler.Request, prevModel *Model, currentModel *Model) (handler for _, key := range currentModel.ProjectApiKeys { if key.Key == nil { errorMessage := fmt.Sprintf("ApiKey is missing the configuration for projectID=%s", projectID) - return progressevent.GetFailedEventByCode(errorMessage, cloudformation.HandlerErrorCodeInvalidRequest), nil + return progressevent.GetFailedEventByCode(errorMessage, string(types.HandlerErrorCodeInvalidRequest)), nil } apiKey := *key.Key _, res, err := atlasV2.ProgrammaticAPIKeysApi.UpdateApiKeyRoles(context.Background(), projectID, apiKey, &admin20231115014.UpdateAtlasProjectApiKey{ @@ -196,7 +198,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (event h return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Error while finding teams in project", - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } if teamsAssigned != nil && teamsAssigned.Results != nil { errorMessage, err := changeProjectTeams(*atlasV2, currentModel, teamsAssigned.GetResults()) @@ -204,7 +206,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (event h return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: errorMessage, - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest, + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest), }, nil } } @@ -219,7 +221,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (event h return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: fmt.Sprintf("Error while Un-assigning Key to project %s", err.Error()), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } } @@ -231,7 +233,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (event h return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: fmt.Sprintf("Error while Assigning Key to project %s", err.Error()), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } } @@ -243,7 +245,7 @@ func Update(req handler.Request, prevModel *Model, currentModel *Model) (event h return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: fmt.Sprintf("Error while Assigning Key to project %s", err.Error()), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest}, nil + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)}, nil } } } @@ -337,10 +339,10 @@ func updateProject(client *admin20231115014.APIClient, currentModel *Model) (eve } project, res, err := client.ProjectsApi.UpdateProject(context.Background(), *currentModel.Id, &projectUpdate).Execute() if err != nil { - if res.StatusCode == 401 { // cfn test + if res != nil && res.StatusCode == 401 { // cfn test return progressevent.GetFailedEventByCode( "Unauthorized Error: Unable to update project name. Please verify that the API keys provided in the profile have sufficient privileges to access the project.", - cloudformation.HandlerErrorCodeNotFound), nil, err + string(types.HandlerErrorCodeNotFound)), nil, err } return progressevent.GetFailedEventByResponse(err.Error(), res), project, err @@ -351,10 +353,10 @@ func updateProject(client *admin20231115014.APIClient, currentModel *Model) (eve func getProjectByID(id *string, atlasV2 *admin20231115014.APIClient) (event handler.ProgressEvent, model *admin20231115014.Group, err error) { project, res, err := atlasV2.ProjectsApi.GetProject(context.Background(), *id).Execute() if err != nil { - if res.StatusCode == 401 { // cfn test + if res != nil && res.StatusCode == 401 { // cfn test return progressevent.GetFailedEventByCode( "Unauthorized Error: Unable to retrieve Project by ID. Please verify that the API keys provided in the profile have sufficient privileges to access the project.", - cloudformation.HandlerErrorCodeNotFound), nil, err + string(types.HandlerErrorCodeNotFound)), nil, err } return progressevent.GetFailedEventByResponse(err.Error(), res), project, err diff --git a/cfn-resources/search-deployment/cmd/resource/resource.go b/cfn-resources/search-deployment/cmd/resource/resource.go index 8fbfb20cc..651e0b128 100644 --- a/cfn-resources/search-deployment/cmd/resource/resource.go +++ b/cfn-resources/search-deployment/cmd/resource/resource.go @@ -20,13 +20,15 @@ import ( "net/http" "strings" + admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" + "github.com/mongodb/mongodbatlas-cloudformation-resources/util" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/validator" - admin20231115014 "go.mongodb.org/atlas-sdk/v20231115014/admin" ) const ( @@ -171,13 +173,13 @@ func handleError(res *http.Response, err error) (handler.ProgressEvent, error) { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists}, nil + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists)}, nil } if apiError, ok := admin20231115014.AsError(err); ok && *apiError.Error == http.StatusBadRequest && strings.Contains(*apiError.ErrorCode, SearchDeploymentDoesNotExistsError) { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)}, nil } return progressevent.GetFailedEventByResponse(err.Error(), res), nil } diff --git a/cfn-resources/util/aws/utils.go b/cfn-resources/util/aws/utils.go index 4e7eec4c4..fab47b2e3 100644 --- a/cfn-resources/util/aws/utils.go +++ b/cfn-resources/util/aws/utils.go @@ -19,8 +19,8 @@ import ( "strings" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/aws-sdk-go/service/ec2" progress_events "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" ) @@ -70,7 +70,7 @@ func CreatePrivateEndpoint(req handler.Request, endpointServiceName string, regi vpcE, err := svc.CreateVpcEndpoint(&connection) if err != nil { fpe := progress_events.GetFailedEventByCode(fmt.Sprintf("Error creating vcp Endpoint: %s", err.Error()), - cloudformation.HandlerErrorCodeGeneralServiceException) + string(types.HandlerErrorCodeGeneralServiceException)) return nil, &fpe } @@ -101,7 +101,7 @@ func DeletePrivateEndpoint(req handler.Request, interfaceEndpoints []string, reg if err != nil { fpe := progress_events.GetFailedEventByCode(fmt.Sprintf("Error deleting vcp Endpoint: %s", err.Error()), - cloudformation.HandlerErrorCodeGeneralServiceException) + string(types.HandlerErrorCodeGeneralServiceException)) return &fpe } diff --git a/cfn-resources/util/awsconfig/awsconfig.go b/cfn-resources/util/awsconfig/awsconfig.go new file mode 100644 index 000000000..4e4023c96 --- /dev/null +++ b/cfn-resources/util/awsconfig/awsconfig.go @@ -0,0 +1,47 @@ +// Copyright 2023 MongoDB Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package awsconfig provides utilities for creating AWS SDK v2 configurations +// from CloudFormation handler requests. +package awsconfig + +import ( + "context" + "fmt" + + "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" + "github.com/aws/aws-sdk-go-v2/aws" +) + +// FromHandlerRequest creates an AWS SDK v2 config using the CloudFormation handler's SDK v1 session. +// +// The cloudformation-cli-go-plugin provides credentials via handler.Request.Session, +// which is an AWS SDK v1 session. This function bridges those credentials to SDK v2 +// using a provider that fetches credentials on each AWS API call. +func FromHandlerRequest(req *handler.Request) aws.Config { + return aws.Config{ + Region: aws.ToString(req.Session.Config.Region), + Credentials: aws.CredentialsProviderFunc(func(ctx context.Context) (aws.Credentials, error) { + v1Creds, err := req.Session.Config.Credentials.Get() + if err != nil { + return aws.Credentials{}, fmt.Errorf("failed to get credentials from CloudFormation handler session: %w", err) + } + return aws.Credentials{ + AccessKeyID: v1Creds.AccessKeyID, + SecretAccessKey: v1Creds.SecretAccessKey, + SessionToken: v1Creds.SessionToken, + }, nil + }), + } +} diff --git a/cfn-resources/util/cluster_common.go b/cfn-resources/util/cluster_common.go index 28a51a2b8..a64de9c63 100644 --- a/cfn-resources/util/cluster_common.go +++ b/cfn-resources/util/cluster_common.go @@ -19,7 +19,7 @@ import ( "strings" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/constants" "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" ) @@ -31,13 +31,13 @@ func HandleClusterError(err error, resp *http.Response) *handler.ProgressEvent { } pe := progressevent.GetFailedEventByResponse(err.Error(), resp) if resp != nil && resp.StatusCode == http.StatusBadRequest && strings.Contains(err.Error(), constants.Duplicate) { - pe.HandlerErrorCode = cloudformation.HandlerErrorCodeAlreadyExists + pe.HandlerErrorCode = string(types.HandlerErrorCodeAlreadyExists) } if resp != nil && resp.StatusCode == http.StatusNotFound { - pe.HandlerErrorCode = cloudformation.HandlerErrorCodeNotFound + pe.HandlerErrorCode = string(types.HandlerErrorCodeNotFound) } if strings.Contains(err.Error(), "not exist") || strings.Contains(err.Error(), "being deleted") { - pe.HandlerErrorCode = cloudformation.HandlerErrorCodeNotFound + pe.HandlerErrorCode = string(types.HandlerErrorCodeNotFound) } return &pe } diff --git a/cfn-resources/util/deployment_secret.go b/cfn-resources/util/deployment_secret.go index 103d1f08e..ccff9fb7b 100644 --- a/cfn-resources/util/deployment_secret.go +++ b/cfn-resources/util/deployment_secret.go @@ -15,13 +15,16 @@ package util import ( + "context" "encoding/json" "log" "os" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/secretsmanager" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + + "github.com/mongodb/mongodbatlas-cloudformation-resources/util/awsconfig" ) type DeploymentSecret struct { @@ -46,19 +49,16 @@ func CreateDeploymentSecret(req *handler.Request, cfnID *ResourceIdentifier, pub log.Printf("%+v", os.Environ()) log.Println("===============================================") - // sess := credentials.SessionFromCredentialsProvider(creds) - // create a new secret from this struct with the json string - - // Create service client value configured for credentials - // from assumed role. - svc := secretsmanager.New(req.Session) + // Create service client using credentials from the CloudFormation handler's session + cfg := awsconfig.FromHandlerRequest(req) + svc := secretsmanager.NewFromConfig(cfg) input := &secretsmanager.CreateSecretInput{ Description: aws.String("MongoDB Atlas Quickstart Deployment Secret"), Name: aws.String(cfnID.String()), SecretString: aws.String(string(deploySecretString)), } - result, err := svc.CreateSecret(input) + result, err := svc.CreateSecret(context.Background(), input) if err != nil { // Print the error, cast err to awserr. Error to get the Code and // Message from an error. @@ -70,8 +70,9 @@ func CreateDeploymentSecret(req *handler.Request, cfnID *ResourceIdentifier, pub } func GetAPIKeyFromDeploymentSecret(req *handler.Request, secretName string) (DeploymentSecret, error) { - sm := secretsmanager.New(req.Session) - output, err := sm.GetSecretValue(&secretsmanager.GetSecretValueInput{SecretId: &secretName}) + cfg := awsconfig.FromHandlerRequest(req) + sm := secretsmanager.NewFromConfig(cfg) + output, err := sm.GetSecretValue(context.Background(), &secretsmanager.GetSecretValueInput{SecretId: &secretName}) if err != nil { log.Printf("Error --- %v", err.Error()) return DeploymentSecret{}, err diff --git a/cfn-resources/util/progressevent/failed_event.go b/cfn-resources/util/progressevent/failed_event.go index d5fdeaae2..adfd406de 100644 --- a/cfn-resources/util/progressevent/failed_event.go +++ b/cfn-resources/util/progressevent/failed_event.go @@ -18,21 +18,21 @@ import ( "net/http" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" ) func getHandlerErrorCode(response *http.Response) string { switch response.StatusCode { case http.StatusBadRequest: - return cloudformation.HandlerErrorCodeInvalidRequest + return string(types.HandlerErrorCodeInvalidRequest) case http.StatusNotFound: - return cloudformation.HandlerErrorCodeNotFound + return string(types.HandlerErrorCodeNotFound) case http.StatusInternalServerError: - return cloudformation.HandlerErrorCodeServiceInternalError + return string(types.HandlerErrorCodeServiceInternalError) case http.StatusPaymentRequired, http.StatusUnauthorized: - return cloudformation.HandlerErrorCodeAccessDenied + return string(types.HandlerErrorCodeAccessDenied) default: - return cloudformation.HandlerErrorCodeInternalFailure + return string(types.HandlerErrorCodeInternalFailure) } } @@ -41,28 +41,28 @@ func GetFailedEventByResponse(message string, response *http.Response) handler.P return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: message, - HandlerErrorCode: cloudformation.HandlerErrorCodeHandlerInternalFailure} + HandlerErrorCode: string(types.HandlerErrorCodeHandlerInternalFailure)} } if response.StatusCode == http.StatusConflict { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: message, - HandlerErrorCode: cloudformation.HandlerErrorCodeAlreadyExists} + HandlerErrorCode: string(types.HandlerErrorCodeAlreadyExists)} } if response.StatusCode == http.StatusUnauthorized { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: "Not found", - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound} + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)} } if response.StatusCode == http.StatusBadRequest { return handler.ProgressEvent{ OperationStatus: handler.Failed, Message: message, - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound} + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)} } return handler.ProgressEvent{ diff --git a/cfn-resources/util/util.go b/cfn-resources/util/util.go index 4930c1778..3836663e1 100644 --- a/cfn-resources/util/util.go +++ b/cfn-resources/util/util.go @@ -32,10 +32,8 @@ import ( "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/logging" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudformation" - "github.com/aws/aws-sdk-go/service/ssm" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" "github.com/mongodb-forks/digest" "github.com/mongodb-labs/go-client-mongodb-atlas-app-services/appservices" appServicesAuth "github.com/mongodb-labs/go-client-mongodb-atlas-app-services/auth" @@ -140,7 +138,7 @@ func newAtlasV2Client(req *handler.Request, profileName *string, profileNamePref return nil, &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound} + HandlerErrorCode: string(types.HandlerErrorCodeNotFound)} } // setup a transport to handle digest @@ -152,7 +150,7 @@ func newAtlasV2Client(req *handler.Request, profileName *string, profileNamePref return nil, &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest} + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)} } c := Config{BaseURL: prof.BaseURL, DebugClient: prof.UseDebug()} @@ -163,7 +161,7 @@ func newAtlasV2Client(req *handler.Request, profileName *string, profileNamePref return nil, &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest} + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)} } // new V2 version 20231115014 instance @@ -172,7 +170,7 @@ func newAtlasV2Client(req *handler.Request, profileName *string, profileNamePref return nil, &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest} + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)} } // latest V2 instance @@ -181,7 +179,7 @@ func newAtlasV2Client(req *handler.Request, profileName *string, profileNamePref return nil, &handler.ProgressEvent{ OperationStatus: handler.Failed, Message: err.Error(), - HandlerErrorCode: cloudformation.HandlerErrorCodeInvalidRequest} + HandlerErrorCode: string(types.HandlerErrorCodeInvalidRequest)} } clients := &MongoDBClient{ @@ -281,36 +279,10 @@ func ToStringMapE(ep any) (map[string]any, error) { return eMap, nil } -func CreateSSManagerClient(curSession *session.Session) (*ssm.SSM, error) { - ssmCli := ssm.New(curSession) - return ssmCli, nil -} - -func Get(keyID, prefix string, curSession *session.Session) string { - ssmClient, err := CreateSSManagerClient(curSession) - if err != nil { - return "" - } - parameterName := buildKey(keyID, prefix) - decrypt := true - getParamOutput, err := ssmClient.GetParameter(&ssm.GetParameterInput{Name: ¶meterName, WithDecryption: &decrypt}) - if err != nil { - return "" - } - - return *getParamOutput.Parameter.Value -} - func Pointer[T any](x T) *T { return &x } -func buildKey(keyID, storePrefix string) string { - // this is strictly coupled with permissions for handlers, changing this means changing permissions in handler - // moreover changing this might cause pollution in parameter store - be sure you know what you are doing - return fmt.Sprintf("%s-%s", storePrefix, keyID) -} - // Contains checks if a string is present in a slice func Contains(s []string, str string) bool { for _, v := range s { diff --git a/cfn-resources/util/validator/validator.go b/cfn-resources/util/validator/validator.go index 3b87b17b0..07ead5666 100644 --- a/cfn-resources/util/validator/validator.go +++ b/cfn-resources/util/validator/validator.go @@ -20,7 +20,7 @@ import ( "strings" "github.com/aws-cloudformation/cloudformation-cli-go-plugin/cfn/handler" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" progressevents "github.com/mongodb/mongodbatlas-cloudformation-resources/util/progressevent" ) @@ -37,7 +37,7 @@ func ValidateModel(fields []string, model interface{}) *handler.ProgressEvent { } progressEvent := progressevents.GetFailedEventByCode(fmt.Sprintf("The next fields are required%s", requiredFields), - cloudformation.HandlerErrorCodeInvalidRequest) + string(types.HandlerErrorCodeInvalidRequest)) return &progressEvent }