|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/aws/aws-sdk-go-v2/aws" |
| 9 | + "github.com/aws/aws-sdk-go-v2/service/cloudformation" |
| 10 | + types "github.com/aws/aws-sdk-go-v2/service/cloudformation/types" |
| 11 | +) |
| 12 | + |
| 13 | +// TODO: implement AWS client wrappers, and incorporate this into the cfn:CreateStack call |
| 14 | +func WrapCFNStackFailure(ctx context.Context, cfnClient *cloudformation.Client, createStackErr error, stackName string) error { |
| 15 | + if createStackErr == nil { |
| 16 | + return nil |
| 17 | + } |
| 18 | + resourceByFailureMode := make(map[string][]string) |
| 19 | + eventsPaginator := cloudformation.NewDescribeStackEventsPaginator(cfnClient, &cloudformation.DescribeStackEventsInput{ |
| 20 | + StackName: &stackName, |
| 21 | + }) |
| 22 | + for eventsPaginator.HasMorePages() { |
| 23 | + page, err := eventsPaginator.NextPage(ctx) |
| 24 | + if err != nil { |
| 25 | + return createStackErr |
| 26 | + } |
| 27 | + for _, event := range page.StackEvents { |
| 28 | + if event.ResourceStatus == types.ResourceStatusCreateFailed { |
| 29 | + if _, ok := resourceByFailureMode[aws.ToString(event.ResourceStatusReason)]; !ok { |
| 30 | + resourceByFailureMode[aws.ToString(event.ResourceStatusReason)] = []string{} |
| 31 | + } |
| 32 | + resourceByFailureMode[aws.ToString(event.ResourceStatusReason)] = append(resourceByFailureMode[aws.ToString(event.ResourceStatusReason)], aws.ToString(event.LogicalResourceId)) |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + nonCancellationFailure := len(resourceByFailureMode) > 1 |
| 37 | + var enhancedDetails []string |
| 38 | + for reason, resources := range resourceByFailureMode { |
| 39 | + if nonCancellationFailure && reason == "Resource creation cancelled" { |
| 40 | + // Ignore resource cancellation errors if there's another failure reported, those failures |
| 41 | + // would just be a consequence of that failure. If all the failures are resource cancellation, |
| 42 | + // then there was likely a user initiated delete of the whole stack based on a timeout |
| 43 | + // waiting for one of the resources to create |
| 44 | + continue |
| 45 | + } |
| 46 | + enhancedDetails = append(enhancedDetails, fmt.Sprintf("%s: %s", strings.Join(resources, ","), reason)) |
| 47 | + } |
| 48 | + return fmt.Errorf("%w: %s", createStackErr, strings.Join(enhancedDetails, "--")) |
| 49 | +} |
0 commit comments