From 08e4431ae72af2cbf14d34fb805f5762cf669caa Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 12:38:01 -0800 Subject: [PATCH 001/106] Documentation update --- docs/data-handling-and-conversion.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/data-handling-and-conversion.md b/docs/data-handling-and-conversion.md index 508485933cd..a610e16164a 100644 --- a/docs/data-handling-and-conversion.md +++ b/docs/data-handling-and-conversion.md @@ -65,7 +65,7 @@ To further understand the necessary data conversions used throughout the Terrafo | `list` | `[]*T` | `TypeList` (`[]interface{}` of `T`)
`TypeSet` (`*schema.Set` of `T`) | `list(any)`
`set(any)` | | `map` | `map[T1]*T2` | `TypeMap` (`map[string]interface{}`) | `map(any)` | | `string` | `*string` | `TypeString` (`string`) | `string` | -| `structure` | `struct` | `TypeList` (`[]interface{}` of `map[string]interface{}`) | `list(object(any))` | +| `structure` | `struct` | `TypeList` (`[]interface{}` of `map[string]interface{}`) with `MaxItems: 1` | `list(object(any))` | | `timestamp` | `*time.Time` | `TypeString` (typically RFC3339 formatted) | `string` | From 71649e80b60eb8aca66e81601d70891eaf41ab56 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 14:04:18 -0800 Subject: [PATCH 002/106] Fixes bare errors in `route53` --- internal/service/route53/record.go | 134 +++++++++-------------------- 1 file changed, 40 insertions(+), 94 deletions(-) diff --git a/internal/service/route53/record.go b/internal/service/route53/record.go index d79d04eb1a1..346d4799f49 100644 --- a/internal/service/route53/record.go +++ b/internal/service/route53/record.go @@ -1,7 +1,6 @@ package route53 import ( - "bytes" "errors" "fmt" "log" @@ -17,7 +16,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" - "github.com/hashicorp/terraform-provider-aws/internal/create" "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) @@ -79,6 +77,7 @@ func ResourceRecord() *schema.Resource { Type: schema.TypeInt, Optional: true, ConflictsWith: []string{"alias"}, + RequiredWith: []string{"records", "ttl"}, }, "set_identifier": { @@ -87,9 +86,11 @@ func ResourceRecord() *schema.Resource { }, "alias": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, - ConflictsWith: []string{"records", "ttl"}, + MaxItems: 1, + ExactlyOneOf: []string{"alias", "records"}, + ConflictsWith: []string{"ttl"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "zone_id": { @@ -114,11 +115,11 @@ func ResourceRecord() *schema.Resource { }, }, }, - Set: resourceAliasRecordHash, }, "failover_routing_policy": { Type: schema.TypeList, + MaxItems: 1, Optional: true, ConflictsWith: []string{ "geolocation_routing_policy", @@ -126,6 +127,7 @@ func ResourceRecord() *schema.Resource { "weighted_routing_policy", "multivalue_answer_routing_policy", }, + RequiredWith: []string{"set_identifier"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "type": { @@ -145,6 +147,7 @@ func ResourceRecord() *schema.Resource { "latency_routing_policy": { Type: schema.TypeList, + MaxItems: 1, Optional: true, ConflictsWith: []string{ "failover_routing_policy", @@ -152,6 +155,7 @@ func ResourceRecord() *schema.Resource { "weighted_routing_policy", "multivalue_answer_routing_policy", }, + RequiredWith: []string{"set_identifier"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "region": { @@ -164,6 +168,7 @@ func ResourceRecord() *schema.Resource { "geolocation_routing_policy": { // AWS Geolocation Type: schema.TypeList, + MaxItems: 1, Optional: true, ConflictsWith: []string{ "failover_routing_policy", @@ -171,6 +176,7 @@ func ResourceRecord() *schema.Resource { "weighted_routing_policy", "multivalue_answer_routing_policy", }, + RequiredWith: []string{"set_identifier"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "continent": { @@ -191,6 +197,7 @@ func ResourceRecord() *schema.Resource { "weighted_routing_policy": { Type: schema.TypeList, + MaxItems: 1, Optional: true, ConflictsWith: []string{ "failover_routing_policy", @@ -198,6 +205,7 @@ func ResourceRecord() *schema.Resource { "latency_routing_policy", "multivalue_answer_routing_policy", }, + RequiredWith: []string{"set_identifier"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "weight": { @@ -217,6 +225,7 @@ func ResourceRecord() *schema.Resource { "latency_routing_policy", "weighted_routing_policy", }, + RequiredWith: []string{"set_identifier"}, }, "health_check_id": { // ID of health check @@ -225,11 +234,11 @@ func ResourceRecord() *schema.Resource { }, "records": { - Type: schema.TypeSet, - ConflictsWith: []string{"alias"}, - Elem: &schema.Schema{Type: schema.TypeString}, - Optional: true, - Set: schema.HashString, + Type: schema.TypeSet, + ExactlyOneOf: []string{"alias", "records"}, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + Set: schema.HashString, }, "allow_overwrite": { @@ -260,13 +269,9 @@ func resourceRecordUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).Route53Conn() zone := CleanZoneID(d.Get("zone_id").(string)) - var err error - zoneRecord, err := conn.GetHostedZone(&route53.GetHostedZoneInput{Id: aws.String(zone)}) + zoneRecord, err := FindHostedZoneByID(conn, zone) if err != nil { - return err - } - if zoneRecord.HostedZone == nil { - return fmt.Errorf("No Route53 Zone found for id (%s)", zone) + return fmt.Errorf("updating Route 53 Record (%s): getting Hosted Zone (%s): %w", d.Id(), zone, err) } // Build the to be deleted record @@ -348,7 +353,7 @@ func resourceRecordUpdate(d *schema.ResourceData, meta interface{}) error { // Alias record if v, _ := d.GetChange("alias"); v != nil { - aliases := v.(*schema.Set).List() + aliases := v.([]interface{}) if len(aliases) == 1 { alias := aliases[0].(map[string]interface{}) oldRec.AliasTarget = &route53.AliasTarget{ @@ -369,10 +374,7 @@ func resourceRecordUpdate(d *schema.ResourceData, meta interface{}) error { } // Build the to be created record - rec, err := resourceRecordBuildSet(d, aws.StringValue(zoneRecord.HostedZone.Name)) - if err != nil { - return err - } + rec := resourceRecordBuildSet(d, aws.StringValue(zoneRecord.HostedZone.Name)) // Delete the old and create the new records in a single batch. We abuse // StateChangeConf for this to retry for us since Route53 sometimes returns @@ -396,12 +398,11 @@ func resourceRecordUpdate(d *schema.ResourceData, meta interface{}) error { ChangeBatch: changeBatch, } - log.Printf("[DEBUG] Updating resource records for zone: %s, name: %s\n\n%s", - zone, aws.StringValue(rec.Name), input) + log.Printf("[DEBUG] Updating resource records for zone: %s, name: %s", zone, aws.StringValue(rec.Name)) respRaw, err := ChangeRecordSet(conn, input) if err != nil { - return fmt.Errorf("[ERR]: Error building changeset: %w", err) + return fmt.Errorf("updating Route 53 Record (%s): updating record set: : %w", d.Id(), err) } changeInfo := respRaw.(*route53.ChangeResourceRecordSetsOutput).ChangeInfo @@ -418,33 +419,27 @@ func resourceRecordUpdate(d *schema.ResourceData, meta interface{}) error { d.SetId(strings.Join(vars, "_")) - err = WaitForRecordSetToSync(conn, CleanChangeID(aws.StringValue(changeInfo.Id))) - if err != nil { - return err + if err := WaitForRecordSetToSync(conn, CleanChangeID(aws.StringValue(changeInfo.Id))); err != nil { + return fmt.Errorf("updating Route 53 Record (%s): updating record set: waiting for completion: %w", d.Id(), err) } - _, err = findRecord(d, meta) - return err + if _, err := findRecord(d, meta); err != nil { + return fmt.Errorf("updating Route 53 Record (%s): %w", d.Id(), err) + } + return nil } func resourceRecordCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).Route53Conn() zone := CleanZoneID(d.Get("zone_id").(string)) - var err error - zoneRecord, err := conn.GetHostedZone(&route53.GetHostedZoneInput{Id: aws.String(zone)}) + zoneRecord, err := FindHostedZoneByID(conn, zone) if err != nil { - return err - } - if zoneRecord.HostedZone == nil { - return fmt.Errorf("No Route53 Zone found for id (%s)", zone) + return fmt.Errorf("creating Route 53 Record (%s): getting Hosted Zone (%s): %w", d.Id(), zone, err) } // Build the record - rec, err := resourceRecordBuildSet(d, aws.StringValue(zoneRecord.HostedZone.Name)) - if err != nil { - return err - } + rec := resourceRecordBuildSet(d, aws.StringValue(zoneRecord.HostedZone.Name)) // Protect existing DNS records which might be managed in another way. // Use UPSERT only if the overwrite flag is true or if the current action is an update @@ -554,7 +549,7 @@ func resourceRecordRead(d *schema.ResourceData, meta interface{}) error { // We check that we have parsed the id into the correct number of segments. // We need at least 3 segments! if parts[0] == "" || parts[1] == "" || parts[2] == "" { - return fmt.Errorf("Error Importing aws_route_53 record. Please make sure the record ID is in the form ZONEID_RECORDNAME_TYPE_SET-IDENTIFIER (e.g. Z4KAPRWWNC7JR_dev.example.com_NS_dev), where SET-IDENTIFIER is optional") + return fmt.Errorf("importing aws_route_53 record. Please make sure the record ID is in the form ZONEID_RECORDNAME_TYPE_SET-IDENTIFIER (e.g. Z4KAPRWWNC7JR_dev.example.com_NS_dev), where SET-IDENTIFIER is optional") } d.Set("zone_id", parts[0]) @@ -569,7 +564,7 @@ func resourceRecordRead(d *schema.ResourceData, meta interface{}) error { if err != nil { switch err { case errNoHostedZoneFound, errNoRecordsFound: - log.Printf("[DEBUG] %s for: %s, removing from state file", err, d.Id()) + log.Printf("[WARN] Route 53 Record (%s) not found, removing from state", d.Id()) d.SetId("") return nil default: @@ -579,7 +574,7 @@ func resourceRecordRead(d *schema.ResourceData, meta interface{}) error { err = d.Set("records", FlattenResourceRecords(record.ResourceRecords, aws.StringValue(record.Type))) if err != nil { - return fmt.Errorf("Error setting records for: %s, error: %w", d.Id(), err) + return fmt.Errorf("setting records: %w", err) } if alias := record.AliasTarget; alias != nil { @@ -816,7 +811,7 @@ func DeleteRecordSet(conn *route53.Route53, input *route53.ChangeResourceRecordS return out, err } -func resourceRecordBuildSet(d *schema.ResourceData, zoneName string) (*route53.ResourceRecordSet, error) { +func resourceRecordBuildSet(d *schema.ResourceData, zoneName string) *route53.ResourceRecordSet { // get expanded name en := ExpandRecordName(d.Get("name").(string), zoneName) @@ -841,35 +836,17 @@ func resourceRecordBuildSet(d *schema.ResourceData, zoneName string) (*route53.R // Alias record if v, ok := d.GetOk("alias"); ok { - aliases := v.(*schema.Set).List() - if len(aliases) > 1 { - return nil, fmt.Errorf("You can only define a single alias target per record") - } + aliases := v.([]interface{}) alias := aliases[0].(map[string]interface{}) rec.AliasTarget = &route53.AliasTarget{ DNSName: aws.String(alias["name"].(string)), EvaluateTargetHealth: aws.Bool(alias["evaluate_target_health"].(bool)), HostedZoneId: aws.String(alias["zone_id"].(string)), } - log.Printf("[DEBUG] Creating alias: %#v", alias) - } else { - if _, ok := d.GetOk("ttl"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "ttl": required field is not set`, d.Get("name").(string)) - } - - if _, ok := d.GetOk("records"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "records": required field is not set`, d.Get("name").(string)) - } } if v, ok := d.GetOk("failover_routing_policy"); ok { - if _, ok := d.GetOk("set_identifier"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "set_identifier": required field is not set when "failover_routing_policy" is set`, d.Get("name").(string)) - } records := v.([]interface{}) - if len(records) > 1 { - return nil, fmt.Errorf("You can only define a single failover_routing_policy per record") - } failover := records[0].(map[string]interface{}) rec.Failover = aws.String(failover["type"].(string)) @@ -880,13 +857,7 @@ func resourceRecordBuildSet(d *schema.ResourceData, zoneName string) (*route53.R } if v, ok := d.GetOk("weighted_routing_policy"); ok { - if _, ok := d.GetOk("set_identifier"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "set_identifier": required field is not set when "weighted_routing_policy" is set`, d.Get("name").(string)) - } records := v.([]interface{}) - if len(records) > 1 { - return nil, fmt.Errorf("You can only define a single weighted_routing_policy per record") - } weight := records[0].(map[string]interface{}) rec.Weight = aws.Int64(int64(weight["weight"].(int))) @@ -897,26 +868,14 @@ func resourceRecordBuildSet(d *schema.ResourceData, zoneName string) (*route53.R } if v, ok := d.GetOk("latency_routing_policy"); ok { - if _, ok := d.GetOk("set_identifier"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "set_identifier": required field is not set when "latency_routing_policy" is set`, d.Get("name").(string)) - } records := v.([]interface{}) - if len(records) > 1 { - return nil, fmt.Errorf("You can only define a single latency_routing_policy per record") - } latency := records[0].(map[string]interface{}) rec.Region = aws.String(latency["region"].(string)) } if v, ok := d.GetOk("geolocation_routing_policy"); ok { - if _, ok := d.GetOk("set_identifier"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "set_identifier": required field is not set when "geolocation_routing_policy" is set`, d.Get("name").(string)) - } geolocations := v.([]interface{}) - if len(geolocations) > 1 { - return nil, fmt.Errorf("You can only define a single geolocation_routing_policy per record") - } geolocation := geolocations[0].(map[string]interface{}) rec.GeoLocation = &route53.GeoLocation{ @@ -928,13 +887,10 @@ func resourceRecordBuildSet(d *schema.ResourceData, zoneName string) (*route53.R } if v, ok := d.GetOk("multivalue_answer_routing_policy"); ok { - if _, ok := d.GetOk("set_identifier"); !ok { - return nil, fmt.Errorf(`provider.aws: aws_route53_record: %s: "set_identifier": required field is not set when "multivalue_answer_routing_policy" is set`, d.Get("name").(string)) - } rec.MultiValueAnswer = aws.Bool(v.(bool)) } - return rec, nil + return rec } func FQDN(name string) string { @@ -974,16 +930,6 @@ func ExpandRecordName(name, zone string) string { return rn } -func resourceAliasRecordHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", NormalizeAliasName(m["name"].(string)))) - buf.WriteString(fmt.Sprintf("%s-", m["zone_id"].(string))) - buf.WriteString(fmt.Sprintf("%t-", m["evaluate_target_health"].(bool))) - - return create.StringHashcode(buf.String()) -} - // nilString takes a string as an argument and returns a string // pointer. The returned pointer is nil if the string argument is // empty. Otherwise, it is a pointer to a copy of the string. From a2fac30d032c008bafb5f2fef8a941215053237c Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 14:28:46 -0800 Subject: [PATCH 003/106] Fixes bare errors in `redshift` --- .../service/redshift/snapshot_copy_grant.go | 64 ++++++------------- 1 file changed, 18 insertions(+), 46 deletions(-) diff --git a/internal/service/redshift/snapshot_copy_grant.go b/internal/service/redshift/snapshot_copy_grant.go index c45fb478aa4..52c365bf57d 100644 --- a/internal/service/redshift/snapshot_copy_grant.go +++ b/internal/service/redshift/snapshot_copy_grant.go @@ -83,24 +83,11 @@ func resourceSnapshotCopyGrantCreate(d *schema.ResourceData, meta interface{}) e log.Printf("[DEBUG] Created new Redshift SnapshotCopyGrant: %s", *out.SnapshotCopyGrant.SnapshotCopyGrantName) d.SetId(grantName) - err = resource.Retry(3*time.Minute, func() *resource.RetryError { - var err error - var grant *redshift.SnapshotCopyGrant - grant, err = findSnapshotCopyGrant(conn, grantName) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) || grant == nil { - return resource.RetryableError(err) - } - if err != nil { - return resource.NonRetryableError(err) - } - - return nil + _, err = tfresource.RetryWhenNotFound(3*time.Minute, func() (any, error) { + return findSnapshotCopyGrant(conn, grantName) }) - if tfresource.TimedOut(err) { - _, err = findSnapshotCopyGrant(conn, grantName) - if err != nil { - return err - } + if err != nil { + return fmt.Errorf("creating Redshift Snapshot Copy Grant (%s): waiting for completion: %s", grantName, err) } return resourceSnapshotCopyGrantRead(d, meta) @@ -114,14 +101,13 @@ func resourceSnapshotCopyGrantRead(d *schema.ResourceData, meta interface{}) err grantName := d.Id() grant, err := findSnapshotCopyGrant(conn, grantName) - if !d.IsNewResource() && (tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) || grant == nil) { + if !d.IsNewResource() && tfresource.NotFound(err) { log.Printf("[WARN] Redshift Snapshot Copy Grant (%s) not found, removing from state", grantName) d.SetId("") return nil } - if err != nil { - return err + return fmt.Errorf("reading Redshift Snapshot Copy Grant (%s): %s", grantName, err) } arn := arn.ARN{ @@ -191,30 +177,10 @@ func resourceSnapshotCopyGrantDelete(d *schema.ResourceData, meta interface{}) e // Used by the tests as well func WaitForSnapshotCopyGrantToBeDeleted(conn *redshift.Redshift, grantName string) error { - err := resource.Retry(3*time.Minute, func() *resource.RetryError { - var err error - var grant *redshift.SnapshotCopyGrant - grant, err = findSnapshotCopyGrant(conn, grantName) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) || grant == nil { - return nil - } - if err != nil { - return resource.NonRetryableError(err) - } - - return resource.RetryableError(fmt.Errorf("[DEBUG] Grant still exists while expected to be deleted: %s", grantName)) + _, err := tfresource.RetryUntilNotFound(3*time.Minute, func() (any, error) { + return findSnapshotCopyGrant(conn, grantName) }) - if tfresource.TimedOut(err) { - var grant *redshift.SnapshotCopyGrant - grant, err = findSnapshotCopyGrant(conn, grantName) - if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) || grant == nil { - return nil - } - } - if err != nil { - return fmt.Errorf("Error waiting for snapshot copy grant to be deleted: %s", err) - } - return nil + return err } func findSnapshotCopyGrant(conn *redshift.Redshift, grantName string) (*redshift.SnapshotCopyGrant, error) { @@ -224,12 +190,18 @@ func findSnapshotCopyGrant(conn *redshift.Redshift, grantName string) (*redshift out, err := conn.DescribeSnapshotCopyGrants(&input) - if err != nil { - return nil, err + if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) { + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: input, + } } if out == nil || len(out.SnapshotCopyGrants) == 0 { - return nil, nil + return nil, tfresource.NewEmptyResultError(input) + } + if l := len(out.SnapshotCopyGrants); l > 1 { + return nil, tfresource.NewTooManyResultsError(1, nil) } return out.SnapshotCopyGrants[0], nil From 46f9a44529565dd2742a3a3cb79ccc22562ad669 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 14:38:37 -0800 Subject: [PATCH 004/106] Fixes bare errors in `opsworks` --- internal/service/opsworks/stack.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/internal/service/opsworks/stack.go b/internal/service/opsworks/stack.go index 3333e67a97b..969027a0634 100644 --- a/internal/service/opsworks/stack.go +++ b/internal/service/opsworks/stack.go @@ -320,10 +320,10 @@ func resourceStackRead(d *schema.ResourceData, meta interface{}) error { ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig if v, ok := d.GetOk("stack_endpoint"); ok { + log.Printf(`[DEBUG] overriding region using "stack_endpoint": %s`, v) conn, err = regionalConn(meta.(*conns.AWSClient), v.(string)) - if err != nil { - return err + return fmt.Errorf(`reading OpsWorks Stack (%s): creating client for "stack_endpoint" (%s): %w`, d.Id(), v, err) } } @@ -333,10 +333,11 @@ func resourceStackRead(d *schema.ResourceData, meta interface{}) error { // If it's not found in the default region we're in, we check us-east-1 // in the event this stack was created with Terraform before version 0.9. // See https://github.com/hashicorp/terraform/issues/12842. - conn, err = regionalConn(meta.(*conns.AWSClient), endpoints.UsEast1RegionID) - + v := endpoints.UsEast1RegionID + log.Printf(`[DEBUG] overriding region using legacy region: %s`, v) + conn, err = regionalConn(meta.(*conns.AWSClient), v) if err != nil { - return err + return fmt.Errorf(`reading OpsWorks Stack (%s): creating client for legacy region (%s): %w`, d.Id(), v, err) } stack, err = FindStackByID(conn, d.Id()) @@ -436,9 +437,8 @@ func resourceStackUpdate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("stack_endpoint"); ok { conn, err = regionalConn(meta.(*conns.AWSClient), v.(string)) - if err != nil { - return err + return fmt.Errorf(`updating OpsWorks Stack (%s): creating client for "stack_endpoint" (%s): %w`, d.Id(), v, err) } } @@ -552,9 +552,8 @@ func resourceStackDelete(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("stack_endpoint"); ok { conn, err = regionalConn(meta.(*conns.AWSClient), v.(string)) - if err != nil { - return err + return fmt.Errorf(`deleting OpsWorks Stack (%s): creating client for "stack_endpoint" (%s): %w`, d.Id(), v, err) } } From f2325a5acde5733892804af0203cff8785fa98ac Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 14:42:58 -0800 Subject: [PATCH 005/106] Fixes bare errors in `kms` --- internal/service/kms/alias.go | 3 +- internal/service/kms/arn.go | 2 +- internal/service/kms/ciphertext.go | 6 +- .../service/kms/ciphertext_data_source.go | 8 +- internal/service/kms/external_key.go | 56 +++++++------- internal/service/kms/grant.go | 31 ++++---- internal/service/kms/key.go | 77 ++++++++++--------- internal/service/kms/replica_external_key.go | 49 ++++++------ internal/service/kms/replica_key.go | 19 +++-- 9 files changed, 125 insertions(+), 126 deletions(-) diff --git a/internal/service/kms/alias.go b/internal/service/kms/alias.go index 788d98c6361..e840b497f00 100644 --- a/internal/service/kms/alias.go +++ b/internal/service/kms/alias.go @@ -113,9 +113,8 @@ func resourceAliasRead(d *schema.ResourceData, meta interface{}) error { aliasARN := aws.StringValue(alias.AliasArn) targetKeyID := aws.StringValue(alias.TargetKeyId) targetKeyARN, err := AliasARNToKeyARN(aliasARN, targetKeyID) - if err != nil { - return err + return fmt.Errorf("error reading KMS Alias (%s): %w", d.Id(), err) } d.Set("arn", aliasARN) diff --git a/internal/service/kms/arn.go b/internal/service/kms/arn.go index d54fd3bb334..9024709d734 100644 --- a/internal/service/kms/arn.go +++ b/internal/service/kms/arn.go @@ -17,7 +17,7 @@ func AliasARNToKeyARN(inputARN, keyID string) (string, error) { parsedARN, err := arn.Parse(inputARN) if err != nil { - return "", fmt.Errorf("error parsing ARN (%s): %w", inputARN, err) + return "", fmt.Errorf("parsing ARN (%s): %w", inputARN, err) } if actual, expected := parsedARN.Service, ARNService; actual != expected { diff --git a/internal/service/kms/ciphertext.go b/internal/service/kms/ciphertext.go index 0da562897b9..0bddbea661a 100644 --- a/internal/service/kms/ciphertext.go +++ b/internal/service/kms/ciphertext.go @@ -2,6 +2,7 @@ package kms import ( "encoding/base64" + "fmt" "log" "time" @@ -53,6 +54,7 @@ func resourceCiphertextCreate(d *schema.ResourceData, meta interface{}) error { //lintignore:R017 // Allow legacy unstable ID usage in managed resource d.SetId(time.Now().UTC().String()) + keyID := d.Get("key_id").(string) req := &kms.EncryptInput{ KeyId: aws.String(d.Get("key_id").(string)), Plaintext: []byte(d.Get("plaintext").(string)), @@ -62,10 +64,10 @@ func resourceCiphertextCreate(d *schema.ResourceData, meta interface{}) error { req.EncryptionContext = flex.ExpandStringMap(ec.(map[string]interface{})) } - log.Printf("[DEBUG] KMS encrypt for key: %s", d.Get("key_id").(string)) + log.Printf("[DEBUG] KMS encrypting with KMS Key: %s", keyID) resp, err := conn.Encrypt(req) if err != nil { - return err + return fmt.Errorf("encrypting with KMS Key (%s): %w", keyID, err) } d.Set("ciphertext_blob", base64.StdEncoding.EncodeToString(resp.CiphertextBlob)) diff --git a/internal/service/kms/ciphertext_data_source.go b/internal/service/kms/ciphertext_data_source.go index a2d92c70701..efb82d687d8 100644 --- a/internal/service/kms/ciphertext_data_source.go +++ b/internal/service/kms/ciphertext_data_source.go @@ -2,6 +2,7 @@ package kms import ( "encoding/base64" + "fmt" "log" "github.com/aws/aws-sdk-go/aws" @@ -44,8 +45,9 @@ func DataSourceCiphertext() *schema.Resource { func dataSourceCiphertextRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).KMSConn() + keyID := d.Get("key_id").(string) req := &kms.EncryptInput{ - KeyId: aws.String(d.Get("key_id").(string)), + KeyId: aws.String(keyID), Plaintext: []byte(d.Get("plaintext").(string)), } @@ -53,10 +55,10 @@ func dataSourceCiphertextRead(d *schema.ResourceData, meta interface{}) error { req.EncryptionContext = flex.ExpandStringMap(ec.(map[string]interface{})) } - log.Printf("[DEBUG] KMS encrypt for key: %s", d.Get("key_id").(string)) + log.Printf("[DEBUG] KMS encrypting with KMS Key: %s", keyID) resp, err := conn.Encrypt(req) if err != nil { - return err + return fmt.Errorf("encrypting with KMS Key (%s): %w", keyID, err) } d.SetId(aws.StringValue(resp.KeyId)) diff --git a/internal/service/kms/external_key.go b/internal/service/kms/external_key.go index dc9e759e750..7ae562dc2de 100644 --- a/internal/service/kms/external_key.go +++ b/internal/service/kms/external_key.go @@ -148,14 +148,12 @@ func resourceExternalKeyCreate(d *schema.ResourceData, meta interface{}) error { // KMS will report this error until it can validate the policy itself. // They acknowledge this here: // http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html - log.Printf("[DEBUG] Creating KMS External Key: %s", input) - outputRaw, err := WaitIAMPropagation(func() (interface{}, error) { return conn.CreateKey(input) }) if err != nil { - return fmt.Errorf("error creating KMS External Key: %w", err) + return fmt.Errorf("creating KMS External Key: %w", err) } d.SetId(aws.StringValue(outputRaw.(*kms.CreateKeyOutput).KeyMetadata.KeyId)) @@ -164,22 +162,22 @@ func resourceExternalKeyCreate(d *schema.ResourceData, meta interface{}) error { validTo := d.Get("valid_to").(string) if err := importExternalKeyMaterial(conn, d.Id(), v.(string), validTo); err != nil { - return fmt.Errorf("error importing KMS External Key (%s) material: %w", d.Id(), err) + return fmt.Errorf("importing KMS External Key (%s) material: %w", d.Id(), err) } if _, err := WaitKeyMaterialImported(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) material import: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) material import: %w", d.Id(), err) } if err := WaitKeyValidToPropagated(conn, d.Id(), validTo); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) valid_to propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) valid_to propagation: %w", d.Id(), err) } // The key can only be disabled if key material has been imported, else: // "KMSInvalidStateException: arn:aws:kms:us-west-2:123456789012:key/47e3edc1-945f-413b-88b1-e7341c2d89f7 is pending import." if enabled := d.Get("enabled").(bool); !enabled { if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("creating KMS External Key (%s): %w", d.Id(), err) } } } @@ -187,13 +185,13 @@ func resourceExternalKeyCreate(d *schema.ResourceData, meta interface{}) error { // Wait for propagation since KMS is eventually consistent. if v, ok := d.GetOk("policy"); ok { if err := WaitKeyPolicyPropagated(conn, d.Id(), v.(string)); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) policy propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) policy propagation: %w", d.Id(), err) } } if len(tags) > 0 { if err := WaitTagsPropagated(conn, d.Id(), tags); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) tag propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) tag propagation: %w", d.Id(), err) } } @@ -214,7 +212,7 @@ func resourceExternalKeyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return err + return fmt.Errorf("reading KMS External Key (%s): %w", d.Id(), err) } if keyManager := aws.StringValue(key.metadata.KeyManager); keyManager != kms.KeyManagerTypeCustomer { @@ -255,11 +253,11 @@ func resourceExternalKeyRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -271,19 +269,19 @@ func resourceExternalKeyUpdate(d *schema.ResourceData, meta interface{}) error { if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && enabled && state != kms.KeyStatePendingImport { // Enable before any attributes are modified. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS External Key (%s): %w", d.Id(), err) } } if d.HasChange("description") { if err := updateKeyDescription(conn, d.Id(), d.Get("description").(string)); err != nil { - return err + return fmt.Errorf("updating KMS External Key (%s): %w", d.Id(), err) } } if d.HasChange("policy") { if err := updateKeyPolicy(conn, d.Id(), d.Get("policy").(string), d.Get("bypass_policy_lockout_safety_check").(bool)); err != nil { - return err + return fmt.Errorf("updating KMS External Key (%s): %w", d.Id(), err) } } @@ -291,22 +289,22 @@ func resourceExternalKeyUpdate(d *schema.ResourceData, meta interface{}) error { validTo := d.Get("valid_to").(string) if err := importExternalKeyMaterial(conn, d.Id(), d.Get("key_material_base64").(string), validTo); err != nil { - return fmt.Errorf("error importing KMS External Key (%s) material: %s", d.Id(), err) + return fmt.Errorf("importing KMS External Key (%s) material: %s", d.Id(), err) } if _, err := WaitKeyMaterialImported(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) material import: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) material import: %w", d.Id(), err) } if err := WaitKeyValidToPropagated(conn, d.Id(), validTo); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) valid_to propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) valid_to propagation: %w", d.Id(), err) } } if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && !enabled && state != kms.KeyStatePendingImport { // Only disable after all attributes have been modified because we cannot modify disabled keys. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS External Key (%s): %w", d.Id(), err) } } @@ -314,11 +312,11 @@ func resourceExternalKeyUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating KMS External Key (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating KMS External Key (%s) tags: %w", d.Id(), err) } if err := WaitTagsPropagated(conn, d.Id(), tftags.New(n)); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) tag propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) tag propagation: %w", d.Id(), err) } } @@ -348,11 +346,11 @@ func resourceExternalKeyDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting KMS External Key (%s): %w", d.Id(), err) + return fmt.Errorf("deleting KMS External Key (%s): %w", d.Id(), err) } if _, err := WaitKeyDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS External Key (%s) to delete: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Key (%s) to delete: %w", d.Id(), err) } return nil @@ -369,7 +367,7 @@ func importExternalKeyMaterial(conn *kms.KMS, keyID, keyMaterialBase64, validTo }, kms.ErrCodeNotFoundException) if err != nil { - return fmt.Errorf("error getting parameters for import: %w", err) + return fmt.Errorf("getting parameters for import: %w", err) } output := outputRaw.(*kms.GetParametersForImportOutput) @@ -377,19 +375,19 @@ func importExternalKeyMaterial(conn *kms.KMS, keyID, keyMaterialBase64, validTo keyMaterial, err := base64.StdEncoding.DecodeString(keyMaterialBase64) if err != nil { - return fmt.Errorf("error Base64 decoding key material: %w", err) + return fmt.Errorf("Base64 decoding key material: %w", err) } publicKey, err := x509.ParsePKIXPublicKey(output.PublicKey) if err != nil { - return fmt.Errorf("error parsing public key: %w", err) + return fmt.Errorf("parsing public key: %w", err) } encryptedKeyMaterial, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey.(*rsa.PublicKey), keyMaterial, []byte{}) if err != nil { - return fmt.Errorf("error encrypting key material: %w", err) + return fmt.Errorf("encrypting key material: %w", err) } input := &kms.ImportKeyMaterialInput{ @@ -403,7 +401,7 @@ func importExternalKeyMaterial(conn *kms.KMS, keyID, keyMaterialBase64, validTo t, err := time.Parse(time.RFC3339, validTo) if err != nil { - return fmt.Errorf("error parsing valid_to timestamp: %w", err) + return fmt.Errorf("parsing valid_to timestamp: %w", err) } input.ExpirationModel = aws.String(kms.ExpirationModelTypeKeyMaterialExpires) @@ -416,7 +414,7 @@ func importExternalKeyMaterial(conn *kms.KMS, keyID, keyMaterialBase64, validTo }, kms.ErrCodeNotFoundException) if err != nil { - return fmt.Errorf("error importing key material: %w", err) + return fmt.Errorf("importing key material: %w", err) } return nil diff --git a/internal/service/kms/grant.go b/internal/service/kms/grant.go index 380638f077e..692640cff82 100644 --- a/internal/service/kms/grant.go +++ b/internal/service/kms/grant.go @@ -164,7 +164,7 @@ func resourceGrantCreate(d *schema.ResourceData, meta interface{}) error { tfawserr.ErrCodeEquals(err, kms.ErrCodeInternalException) || tfawserr.ErrCodeEquals(err, kms.ErrCodeInvalidArnException) { return resource.RetryableError( - fmt.Errorf("error creating KMS Grant for Key (%s), retrying: %w", keyId, err)) + fmt.Errorf("creating KMS Grant for Key (%s), retrying: %w", keyId, err)) } return resource.NonRetryableError(err) } @@ -176,7 +176,7 @@ func resourceGrantCreate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error creating KMS Grant for Key (%s): %w", keyId, err) + return fmt.Errorf("creating KMS Grant for Key (%s): %w", keyId, err) } d.SetId(fmt.Sprintf("%s:%s", keyId, aws.StringValue(out.GrantId))) @@ -191,22 +191,22 @@ func resourceGrantRead(d *schema.ResourceData, meta interface{}) error { keyId, grantId, err := decodeGrantID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading KMS Grant (%s): %w", d.Id(), err) } grant, err := findGrantByIdRetry(conn, keyId, grantId) if err != nil { if tfresource.NotFound(err) { - log.Printf("[WARN] KMS Grant (%s) not found for Key (%s), removing from state file", grantId, keyId) + log.Printf("[WARN] KMS Grant (%s) not found for Key (%s), removing from state", grantId, keyId) d.SetId("") return nil } - return err + return fmt.Errorf("reading KMS Grant (%s): %w", d.Id(), err) } if grant == nil { - log.Printf("[WARN] KMS Grant (%s) not found for Key (%s), removing from state file", grantId, keyId) + log.Printf("[WARN] KMS Grant (%s) not found for Key (%s), removing from state", grantId, keyId) d.SetId("") return nil } @@ -249,13 +249,12 @@ func resourceGrantRead(d *schema.ResourceData, meta interface{}) error { func resourceGrantDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).KMSConn() - keyId, grantId, decodeErr := decodeGrantID(d.Id()) - if decodeErr != nil { - return decodeErr + keyId, grantId, err := decodeGrantID(d.Id()) + if err != nil { + return fmt.Errorf("deleting KMS Grant (%s): %w", d.Id(), err) } doRetire := d.Get("retire_on_delete").(bool) - var err error if doRetire { retireInput := kms.RetireGrantInput{ GrantId: aws.String(grantId), @@ -278,13 +277,13 @@ func resourceGrantDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, kms.ErrCodeNotFoundException) { return nil } - return err + return fmt.Errorf("deleting KMS Grant (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Checking if grant is revoked: %s", grantId) - err = WaitForGrantToBeRevoked(conn, keyId, grantId) - - return err + if err := WaitForGrantToBeRevoked(conn, keyId, grantId); err != nil { + return fmt.Errorf("deleting KMS Grant (%s): waiting for completion: %w", d.Id(), err) + } + return nil } func getGrantByID(grants []*kms.GrantListEntry, grantIdentifier string) *kms.GrantListEntry { @@ -390,7 +389,7 @@ func findGrantByID(conn *kms.KMS, keyId string, grantId string, marker *string) } if err != nil { - return nil, fmt.Errorf("error listing KMS Grants: %w", err) + return nil, fmt.Errorf("listing KMS Grants: %w", err) } grant = getGrantByID(out.Grants, grantId) diff --git a/internal/service/kms/key.go b/internal/service/kms/key.go index 287b2fdd0db..be5c913a98c 100644 --- a/internal/service/kms/key.go +++ b/internal/service/kms/key.go @@ -157,33 +157,33 @@ func resourceKeyCreate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("error creating KMS Key: %w", err) + return fmt.Errorf("creating KMS Key: %w", err) } d.SetId(aws.StringValue(outputRaw.(*kms.CreateKeyOutput).KeyMetadata.KeyId)) if enableKeyRotation := d.Get("enable_key_rotation").(bool); enableKeyRotation { if err := updateKeyRotationEnabled(conn, d.Id(), enableKeyRotation); err != nil { - return err + return fmt.Errorf("creating KMS Key (%s): %w", d.Id(), err) } } if enabled := d.Get("is_enabled").(bool); !enabled { if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("creating KMS Key (%s): %w", d.Id(), err) } } // Wait for propagation since KMS is eventually consistent. if v, ok := d.GetOk("policy"); ok { if err := WaitKeyPolicyPropagated(conn, d.Id(), v.(string)); err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) policy propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Key (%s) policy propagation: %w", d.Id(), err) } } if len(tags) > 0 { if err := WaitTagsPropagated(conn, d.Id(), tags); err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) tag propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Key (%s) tag propagation: %w", d.Id(), err) } } @@ -202,9 +202,8 @@ func resourceKeyRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - if err != nil { - return err + return fmt.Errorf("reading KMS Key (%s): %w", d.Id(), err) } if aws.BoolValue(key.metadata.MultiRegion) && @@ -233,11 +232,11 @@ func resourceKeyRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -249,32 +248,32 @@ func resourceKeyUpdate(d *schema.ResourceData, meta interface{}) error { if hasChange, enabled := d.HasChange("is_enabled"), d.Get("is_enabled").(bool); hasChange && enabled { // Enable before any attributes are modified. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS Key (%s): %w", d.Id(), err) } } if hasChange, enableKeyRotation := d.HasChange("enable_key_rotation"), d.Get("enable_key_rotation").(bool); hasChange { if err := updateKeyRotationEnabled(conn, d.Id(), enableKeyRotation); err != nil { - return err + return fmt.Errorf("updating KMS Key (%s): %w", d.Id(), err) } } if d.HasChange("description") { if err := updateKeyDescription(conn, d.Id(), d.Get("description").(string)); err != nil { - return err + return fmt.Errorf("updating KMS Key (%s): %w", d.Id(), err) } } if d.HasChange("policy") { if err := updateKeyPolicy(conn, d.Id(), d.Get("policy").(string), d.Get("bypass_policy_lockout_safety_check").(bool)); err != nil { - return err + return fmt.Errorf("updating KMS Key (%s): %w", d.Id(), err) } } if hasChange, enabled := d.HasChange("is_enabled"), d.Get("is_enabled").(bool); hasChange && !enabled { // Only disable after all attributes have been modified because we cannot modify disabled keys. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS Key (%s): %w", d.Id(), err) } } @@ -282,11 +281,11 @@ func resourceKeyUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating KMS Key (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating KMS Key (%s) tags: %w", d.Id(), err) } if err := WaitTagsPropagated(conn, d.Id(), tftags.New(n)); err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) tag propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Key (%s) tag propagation: %w", d.Id(), err) } } @@ -316,11 +315,11 @@ func resourceKeyDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting KMS Key (%s): %w", d.Id(), err) + return fmt.Errorf("deleting KMS Key (%s): %w", d.Id(), err) } if _, err := WaitKeyDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) to delete: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Key (%s) to delete: %w", d.Id(), err) } return nil @@ -342,13 +341,13 @@ func findKey(conn *kms.KMS, keyID string, isNewResource bool) (*kmsKey, error) { key.metadata, err = FindKeyByID(conn, keyID) if err != nil { - return nil, fmt.Errorf("error reading KMS Key (%s): %w", keyID, err) + return nil, fmt.Errorf("reading KMS Key (%s): %w", keyID, err) } policy, err := FindKeyPolicyByKeyIDAndPolicyName(conn, keyID, PolicyNameDefault) if err != nil { - return nil, fmt.Errorf("error reading KMS Key (%s) policy: %w", keyID, err) + return nil, fmt.Errorf("reading KMS Key (%s) policy: %w", keyID, err) } key.policy, err = structure.NormalizeJsonString(aws.StringValue(policy)) @@ -361,7 +360,7 @@ func findKey(conn *kms.KMS, keyID string, isNewResource bool) (*kmsKey, error) { key.rotation, err = FindKeyRotationEnabledByKeyID(conn, keyID) if err != nil { - return nil, fmt.Errorf("error reading KMS Key (%s) rotation enabled: %w", keyID, err) + return nil, fmt.Errorf("reading KMS Key (%s) rotation enabled: %w", keyID, err) } } @@ -372,7 +371,7 @@ func findKey(conn *kms.KMS, keyID string, isNewResource bool) (*kmsKey, error) { } if err != nil { - return nil, fmt.Errorf("error listing tags for KMS Key (%s): %w", keyID, err) + return nil, fmt.Errorf("listing tags for KMS Key (%s): %w", keyID, err) } return &key, nil @@ -391,33 +390,35 @@ func updateKeyDescription(conn *kms.KMS, keyID string, description string) error KeyId: aws.String(keyID), } - log.Printf("[DEBUG] Updating KMS Key description: %s", input) _, err := conn.UpdateKeyDescription(input) - if err != nil { - return fmt.Errorf("error updating KMS Key (%s) description: %w", keyID, err) + return fmt.Errorf("updating description: %w", err) } // Wait for propagation since KMS is eventually consistent. err = WaitKeyDescriptionPropagated(conn, keyID, description) - if err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) description propagation: %w", keyID, err) + return fmt.Errorf("updating description: waiting for completion: %w", err) } return nil } func updateKeyEnabled(conn *kms.KMS, keyID string, enabled bool) error { + var action string + updateFunc := func() (interface{}, error) { var err error - log.Printf("[DEBUG] Updating KMS Key (%s) key enabled: %t", keyID, enabled) if enabled { + log.Printf("[DEBUG] Enabling KMS Key (%s)", keyID) + action = "enabling" _, err = conn.EnableKey(&kms.EnableKeyInput{ KeyId: aws.String(keyID), }) } else { + log.Printf("[DEBUG] Disabling KMS Key (%s)", keyID) + action = "disabling" _, err = conn.DisableKey(&kms.DisableKeyInput{ KeyId: aws.String(keyID), }) @@ -427,16 +428,15 @@ func updateKeyEnabled(conn *kms.KMS, keyID string, enabled bool) error { } _, err := tfresource.RetryWhenAWSErrCodeEquals(PropagationTimeout, updateFunc, kms.ErrCodeNotFoundException) - if err != nil { - return fmt.Errorf("error updating KMS Key (%s) key enabled (%t): %w", keyID, enabled, err) + return fmt.Errorf("%s KMS Key: %w", action, err) } // Wait for propagation since KMS is eventually consistent. err = WaitKeyStatePropagated(conn, keyID, enabled) if err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) key state propagation: %w", keyID, err) + return fmt.Errorf("%s KMS Key: waiting for completion: %w", action, err) } return nil @@ -458,7 +458,6 @@ func updateKeyPolicy(conn *kms.KMS, keyID string, policy string, bypassPolicyLoc PolicyName: aws.String(PolicyNameDefault), } - log.Printf("[DEBUG] Updating KMS Key policy: %s", input) _, err = conn.PutKeyPolicy(input) return nil, err @@ -466,28 +465,31 @@ func updateKeyPolicy(conn *kms.KMS, keyID string, policy string, bypassPolicyLoc _, err = tfresource.RetryWhenAWSErrCodeEquals(PropagationTimeout, updateFunc, kms.ErrCodeNotFoundException, kms.ErrCodeMalformedPolicyDocumentException) if err != nil { - return fmt.Errorf("error updating KMS Key (%s) policy: %w", keyID, err) + return fmt.Errorf("updating policy: %w", err) } // Wait for propagation since KMS is eventually consistent. err = WaitKeyPolicyPropagated(conn, keyID, policy) if err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) policy propagation: %w", keyID, err) + return fmt.Errorf("updating policy: waiting for completion: %w", err) } return nil } func updateKeyRotationEnabled(conn *kms.KMS, keyID string, enabled bool) error { + var action string + updateFunc := func() (interface{}, error) { var err error - log.Printf("[DEBUG] Updating KMS Key (%s) key rotation enabled: %t", keyID, enabled) if enabled { + log.Printf("[DEBUG] Enabling KMS Key (%s) key rotation", keyID) _, err = conn.EnableKeyRotation(&kms.EnableKeyRotationInput{ KeyId: aws.String(keyID), }) } else { + log.Printf("[DEBUG] Disabling KMS Key (%s) key rotation", keyID) _, err = conn.DisableKeyRotation(&kms.DisableKeyRotationInput{ KeyId: aws.String(keyID), }) @@ -497,16 +499,15 @@ func updateKeyRotationEnabled(conn *kms.KMS, keyID string, enabled bool) error { } _, err := tfresource.RetryWhenAWSErrCodeEquals(KeyRotationUpdatedTimeout, updateFunc, kms.ErrCodeNotFoundException, kms.ErrCodeDisabledException) - if err != nil { - return fmt.Errorf("error updating KMS Key (%s) key rotation enabled (%t): %w", keyID, enabled, err) + return fmt.Errorf("%s key rotation: %w", action, err) } // Wait for propagation since KMS is eventually consistent. err = WaitKeyRotationEnabledPropagated(conn, keyID, enabled) if err != nil { - return fmt.Errorf("error waiting for KMS Key (%s) key rotation propagation: %w", keyID, err) + return fmt.Errorf("%s key rotation: waiting for completion: %w", action, err) } return nil diff --git a/internal/service/kms/replica_external_key.go b/internal/service/kms/replica_external_key.go index 925bf2fb20a..cb650a9ff3d 100644 --- a/internal/service/kms/replica_external_key.go +++ b/internal/service/kms/replica_external_key.go @@ -112,7 +112,7 @@ func resourceReplicaExternalKeyCreate(d *schema.ResourceData, meta interface{}) primaryKeyARN, err := arn.Parse(d.Get("primary_key_arn").(string)) if err != nil { - return fmt.Errorf("error parsing primary key ARN: %w", err) + return fmt.Errorf("parsing primary key ARN: %w", err) } input := &kms.ReplicateKeyInput{ @@ -140,7 +140,7 @@ func resourceReplicaExternalKeyCreate(d *schema.ResourceData, meta interface{}) session, err := conns.NewSessionForRegion(&conn.Config, primaryKeyARN.Region, meta.(*conns.AWSClient).TerraformVersion) if err != nil { - return fmt.Errorf("error creating AWS session: %w", err) + return fmt.Errorf("creating AWS session: %w", err) } replicateConn := kms.New(session) @@ -151,35 +151,35 @@ func resourceReplicaExternalKeyCreate(d *schema.ResourceData, meta interface{}) }) if err != nil { - return fmt.Errorf("error creating KMS Replica External Key: %w", err) + return fmt.Errorf("creating KMS Replica External Key: %w", err) } d.SetId(aws.StringValue(outputRaw.(*kms.ReplicateKeyOutput).ReplicaKeyMetadata.KeyId)) if _, err := WaitReplicaExternalKeyCreated(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) create: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) create: %w", d.Id(), err) } if v, ok := d.GetOk("key_material_base64"); ok { validTo := d.Get("valid_to").(string) if err := importExternalKeyMaterial(conn, d.Id(), v.(string), validTo); err != nil { - return fmt.Errorf("error importing KMS Replica External Key (%s) material: %w", d.Id(), err) + return fmt.Errorf("importing KMS Replica External Key (%s) material: %w", d.Id(), err) } if _, err := WaitKeyMaterialImported(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) material import: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) material import: %w", d.Id(), err) } if err := WaitKeyValidToPropagated(conn, d.Id(), validTo); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) valid_to propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) valid_to propagation: %w", d.Id(), err) } // The key can only be disabled if key material has been imported, else: // "KMSInvalidStateException: arn:aws:kms:us-west-2:123456789012:key/47e3edc1-945f-413b-88b1-e7341c2d89f7 is pending import." if enabled := d.Get("enabled").(bool); !enabled { if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("creating KMS Replica External Key (%s): %w", d.Id(), err) } } } @@ -187,13 +187,13 @@ func resourceReplicaExternalKeyCreate(d *schema.ResourceData, meta interface{}) // Wait for propagation since KMS is eventually consistent. if v, ok := d.GetOk("policy"); ok { if err := WaitKeyPolicyPropagated(conn, d.Id(), v.(string)); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) policy propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) policy propagation: %w", d.Id(), err) } } if len(tags) > 0 { if err := WaitTagsPropagated(conn, d.Id(), tags); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) tag propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) tag propagation: %w", d.Id(), err) } } @@ -212,9 +212,8 @@ func resourceReplicaExternalKeyRead(d *schema.ResourceData, meta interface{}) er d.SetId("") return nil } - if err != nil { - return err + return fmt.Errorf("reading KMS External Replica Key (%s): %w", d.Id(), err) } if keyManager := aws.StringValue(key.metadata.KeyManager); keyManager != kms.KeyManagerTypeCustomer { @@ -257,11 +256,11 @@ func resourceReplicaExternalKeyRead(d *schema.ResourceData, meta interface{}) er //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -273,19 +272,19 @@ func resourceReplicaExternalKeyUpdate(d *schema.ResourceData, meta interface{}) if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && enabled && state != kms.KeyStatePendingImport { // Enable before any attributes are modified. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS Replica External Key (%s): %w", d.Id(), err) } } if d.HasChange("description") { if err := updateKeyDescription(conn, d.Id(), d.Get("description").(string)); err != nil { - return err + return fmt.Errorf("updating KMS Replica External Key (%s): %w", d.Id(), err) } } if d.HasChange("policy") { if err := updateKeyPolicy(conn, d.Id(), d.Get("policy").(string), d.Get("bypass_policy_lockout_safety_check").(bool)); err != nil { - return err + return fmt.Errorf("updating KMS Replica External Key (%s): %w", d.Id(), err) } } @@ -293,22 +292,22 @@ func resourceReplicaExternalKeyUpdate(d *schema.ResourceData, meta interface{}) validTo := d.Get("valid_to").(string) if err := importExternalKeyMaterial(conn, d.Id(), d.Get("key_material_base64").(string), validTo); err != nil { - return fmt.Errorf("error importing KMS External Replica Key (%s) material: %s", d.Id(), err) + return fmt.Errorf("importing KMS External Replica Key (%s) material: %s", d.Id(), err) } if _, err := WaitKeyMaterialImported(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS External Replica Key (%s) material import: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Replica Key (%s) material import: %w", d.Id(), err) } if err := WaitKeyValidToPropagated(conn, d.Id(), validTo); err != nil { - return fmt.Errorf("error waiting for KMS External Replica Key (%s) valid_to propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS External Replica Key (%s) valid_to propagation: %w", d.Id(), err) } } if hasChange, enabled, state := d.HasChange("enabled"), d.Get("enabled").(bool), d.Get("key_state").(string); hasChange && !enabled && state != kms.KeyStatePendingImport { // Only disable after all attributes have been modified because we cannot modify disabled keys. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS Replica External Key (%s): %w", d.Id(), err) } } @@ -316,11 +315,11 @@ func resourceReplicaExternalKeyUpdate(d *schema.ResourceData, meta interface{}) o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating KMS Replica External Key (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating KMS Replica External Key (%s) tags: %w", d.Id(), err) } if err := WaitTagsPropagated(conn, d.Id(), tftags.New(n)); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) tag propagation: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) tag propagation: %w", d.Id(), err) } } @@ -350,11 +349,11 @@ func resourceReplicaExternalKeyDelete(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error deleting KMS Replica External Key (%s): %w", d.Id(), err) + return fmt.Errorf("deleting KMS Replica External Key (%s): %w", d.Id(), err) } if _, err := WaitKeyDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for KMS Replica External Key (%s) delete: %w", d.Id(), err) + return fmt.Errorf("waiting for KMS Replica External Key (%s) delete: %w", d.Id(), err) } return nil diff --git a/internal/service/kms/replica_key.go b/internal/service/kms/replica_key.go index b433ac8df7b..af65c61b490 100644 --- a/internal/service/kms/replica_key.go +++ b/internal/service/kms/replica_key.go @@ -152,7 +152,7 @@ func resourceReplicaKeyCreate(d *schema.ResourceData, meta interface{}) error { if enabled := d.Get("enabled").(bool); !enabled { if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("creating KMS Replica Key (%s): %w", d.Id(), err) } } @@ -184,22 +184,21 @@ func resourceReplicaKeyRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - if err != nil { - return err + return fmt.Errorf("reading KMS Replica Key (%s): %w", d.Id(), err) } if keyManager := aws.StringValue(key.metadata.KeyManager); keyManager != kms.KeyManagerTypeCustomer { - return fmt.Errorf("KMS Key (%s) has invalid KeyManager: %s", d.Id(), keyManager) + return fmt.Errorf("KMS Replica Key (%s) has invalid KeyManager: %s", d.Id(), keyManager) } if origin := aws.StringValue(key.metadata.Origin); origin != kms.OriginTypeAwsKms { - return fmt.Errorf("KMS Key (%s) has invalid Origin: %s", d.Id(), origin) + return fmt.Errorf("KMS Replica Key (%s) has invalid Origin: %s", d.Id(), origin) } if !aws.BoolValue(key.metadata.MultiRegion) || aws.StringValue(key.metadata.MultiRegionConfiguration.MultiRegionKeyType) != kms.MultiRegionKeyTypeReplica { - return fmt.Errorf("KMS Key (%s) is not a multi-Region replica key", d.Id()) + return fmt.Errorf("KMS Replica Key (%s) is not a multi-Region replica key", d.Id()) } d.Set("arn", key.metadata.Arn) @@ -240,26 +239,26 @@ func resourceReplicaKeyUpdate(d *schema.ResourceData, meta interface{}) error { if hasChange, enabled := d.HasChange("enabled"), d.Get("enabled").(bool); hasChange && enabled { // Enable before any attributes are modified. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS Replica Key (%s): %w", d.Id(), err) } } if d.HasChange("description") { if err := updateKeyDescription(conn, d.Id(), d.Get("description").(string)); err != nil { - return err + return fmt.Errorf("updating KMS Replica Key (%s): %w", d.Id(), err) } } if d.HasChange("policy") { if err := updateKeyPolicy(conn, d.Id(), d.Get("policy").(string), d.Get("bypass_policy_lockout_safety_check").(bool)); err != nil { - return err + return fmt.Errorf("updating KMS Replica Key (%s): %w", d.Id(), err) } } if hasChange, enabled := d.HasChange("enabled"), d.Get("enabled").(bool); hasChange && !enabled { // Only disable after all attributes have been modified because we cannot modify disabled keys. if err := updateKeyEnabled(conn, d.Id(), enabled); err != nil { - return err + return fmt.Errorf("updating KMS Replica Key (%s): %w", d.Id(), err) } } From 3a3a07f56621ac2bec5d05b8ecddad921bfeb6f5 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 16:30:59 -0800 Subject: [PATCH 006/106] Fixes bare errors in `workspaces` --- .../service/workspaces/bundle_data_source.go | 12 +++-- internal/service/workspaces/ip_group.go | 23 ++++---- internal/service/workspaces/ip_group_test.go | 6 +-- internal/service/workspaces/workspace.go | 53 ++++++++----------- .../workspaces/workspace_data_source.go | 16 +++--- 5 files changed, 50 insertions(+), 60 deletions(-) diff --git a/internal/service/workspaces/bundle_data_source.go b/internal/service/workspaces/bundle_data_source.go index 0fbb9f0e72a..68a6c2bc52a 100644 --- a/internal/service/workspaces/bundle_data_source.go +++ b/internal/service/workspaces/bundle_data_source.go @@ -83,24 +83,26 @@ func dataSourceWorkspaceBundleRead(d *schema.ResourceData, meta interface{}) err BundleIds: []*string{aws.String(bundleID.(string))}, }) if err != nil { - return err + return fmt.Errorf("reading WorkSpaces Workspace Bundle (%s): %w", bundleID, err) } if len(resp.Bundles) != 1 { - return fmt.Errorf("expected 1 result for Workspace bundle %q, found %d", bundleID, len(resp.Bundles)) + return fmt.Errorf("expected 1 result for WorkSpaces Workspace Bundle %q, found %d", bundleID, len(resp.Bundles)) } bundle = resp.Bundles[0] if bundle == nil { - return fmt.Errorf("no Workspace bundle with ID %q found", bundleID) + return fmt.Errorf("no WorkSpaces Workspace Bundle with ID %q found", bundleID) } } if name, ok := d.GetOk("name"); ok { + id := name input := &workspaces.DescribeWorkspaceBundlesInput{} if owner, ok := d.GetOk("owner"); ok { + id = fmt.Sprintf("%s:%s", owner, id) input.Owner = aws.String(owner.(string)) } @@ -116,11 +118,11 @@ func dataSourceWorkspaceBundleRead(d *schema.ResourceData, meta interface{}) err return !lastPage }) if err != nil { - return err + return fmt.Errorf("reading WorkSpaces Workspace Bundle (%s): %w", id, err) } if bundle == nil { - return fmt.Errorf("no Workspace bundle with name %q found", name) + return fmt.Errorf("no WorkSpaces Workspace Bundle with name %q found", name) } } diff --git a/internal/service/workspaces/ip_group.go b/internal/service/workspaces/ip_group.go index 571bd4ff4f6..d9c5bc3b89e 100644 --- a/internal/service/workspaces/ip_group.go +++ b/internal/service/workspaces/ip_group.go @@ -74,7 +74,7 @@ func resourceIPGroupCreate(d *schema.ResourceData, meta interface{}) error { Tags: Tags(tags.IgnoreAWS()), }) if err != nil { - return err + return fmt.Errorf("creating WorkSpaces IP Group: %w", err) } d.SetId(aws.StringValue(resp.GroupId)) @@ -92,12 +92,12 @@ func resourceIPGroupRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if len(resp.Result) == 0 { - log.Printf("[WARN] WorkSpaces Ip Group (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] WorkSpaces IP Group (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading WorkSpaces IP Group (%s): %w", d.Id(), err) } ipGroups := resp.Result @@ -116,18 +116,18 @@ func resourceIPGroupRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Id()) if err != nil { - return fmt.Errorf("error listing tags for WorkSpaces IP Group (%s): %w", d.Id(), err) + return fmt.Errorf("listing tags for WorkSpaces IP Group (%s): %w", d.Id(), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -139,20 +139,19 @@ func resourceIPGroupUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("rules") { rules := d.Get("rules").(*schema.Set).List() - log.Printf("[INFO] Updating WorkSpaces IP Group Rules") _, err := conn.UpdateRulesOfIpGroup(&workspaces.UpdateRulesOfIpGroupInput{ GroupId: aws.String(d.Id()), UserRules: expandIPGroupRules(rules), }) if err != nil { - return err + return fmt.Errorf("updating WorkSpaces IP Group (%s): %w", d.Id(), err) } } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating tags: %w", err) + return fmt.Errorf("updating tags: %w", err) } } @@ -177,7 +176,7 @@ func resourceIPGroupDelete(d *schema.ResourceData, meta interface{}) error { GroupIds: aws.StringSlice([]string{d.Id()}), }) if err != nil { - sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error disassociating WorkSpaces IP Group (%s) from WorkSpaces Directory (%s): %w", d.Id(), aws.StringValue(dir.DirectoryId), err)) + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("disassociating WorkSpaces IP Group (%s) from WorkSpaces Directory (%s): %w", d.Id(), aws.StringValue(dir.DirectoryId), err)) continue } log.Printf("[INFO] WorkSpaces IP Group (%s) disassociated from WorkSpaces Directory (%s)", d.Id(), aws.StringValue(dir.DirectoryId)) @@ -187,7 +186,7 @@ func resourceIPGroupDelete(d *schema.ResourceData, meta interface{}) error { return !lastPage }) if err != nil { - return multierror.Append(sweeperErrs, fmt.Errorf("error describing WorkSpaces Directories: %w", err)) + return multierror.Append(sweeperErrs, fmt.Errorf("describing WorkSpaces Directories: %w", err)) } if sweeperErrs.ErrorOrNil() != nil { return sweeperErrs @@ -202,7 +201,7 @@ func resourceIPGroupDelete(d *schema.ResourceData, meta interface{}) error { GroupId: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("error deleting WorkSpaces IP Group (%s): %w", d.Id(), err) + return fmt.Errorf("deleting WorkSpaces IP Group (%s): %w", d.Id(), err) } log.Printf("[INFO] WorkSpaces IP Group (%s) deleted", d.Id()) diff --git a/internal/service/workspaces/ip_group_test.go b/internal/service/workspaces/ip_group_test.go index e3d0da6eb78..61713c7d898 100644 --- a/internal/service/workspaces/ip_group_test.go +++ b/internal/service/workspaces/ip_group_test.go @@ -173,7 +173,7 @@ func testAccCheckIPGroupDestroy(s *terraform.State) error { }) if err != nil { - return fmt.Errorf("error Describing Workspaces IP Group: %w", err) + return fmt.Errorf("error Describing WorkSpaces IP Group: %w", err) } // Return nil if the IP Group is already destroyed (does not exist) @@ -182,7 +182,7 @@ func testAccCheckIPGroupDestroy(s *terraform.State) error { } if *resp.Result[0].GroupId == rs.Primary.ID { - return fmt.Errorf("Workspaces IP Group %s still exists", rs.Primary.ID) + return fmt.Errorf("WorkSpaces IP Group %s still exists", rs.Primary.ID) } } @@ -213,7 +213,7 @@ func testAccCheckIPGroupExists(n string, v *workspaces.IpGroup) resource.TestChe return nil } - return fmt.Errorf("Workspaces IP Group (%s) not found", rs.Primary.ID) + return fmt.Errorf("WorkSpaces IP Group (%s) not found", rs.Primary.ID) } } diff --git a/internal/service/workspaces/workspace.go b/internal/service/workspaces/workspace.go index bbf7b72d13f..89e1e475d57 100644 --- a/internal/service/workspaces/workspace.go +++ b/internal/service/workspaces/workspace.go @@ -157,30 +157,26 @@ func resourceWorkspaceCreate(d *schema.ResourceData, meta interface{}) error { input.WorkspaceProperties = ExpandWorkspaceProperties(d.Get("workspace_properties").([]interface{})) - log.Printf("[DEBUG] Creating workspace...\n%#v\n", *input) resp, err := conn.CreateWorkspaces(&workspaces.CreateWorkspacesInput{ Workspaces: []*workspaces.WorkspaceRequest{input}, }) if err != nil { - return err + return fmt.Errorf("creating WorkSpaces Workspace: %w", err) } wsFail := resp.FailedRequests if len(wsFail) > 0 { - return fmt.Errorf("workspace creation failed: %s: %s", aws.StringValue(wsFail[0].ErrorCode), aws.StringValue(wsFail[0].ErrorMessage)) + return fmt.Errorf("creating WorkSpaces Workspace: %s: %s", aws.StringValue(wsFail[0].ErrorCode), aws.StringValue(wsFail[0].ErrorMessage)) } workspaceID := aws.StringValue(resp.PendingRequests[0].WorkspaceId) + d.SetId(workspaceID) - log.Printf("[DEBUG] Waiting for workspace %q to be available...", workspaceID) _, err = WaitWorkspaceAvailable(conn, workspaceID, d.Timeout(schema.TimeoutCreate)) if err != nil { - return fmt.Errorf("workspace %q is not available: %s", workspaceID, err) + return fmt.Errorf("creating WorkSpaces Workspace: waiting for completion: %s", err) } - d.SetId(workspaceID) - log.Printf("[DEBUG] Workspace %q is available", workspaceID) - return resourceWorkspaceRead(d, meta) } @@ -191,10 +187,10 @@ func resourceWorkspaceRead(d *schema.ResourceData, meta interface{}) error { rawOutput, state, err := StatusWorkspaceState(conn, d.Id())() if err != nil { - return fmt.Errorf("error reading workspace (%s): %s", d.Id(), err) + return fmt.Errorf("reading WorkSpaces Workspace (%s): %s", d.Id(), err) } if state == workspaces.WorkspaceStateTerminated { - log.Printf("[WARN] workspace (%s) is not found, removing from state", d.Id()) + log.Printf("[WARN] WorkSpaces Workspace (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -210,23 +206,23 @@ func resourceWorkspaceRead(d *schema.ResourceData, meta interface{}) error { d.Set("user_volume_encryption_enabled", workspace.UserVolumeEncryptionEnabled) d.Set("volume_encryption_key", workspace.VolumeEncryptionKey) if err := d.Set("workspace_properties", FlattenWorkspaceProperties(workspace.WorkspaceProperties)); err != nil { - return fmt.Errorf("error setting workspace properties: %s", err) + return fmt.Errorf("setting workspace properties: %s", err) } tags, err := ListTags(conn, d.Id()) if err != nil { - return fmt.Errorf("error listing tags: %s", err) + return fmt.Errorf("listing tags: %s", err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -241,38 +237,38 @@ func resourceWorkspaceUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("workspace_properties.0.compute_type_name") { if err := workspacePropertyUpdate("compute_type_name", conn, d); err != nil { - return err + return fmt.Errorf("updating WorkSpaces Workspace (%s): %w", d.Id(), err) } } if d.HasChange("workspace_properties.0.root_volume_size_gib") { if err := workspacePropertyUpdate("root_volume_size_gib", conn, d); err != nil { - return err + return fmt.Errorf("updating WorkSpaces Workspace (%s): %w", d.Id(), err) } } if d.HasChange("workspace_properties.0.running_mode") { if err := workspacePropertyUpdate("running_mode", conn, d); err != nil { - return err + return fmt.Errorf("updating WorkSpaces Workspace (%s): %w", d.Id(), err) } } if d.HasChange("workspace_properties.0.running_mode_auto_stop_timeout_in_minutes") { if err := workspacePropertyUpdate("running_mode_auto_stop_timeout_in_minutes", conn, d); err != nil { - return err + return fmt.Errorf("updating WorkSpaces Workspace (%s): %w", d.Id(), err) } } if d.HasChange("workspace_properties.0.user_volume_size_gib") { if err := workspacePropertyUpdate("user_volume_size_gib", conn, d); err != nil { - return err + return fmt.Errorf("updating WorkSpaces Workspace (%s): %w", d.Id(), err) } } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("updating tags: %s", err) } } @@ -286,7 +282,6 @@ func resourceWorkspaceDelete(d *schema.ResourceData, meta interface{}) error { } func WorkspaceDelete(conn *workspaces.WorkSpaces, id string, timeout time.Duration) error { - log.Printf("[DEBUG] Terminating workspace %q", id) resp, err := conn.TerminateWorkspaces(&workspaces.TerminateWorkspacesInput{ TerminateWorkspaceRequests: []*workspaces.TerminateRequest{ { @@ -295,20 +290,18 @@ func WorkspaceDelete(conn *workspaces.WorkSpaces, id string, timeout time.Durati }, }) if err != nil { - return err + return fmt.Errorf("deleting WorkSpaces Workspace (%s): %w", id, err) } wsFail := resp.FailedRequests if len(wsFail) > 0 { - return fmt.Errorf("workspace termination failed: %s: %s", aws.StringValue(wsFail[0].ErrorCode), aws.StringValue(wsFail[0].ErrorMessage)) + return fmt.Errorf("deleting WorkSpaces Workspace (%s): %s: %s", id, aws.StringValue(wsFail[0].ErrorCode), aws.StringValue(wsFail[0].ErrorMessage)) } - log.Printf("[DEBUG] Waiting for workspace %q to be terminated", id) _, err = WaitWorkspaceTerminated(conn, id, timeout) if err != nil { - return fmt.Errorf("workspace %q was not terminated: %s", id, err) + return fmt.Errorf("deleting WorkSpaces Workspace (%s): waiting for completion: %w", id, err) } - log.Printf("[DEBUG] Workspace %q is terminated", id) return nil } @@ -316,8 +309,6 @@ func WorkspaceDelete(conn *workspaces.WorkSpaces, id string, timeout time.Durati func workspacePropertyUpdate(p string, conn *workspaces.WorkSpaces, d *schema.ResourceData) error { id := d.Id() - log.Printf("[DEBUG] Modifying workspace %q %s property...", id, p) - var wsp *workspaces.WorkspaceProperties switch p { @@ -353,15 +344,13 @@ func workspacePropertyUpdate(p string, conn *workspaces.WorkSpaces, d *schema.Re WorkspaceProperties: wsp, }) if err != nil { - return fmt.Errorf("workspace %q %s property was not modified: %w", d.Id(), p, err) + return fmt.Errorf("modifying property %q: %w", p, err) } - log.Printf("[DEBUG] Waiting for workspace %q %s property to be modified...", d.Id(), p) _, err = WaitWorkspaceUpdated(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)) if err != nil { - return fmt.Errorf("error modifying workspace %q property %q was not modified: %w", d.Id(), p, err) + return fmt.Errorf("modifying property %q: waiting for completion: %w", p, err) } - log.Printf("[DEBUG] Workspace %q %s property is modified", d.Id(), p) return nil } diff --git a/internal/service/workspaces/workspace_data_source.go b/internal/service/workspaces/workspace_data_source.go index b5cb3389f81..993880bc59d 100644 --- a/internal/service/workspaces/workspace_data_source.go +++ b/internal/service/workspaces/workspace_data_source.go @@ -107,17 +107,17 @@ func dataSourceWorkspaceRead(d *schema.ResourceData, meta interface{}) error { WorkspaceIds: aws.StringSlice([]string{workspaceID.(string)}), }) if err != nil { - return err + return fmt.Errorf("reading WorkSpaces Workspace (%s): %s", workspaceID, err) } if len(resp.Workspaces) != 1 { - return fmt.Errorf("expected 1 result for WorkSpace %q, found %d", workspaceID, len(resp.Workspaces)) + return fmt.Errorf("expected 1 result for WorkSpaces Workspace (%s), found %d", workspaceID, len(resp.Workspaces)) } workspace = resp.Workspaces[0] if workspace == nil { - return fmt.Errorf("no WorkSpace with ID %q found", workspaceID) + return fmt.Errorf("no WorkSpaces Workspace with ID %q found", workspaceID) } } @@ -128,17 +128,17 @@ func dataSourceWorkspaceRead(d *schema.ResourceData, meta interface{}) error { UserName: aws.String(userName), }) if err != nil { - return err + return fmt.Errorf("reading WorkSpaces Workspace (%s:%s): %s", directoryID, userName, err) } if len(resp.Workspaces) != 1 { - return fmt.Errorf("expected 1 result for %q WorkSpace in %q directory, found %d", userName, directoryID, len(resp.Workspaces)) + return fmt.Errorf("expected 1 result for %q Workspace in %q directory, found %d", userName, directoryID, len(resp.Workspaces)) } workspace = resp.Workspaces[0] if workspace == nil { - return fmt.Errorf("no %q WorkSpace in %q directory found", userName, directoryID) + return fmt.Errorf("no %q Workspace in %q directory found", userName, directoryID) } } @@ -158,11 +158,11 @@ func dataSourceWorkspaceRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, d.Id()) if err != nil { - return fmt.Errorf("error listing tags: %w", err) + return fmt.Errorf("listing tags: %w", err) } if err := d.Set("tags", tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } return nil From a168c5507ee1269819d9b5ed3eafb45c27defe2f Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 16:48:58 -0800 Subject: [PATCH 007/106] Fixes bare errors in `worklink` --- internal/service/worklink/fleet.go | 46 +++++++++---------- ...bsite_certificate_authority_association.go | 14 +++--- 2 files changed, 29 insertions(+), 31 deletions(-) diff --git a/internal/service/worklink/fleet.go b/internal/service/worklink/fleet.go index d60f18ec316..541ae6941b8 100644 --- a/internal/service/worklink/fleet.go +++ b/internal/service/worklink/fleet.go @@ -141,25 +141,25 @@ func resourceFleetCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateFleet(input) if err != nil { - return fmt.Errorf("Error creating WorkLink Fleet: %w", err) + return fmt.Errorf("creating WorkLink Fleet: %w", err) } d.SetId(aws.StringValue(resp.FleetArn)) if err := updateAuditStreamConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("creating WorkLink Fleet: %w", err) } if err := updateCompanyNetworkConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("creating WorkLink Fleet: %w", err) } if err := updateDevicePolicyConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("creating WorkLink Fleet: %w", err) } if err := updateIdentityProviderConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("creating WorkLink Fleet: %w", err) } return resourceFleetRead(d, meta) @@ -177,7 +177,7 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("error describing WorkLink Fleet (%s): %w", d.Id(), err) + return fmt.Errorf("describing WorkLink Fleet (%s): %w", d.Id(), err) } d.Set("arn", d.Id()) @@ -193,7 +193,7 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("error describing WorkLink Fleet (%s) audit stream configuration: %w", d.Id(), err) + return fmt.Errorf("describing WorkLink Fleet (%s) audit stream configuration: %w", d.Id(), err) } d.Set("audit_stream_arn", auditStreamConfigurationResp.AuditStreamArn) @@ -201,27 +201,27 @@ func resourceFleetRead(d *schema.ResourceData, meta interface{}) error { FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("error describing WorkLink Fleet (%s) company network configuration: %w", d.Id(), err) + return fmt.Errorf("describing WorkLink Fleet (%s) company network configuration: %w", d.Id(), err) } if err := d.Set("network", flattenNetworkConfigResponse(companyNetworkConfigurationResp)); err != nil { - return fmt.Errorf("error setting network: %w", err) + return fmt.Errorf("setting network: %w", err) } identityProviderConfigurationResp, err := conn.DescribeIdentityProviderConfiguration(&worklink.DescribeIdentityProviderConfigurationInput{ FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("error describing WorkLink Fleet (%s) identity provider configuration: %w", d.Id(), err) + return fmt.Errorf("describing WorkLink Fleet (%s) identity provider configuration: %w", d.Id(), err) } if err := d.Set("identity_provider", flattenIdentityProviderConfigResponse(identityProviderConfigurationResp)); err != nil { - return fmt.Errorf("error setting identity_provider: %w", err) + return fmt.Errorf("setting identity_provider: %w", err) } devicePolicyConfigurationResp, err := conn.DescribeDevicePolicyConfiguration(&worklink.DescribeDevicePolicyConfigurationInput{ FleetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("error describing WorkLink Fleet (%s) device policy configuration: %w", d.Id(), err) + return fmt.Errorf("describing WorkLink Fleet (%s) device policy configuration: %w", d.Id(), err) } d.Set("device_ca_certificate", strings.TrimSpace(aws.StringValue(devicePolicyConfigurationResp.DeviceCaCertificate))) @@ -243,31 +243,31 @@ func resourceFleetUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChanges("display_name", "optimize_for_end_user_location") { _, err := conn.UpdateFleetMetadata(input) if err != nil { - return fmt.Errorf("error updating WorkLink Fleet (%s): %w", d.Id(), err) + return fmt.Errorf("updating WorkLink Fleet (%s): %w", d.Id(), err) } } if d.HasChange("audit_stream_arn") { if err := updateAuditStreamConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("updating WorkLink Fleet (%s): %w", d.Id(), err) } } if d.HasChange("network") { if err := updateCompanyNetworkConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("updating WorkLink Fleet (%s): %w", d.Id(), err) } } if d.HasChange("device_ca_certificate") { if err := updateDevicePolicyConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("updating WorkLink Fleet (%s): %w", d.Id(), err) } } if d.HasChange("identity_provider") { if err := updateIdentityProviderConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("updating WorkLink Fleet (%s): %w", d.Id(), err) } } @@ -285,7 +285,7 @@ func resourceFleetDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("error deleting WorkLink Fleet resource share (%s): %w", d.Id(), err) + return fmt.Errorf("deleting WorkLink Fleet resource share (%s): %w", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -299,7 +299,7 @@ func resourceFleetDelete(d *schema.ResourceData, meta interface{}) error { _, err := stateConf.WaitForState() if err != nil { - return fmt.Errorf("error waiting for WorkLink Fleet (%s) to become deleted: %w", d.Id(), err) + return fmt.Errorf("waiting for WorkLink Fleet (%s) to become deleted: %w", d.Id(), err) } return nil @@ -333,7 +333,7 @@ func updateAuditStreamConfiguration(conn *worklink.WorkLink, d *schema.ResourceD } if _, err := conn.UpdateAuditStreamConfiguration(input); err != nil { - return fmt.Errorf("error updating WorkLink Fleet (%s) Audit Stream Configuration: %w", d.Id(), err) + return fmt.Errorf("updating Audit Stream Configuration: %w", err) } return nil @@ -355,7 +355,7 @@ func updateCompanyNetworkConfiguration(conn *worklink.WorkLink, d *schema.Resour VpcId: aws.String(config["vpc_id"].(string)), } if _, err := conn.UpdateCompanyNetworkConfiguration(input); err != nil { - return fmt.Errorf("error updating WorkLink Fleet (%s) Company Network Configuration: %w", d.Id(), err) + return fmt.Errorf("updating Company Network Configuration: %w", err) } } return nil @@ -372,7 +372,7 @@ func updateDevicePolicyConfiguration(conn *worklink.WorkLink, d *schema.Resource } if _, err := conn.UpdateDevicePolicyConfiguration(input); err != nil { - return fmt.Errorf("error updating WorkLink Fleet (%s) Device Policy Configuration: %w", d.Id(), err) + return fmt.Errorf("updating Device Policy Configuration: %w", err) } return nil } @@ -393,7 +393,7 @@ func updateIdentityProviderConfiguration(conn *worklink.WorkLink, d *schema.Reso IdentityProviderSamlMetadata: aws.String(config["saml_metadata"].(string)), } if _, err := conn.UpdateIdentityProviderConfiguration(input); err != nil { - return fmt.Errorf("error updating WorkLink Fleet (%s) Identity Provider Configuration: %w", d.Id(), err) + return fmt.Errorf("updating Identity Provider Configuration: %w", err) } } diff --git a/internal/service/worklink/website_certificate_authority_association.go b/internal/service/worklink/website_certificate_authority_association.go index dfe0d4c16ff..1ef2c75c738 100644 --- a/internal/service/worklink/website_certificate_authority_association.go +++ b/internal/service/worklink/website_certificate_authority_association.go @@ -63,7 +63,7 @@ func resourceWebsiteCertificateAuthorityAssociationCreate(d *schema.ResourceData resp, err := conn.AssociateWebsiteCertificateAuthority(input) if err != nil { - return fmt.Errorf("Error creating WorkLink Website Certificate Authority Association: %s", err) + return fmt.Errorf("creating WorkLink Website Certificate Authority Association: %s", err) } d.SetId(fmt.Sprintf("%s,%s", d.Get("fleet_arn").(string), aws.StringValue(resp.WebsiteCaId))) @@ -76,7 +76,7 @@ func resourceWebsiteCertificateAuthorityAssociationRead(d *schema.ResourceData, fleetArn, websiteCaID, err := DecodeWebsiteCertificateAuthorityAssociationResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading WorkLink Website Certificate Authority Association (%s): %s", d.Id(), err) } input := &worklink.DescribeWebsiteCertificateAuthorityInput{ @@ -91,7 +91,7 @@ func resourceWebsiteCertificateAuthorityAssociationRead(d *schema.ResourceData, d.SetId("") return nil } - return fmt.Errorf("Error describing WorkLink Website Certificate Authority Association (%s): %s", d.Id(), err) + return fmt.Errorf("reading WorkLink Website Certificate Authority Association (%s): %s", d.Id(), err) } d.Set("website_ca_id", websiteCaID) @@ -107,7 +107,7 @@ func resourceWebsiteCertificateAuthorityAssociationDelete(d *schema.ResourceData fleetArn, websiteCaID, err := DecodeWebsiteCertificateAuthorityAssociationResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting WorkLink Website Certificate Authority Association (%s): %s", d.Id(), err) } input := &worklink.DisassociateWebsiteCertificateAuthorityInput{ @@ -119,7 +119,7 @@ func resourceWebsiteCertificateAuthorityAssociationDelete(d *schema.ResourceData if tfawserr.ErrCodeEquals(err, worklink.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("Error deleting WorkLink Website Certificate Authority Association (%s): %s", d.Id(), err) + return fmt.Errorf("deleting WorkLink Website Certificate Authority Association (%s): %s", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -133,9 +133,7 @@ func resourceWebsiteCertificateAuthorityAssociationDelete(d *schema.ResourceData _, err = stateConf.WaitForState() if err != nil { - return fmt.Errorf( - "Error waiting for disassociate Worklink Website Certificate Authority (%s) to become deleted: %s", - d.Id(), err) + return fmt.Errorf("deleting WorkLink Website Certificate Authority Association (%s): waiting for completion: %s", d.Id(), err) } return nil From 43c4fe389d39834fe59430509887cae68fdffbc7 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 17:02:11 -0800 Subject: [PATCH 008/106] Fixes bare errors in `wafregional` --- internal/service/wafregional/ipset.go | 17 ++++++------ internal/service/wafregional/rule.go | 22 ++++++++-------- internal/service/wafregional/rule_group.go | 26 +++++++++---------- internal/service/wafregional/web_acl.go | 2 +- .../wafregional/web_acl_association.go | 6 +++-- internal/service/wafregional/xss_match_set.go | 11 ++++---- 6 files changed, 42 insertions(+), 42 deletions(-) diff --git a/internal/service/wafregional/ipset.go b/internal/service/wafregional/ipset.go index ff44fd46063..b2cfff1870b 100644 --- a/internal/service/wafregional/ipset.go +++ b/internal/service/wafregional/ipset.go @@ -69,7 +69,7 @@ func resourceIPSetCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateIPSet(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF Regional IPSet: %w", err) } resp := out.(*waf.CreateIPSetOutput) d.SetId(aws.StringValue(resp.IPSet.IPSetId)) @@ -86,12 +86,12 @@ func resourceIPSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetIPSet(params) if err != nil { if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, wafregional.ErrCodeWAFNonexistentItemException) { - log.Printf("[WARN] WAF IPSet (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] WAF Regional IPSet (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading WAF Regional IPSet: %w", err) } d.Set("ip_set_descriptor", flattenIPSetDescriptorWR(resp.IPSet.IPSetDescriptors)) @@ -133,7 +133,7 @@ func resourceIPSetUpdate(d *schema.ResourceData, meta interface{}) error { err := updateIPSetResourceWR(d.Id(), oldD, newD, conn, region) if err != nil { - return fmt.Errorf("Error Updating WAF IPSet: %s", err) + return fmt.Errorf("updating WAF Regional IPSet: %s", err) } } return resourceIPSetRead(d, meta) @@ -150,7 +150,7 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { err := updateIPSetResourceWR(d.Id(), oldD, noD, conn, region) if err != nil { - return fmt.Errorf("Error Deleting IPSetDescriptors: %s", err) + return fmt.Errorf("deleting IPSetDescriptors: %s", err) } } @@ -160,11 +160,11 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { ChangeToken: token, IPSetId: aws.String(d.Id()), } - log.Printf("[INFO] Deleting WAF IPSet") + log.Printf("[INFO] Deleting WAF Regional IPSet") return conn.DeleteIPSet(req) }) if err != nil { - return fmt.Errorf("Error Deleting WAF IPSet: %s", err) + return fmt.Errorf("deleting WAF Regional IPSet: %s", err) } return nil @@ -179,12 +179,11 @@ func updateIPSetResourceWR(id string, oldD, newD []interface{}, conn *wafregiona IPSetId: aws.String(id), Updates: ipSetUpdates, } - log.Printf("[INFO] Updating IPSet descriptor: %s", req) return conn.UpdateIPSet(req) }) if err != nil { - return fmt.Errorf("Error Updating WAF IPSet: %s", err) + return fmt.Errorf("updating WAF Regional IPSet: %s", err) } } diff --git a/internal/service/wafregional/rule.go b/internal/service/wafregional/rule.go index 63a45f1c67a..68a7bcd47d0 100644 --- a/internal/service/wafregional/rule.go +++ b/internal/service/wafregional/rule.go @@ -93,7 +93,7 @@ func resourceRuleCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateRule(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF Regional Rule (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateRuleOutput) d.SetId(aws.StringValue(resp.Rule.RuleId)) @@ -103,7 +103,7 @@ func resourceRuleCreate(d *schema.ResourceData, meta interface{}) error { noPredicates := []interface{}{} err := updateRuleResource(d.Id(), noPredicates, newPredicates, meta) if err != nil { - return fmt.Errorf("Error Updating WAF Regional Rule: %s", err) + return fmt.Errorf("updating WAF Regional Rule: %s", err) } } return resourceRuleRead(d, meta) @@ -126,7 +126,7 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF Regional Rule (%s): %w", d.Id(), err) } arn := arn.ARN{ @@ -141,18 +141,18 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) if err != nil { - return fmt.Errorf("error listing tags for WAF Regional Rule (%s): %s", arn, err) + return fmt.Errorf("listing tags for WAF Regional Rule (%s): %s", arn, err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } d.Set("predicate", flattenPredicates(resp.Rule.Predicates)) @@ -171,7 +171,7 @@ func resourceRuleUpdate(d *schema.ResourceData, meta interface{}) error { err := updateRuleResource(d.Id(), oldP, newP, meta) if err != nil { - return fmt.Errorf("Error Updating WAF Rule: %s", err) + return fmt.Errorf("updating WAF Rule: %s", err) } } @@ -179,7 +179,7 @@ func resourceRuleUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("updating tags: %s", err) } } @@ -195,7 +195,7 @@ func resourceRuleDelete(d *schema.ResourceData, meta interface{}) error { noPredicates := []interface{}{} err := updateRuleResource(d.Id(), oldPredicates, noPredicates, meta) if err != nil { - return fmt.Errorf("Error Removing WAF Rule Predicates: %s", err) + return fmt.Errorf("removing WAF Rule Predicates: %s", err) } } @@ -209,7 +209,7 @@ func resourceRuleDelete(d *schema.ResourceData, meta interface{}) error { return conn.DeleteRule(req) }) if err != nil { - return fmt.Errorf("Error deleting WAF Rule: %s", err) + return fmt.Errorf("deleting WAF Rule: %s", err) } return nil @@ -231,7 +231,7 @@ func updateRuleResource(id string, oldP, newP []interface{}, meta interface{}) e }) if err != nil { - return fmt.Errorf("Error Updating WAF Rule: %s", err) + return fmt.Errorf("updating WAF Rule: %s", err) } return nil diff --git a/internal/service/wafregional/rule_group.go b/internal/service/wafregional/rule_group.go index 1953260b002..48f7493126d 100644 --- a/internal/service/wafregional/rule_group.go +++ b/internal/service/wafregional/rule_group.go @@ -105,7 +105,7 @@ func resourceRuleGroupCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateRuleGroup(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF Regional Rule Group (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateRuleGroupOutput) d.SetId(aws.StringValue(resp.RuleGroup.RuleGroupId)) @@ -116,7 +116,7 @@ func resourceRuleGroupCreate(d *schema.ResourceData, meta interface{}) error { err := updateRuleGroupResourceWR(d.Id(), noActivatedRules, activatedRule, conn, region) if err != nil { - return fmt.Errorf("Error Updating WAF Regional Rule Group: %s", err) + return fmt.Errorf("updating WAF Regional Rule Group: %s", err) } } @@ -140,14 +140,14 @@ func resourceRuleGroupRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF Regional Rule Group (%s): %w", d.Id(), err) } rResp, err := conn.ListActivatedRulesInRuleGroup(&waf.ListActivatedRulesInRuleGroupInput{ RuleGroupId: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("error listing activated rules in WAF Regional Rule Group (%s): %s", d.Id(), err) + return fmt.Errorf("listing activated rules in WAF Regional Rule Group (%s): %s", d.Id(), err) } arn := arn.ARN{ @@ -161,17 +161,17 @@ func resourceRuleGroupRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) if err != nil { - return fmt.Errorf("error listing tags for WAF Regional Rule Group (%s): %s", arn, err) + return fmt.Errorf("listing tags for WAF Regional Rule Group (%s): %s", arn, err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } d.Set("activated_rule", tfwaf.FlattenActivatedRules(rResp.ActivatedRules)) @@ -191,7 +191,7 @@ func resourceRuleGroupUpdate(d *schema.ResourceData, meta interface{}) error { err := updateRuleGroupResourceWR(d.Id(), oldRules, newRules, conn, region) if err != nil { - return fmt.Errorf("Error Updating WAF Regional Rule Group: %s", err) + return fmt.Errorf("updating WAF Regional Rule Group (%s): %w", d.Id(), err) } } @@ -199,7 +199,7 @@ func resourceRuleGroupUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("updating tags: %s", err) } } @@ -213,7 +213,7 @@ func resourceRuleGroupDelete(d *schema.ResourceData, meta interface{}) error { oldRules := d.Get("activated_rule").(*schema.Set).List() err := DeleteRuleGroup(d.Id(), oldRules, conn, region) - return err + return fmt.Errorf("deleting WAF Regional Rule Group (%s): %w", d.Id(), err) } func DeleteRuleGroup(id string, oldRules []interface{}, conn *wafregional.WAFRegional, region string) error { @@ -221,7 +221,7 @@ func DeleteRuleGroup(id string, oldRules []interface{}, conn *wafregional.WAFReg noRules := []interface{}{} err := updateRuleGroupResourceWR(id, oldRules, noRules, conn, region) if err != nil { - return fmt.Errorf("Error updating WAF Regional Rule Group Predicates: %s", err) + return fmt.Errorf("updating WAF Regional Rule Group Predicates: %s", err) } } @@ -235,7 +235,7 @@ func DeleteRuleGroup(id string, oldRules []interface{}, conn *wafregional.WAFReg return conn.DeleteRuleGroup(req) }) if err != nil { - return fmt.Errorf("Error deleting WAF Regional Rule Group: %s", err) + return fmt.Errorf("deleting WAF Regional Rule Group: %s", err) } return nil } @@ -252,7 +252,7 @@ func updateRuleGroupResourceWR(id string, oldRules, newRules []interface{}, conn return conn.UpdateRuleGroup(req) }) if err != nil { - return fmt.Errorf("Error Updating WAF Regional Rule Group: %s", err) + return fmt.Errorf("updating WAF Regional Rule Group: %s", err) } return nil diff --git a/internal/service/wafregional/web_acl.go b/internal/service/wafregional/web_acl.go index 876e64ec992..39f0b74c194 100644 --- a/internal/service/wafregional/web_acl.go +++ b/internal/service/wafregional/web_acl.go @@ -191,7 +191,7 @@ func resourceWebACLCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateWebACL(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF Regional Web ACL (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateWebACLOutput) d.SetId(aws.StringValue(resp.WebACL.WebACLId)) diff --git a/internal/service/wafregional/web_acl_association.go b/internal/service/wafregional/web_acl_association.go index 3ef4c6027fb..87f953b0115 100644 --- a/internal/service/wafregional/web_acl_association.go +++ b/internal/service/wafregional/web_acl_association.go @@ -123,8 +123,10 @@ func resourceWebACLAssociationDelete(d *schema.ResourceData, meta interface{}) e } // If action successful HTTP 200 response with an empty body - _, err := conn.DisassociateWebACL(params) - return err + if _, err := conn.DisassociateWebACL(params); err != nil { + return fmt.Errorf("deleting WAF Regional Web ACL Association (%s): %w", resourceArn, err) + } + return nil } func WebACLAssociationParseID(id string) (resourceArn string) { diff --git a/internal/service/wafregional/xss_match_set.go b/internal/service/wafregional/xss_match_set.go index 0efad629299..53cef4792ce 100644 --- a/internal/service/wafregional/xss_match_set.go +++ b/internal/service/wafregional/xss_match_set.go @@ -81,7 +81,7 @@ func resourceXSSMatchSetCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateXssMatchSet(params) }) if err != nil { - return fmt.Errorf("Failed creating regional WAF XSS Match Set: %w", err) + return fmt.Errorf("creating WAF Regional XSS Match Set: %w", err) } resp := out.(*waf.CreateXssMatchSetOutput) @@ -90,7 +90,7 @@ func resourceXSSMatchSetCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.Get("xss_match_tuple").(*schema.Set); ok && v.Len() > 0 { err := updateXSSMatchSetResourceWR(d.Id(), nil, v.List(), conn, region) if err != nil { - return fmt.Errorf("Failed updating regional WAF XSS Match Set: %w", err) + return fmt.Errorf("updating WAF Regional XSS Match Set: %w", err) } } @@ -99,7 +99,6 @@ func resourceXSSMatchSetCreate(d *schema.ResourceData, meta interface{}) error { func resourceXSSMatchSetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFRegionalConn() - log.Printf("[INFO] Reading regional WAF XSS Match Set: %s", d.Get("name").(string)) params := &waf.GetXssMatchSetInput{ XssMatchSetId: aws.String(d.Id()), } @@ -112,13 +111,13 @@ func resourceXSSMatchSetRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF Regional XSS Match Set: %w", err) } set := resp.XssMatchSet if err := d.Set("xss_match_tuple", flattenXSSMatchTuples(set.XssMatchTuples)); err != nil { - return fmt.Errorf("error setting xss_match_tuple: %w", err) + return fmt.Errorf("setting xss_match_tuple: %w", err) } d.Set("name", set.Name) @@ -152,7 +151,7 @@ func resourceXSSMatchSetDelete(d *schema.ResourceData, meta interface{}) error { noTuples := []interface{}{} err := updateXSSMatchSetResourceWR(d.Id(), oldTuples, noTuples, conn, region) if err != nil { - return fmt.Errorf("Error updating regional WAF XSS Match Set: %w", err) + return fmt.Errorf("updating regional WAF XSS Match Set: %w", err) } } } From c676bb691ef063a81c6f84df0b3685bde790a98c Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 17:15:54 -0800 Subject: [PATCH 009/106] Fixes bare errors in `waf` --- internal/service/waf/byte_match_set.go | 20 +++++++++---------- internal/service/waf/geo_match_set.go | 12 +++++------ internal/service/waf/ipset.go | 14 ++++++------- internal/service/waf/rate_based_rule.go | 20 +++++++++---------- internal/service/waf/regex_match_set.go | 2 +- internal/service/waf/regex_pattern_set.go | 2 +- internal/service/waf/rule_group.go | 13 ++++++------ internal/service/waf/size_constraint_set.go | 2 +- .../service/waf/sql_injection_match_set.go | 2 +- internal/service/waf/xss_match_set.go | 2 +- 10 files changed, 45 insertions(+), 44 deletions(-) diff --git a/internal/service/waf/byte_match_set.go b/internal/service/waf/byte_match_set.go index efb95939c79..6822e60cd66 100644 --- a/internal/service/waf/byte_match_set.go +++ b/internal/service/waf/byte_match_set.go @@ -73,7 +73,7 @@ func ResourceByteMatchSet() *schema.Resource { func resourceByteMatchSetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFConn() - log.Printf("[INFO] Creating ByteMatchSet: %s", d.Get("name").(string)) + log.Printf("[INFO] Creating WAF ByteMatchSet: %s", d.Get("name").(string)) wr := NewRetryer(conn) out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { @@ -84,7 +84,7 @@ func resourceByteMatchSetCreate(d *schema.ResourceData, meta interface{}) error return conn.CreateByteMatchSet(params) }) if err != nil { - return fmt.Errorf("Error creating ByteMatchSet: %s", err) + return fmt.Errorf("creating WAF ByteMatchSet: %s", err) } resp := out.(*waf.CreateByteMatchSetOutput) @@ -95,7 +95,7 @@ func resourceByteMatchSetCreate(d *schema.ResourceData, meta interface{}) error func resourceByteMatchSetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFConn() - log.Printf("[INFO] Reading ByteMatchSet: %s", d.Get("name").(string)) + log.Printf("[INFO] Reading WAF ByteMatchSet: %s", d.Get("name").(string)) params := &waf.GetByteMatchSetInput{ ByteMatchSetId: aws.String(d.Id()), } @@ -103,12 +103,12 @@ func resourceByteMatchSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetByteMatchSet(params) if err != nil { if tfawserr.ErrCodeEquals(err, waf.ErrCodeNonexistentItemException) { - log.Printf("[WARN] WAF IPSet (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] WAF ByteMatchSet (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading WAF ByteMatchSet (%s): %s", d.Id(), err) } d.Set("name", resp.ByteMatchSet.Name) @@ -120,14 +120,14 @@ func resourceByteMatchSetRead(d *schema.ResourceData, meta interface{}) error { func resourceByteMatchSetUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFConn() - log.Printf("[INFO] Updating ByteMatchSet: %s", d.Get("name").(string)) + log.Printf("[INFO] Updating WAF ByteMatchSet: %s", d.Get("name").(string)) if d.HasChange("byte_match_tuples") { o, n := d.GetChange("byte_match_tuples") oldT, newT := o.(*schema.Set).List(), n.(*schema.Set).List() err := updateByteMatchSetResource(d.Id(), oldT, newT, conn) if err != nil { - return fmt.Errorf("Error updating ByteMatchSet: %s", err) + return fmt.Errorf("updating WAF ByteMatchSet: %s", err) } } @@ -142,7 +142,7 @@ func resourceByteMatchSetDelete(d *schema.ResourceData, meta interface{}) error noTuples := []interface{}{} err := updateByteMatchSetResource(d.Id(), oldTuples, noTuples, conn) if err != nil { - return fmt.Errorf("Error updating ByteMatchSet: %s", err) + return fmt.Errorf("updating WAF ByteMatchSet: %s", err) } } @@ -156,7 +156,7 @@ func resourceByteMatchSetDelete(d *schema.ResourceData, meta interface{}) error return conn.DeleteByteMatchSet(req) }) if err != nil { - return fmt.Errorf("Error deleting ByteMatchSet: %s", err) + return fmt.Errorf("deleting WAF ByteMatchSet: %s", err) } return nil @@ -174,7 +174,7 @@ func updateByteMatchSetResource(id string, oldT, newT []interface{}, conn *waf.W return conn.UpdateByteMatchSet(req) }) if err != nil { - return fmt.Errorf("Error updating ByteMatchSet: %s", err) + return fmt.Errorf("updating ByteMatchSet: %s", err) } return nil diff --git a/internal/service/waf/geo_match_set.go b/internal/service/waf/geo_match_set.go index ed6275e0beb..c1dc2f72af1 100644 --- a/internal/service/waf/geo_match_set.go +++ b/internal/service/waf/geo_match_set.go @@ -67,7 +67,7 @@ func resourceGeoMatchSetCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateGeoMatchSet(params) }) if err != nil { - return fmt.Errorf("Error creating GeoMatchSet: %s", err) + return fmt.Errorf("creating GeoMatchSet: %s", err) } resp := out.(*waf.CreateGeoMatchSetOutput) @@ -91,7 +91,7 @@ func resourceGeoMatchSetRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF GeoMatchSet: %s", err) } d.Set("name", resp.GeoMatchSet.Name) @@ -117,7 +117,7 @@ func resourceGeoMatchSetUpdate(d *schema.ResourceData, meta interface{}) error { err := updateGeoMatchSetResource(d.Id(), oldT, newT, conn) if err != nil { - return fmt.Errorf("Error updating GeoMatchSet: %s", err) + return fmt.Errorf("updating GeoMatchSet: %s", err) } } @@ -132,7 +132,7 @@ func resourceGeoMatchSetDelete(d *schema.ResourceData, meta interface{}) error { noConstraints := []interface{}{} err := updateGeoMatchSetResource(d.Id(), oldConstraints, noConstraints, conn) if err != nil { - return fmt.Errorf("Error updating GeoMatchConstraint: %s", err) + return fmt.Errorf("updating GeoMatchConstraint: %s", err) } } @@ -146,7 +146,7 @@ func resourceGeoMatchSetDelete(d *schema.ResourceData, meta interface{}) error { return conn.DeleteGeoMatchSet(req) }) if err != nil { - return fmt.Errorf("Error deleting GeoMatchSet: %s", err) + return fmt.Errorf("deleting GeoMatchSet: %s", err) } return nil @@ -165,7 +165,7 @@ func updateGeoMatchSetResource(id string, oldT, newT []interface{}, conn *waf.WA return conn.UpdateGeoMatchSet(req) }) if err != nil { - return fmt.Errorf("Error updating GeoMatchSet: %s", err) + return fmt.Errorf("updating GeoMatchSet: %s", err) } return nil diff --git a/internal/service/waf/ipset.go b/internal/service/waf/ipset.go index 69ae9753202..713132fcfa5 100644 --- a/internal/service/waf/ipset.go +++ b/internal/service/waf/ipset.go @@ -73,7 +73,7 @@ func resourceIPSetCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateIPSet(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF IPSet (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateIPSetOutput) d.SetId(aws.StringValue(resp.IPSet.IPSetId)) @@ -81,7 +81,7 @@ func resourceIPSetCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("ip_set_descriptors"); ok && v.(*schema.Set).Len() > 0 { err := updateIPSetDescriptors(d.Id(), nil, v.(*schema.Set).List(), conn) if err != nil { - return fmt.Errorf("Error Setting IP Descriptors: %s", err) + return fmt.Errorf("Setting IP Descriptors: %s", err) } } @@ -103,7 +103,7 @@ func resourceIPSetRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF IPSet (%s): %w", d.Get("name").(string), err) } var descriptors []map[string]interface{} @@ -140,7 +140,7 @@ func resourceIPSetUpdate(d *schema.ResourceData, meta interface{}) error { err := updateIPSetDescriptors(d.Id(), oldD, newD, conn) if err != nil { - return fmt.Errorf("Error Updating WAF IPSet: %s", err) + return fmt.Errorf("updating WAF IPSet: %s", err) } } @@ -155,7 +155,7 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { if len(oldDescriptors) > 0 { err := updateIPSetDescriptors(d.Id(), oldDescriptors, nil, conn) if err != nil { - return fmt.Errorf("Error Deleting IPSetDescriptors: %s", err) + return fmt.Errorf("deleting IPSetDescriptors: %s", err) } } @@ -169,7 +169,7 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { return conn.DeleteIPSet(req) }) if err != nil { - return fmt.Errorf("Error Deleting WAF IPSet: %s", err) + return fmt.Errorf("deleting WAF IPSet: %s", err) } return nil @@ -188,7 +188,7 @@ func updateIPSetDescriptors(id string, oldD, newD []interface{}, conn *waf.WAF) return conn.UpdateIPSet(req) }) if err != nil { - return fmt.Errorf("Error Updating WAF IPSet: %s", err) + return fmt.Errorf("updating WAF IPSet: %s", err) } } diff --git a/internal/service/waf/rate_based_rule.go b/internal/service/waf/rate_based_rule.go index 3ed6fe85e7f..31916d3b14b 100644 --- a/internal/service/waf/rate_based_rule.go +++ b/internal/service/waf/rate_based_rule.go @@ -102,7 +102,7 @@ func resourceRateBasedRuleCreate(d *schema.ResourceData, meta interface{}) error return conn.CreateRateBasedRule(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF Rate Based Rule (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateRateBasedRuleOutput) d.SetId(aws.StringValue(resp.Rule.RuleId)) @@ -112,7 +112,7 @@ func resourceRateBasedRuleCreate(d *schema.ResourceData, meta interface{}) error noPredicates := []interface{}{} err := updateRateBasedRuleResource(*resp.Rule.RuleId, noPredicates, newPredicates, d.Get("rate_limit"), conn) if err != nil { - return fmt.Errorf("Error Updating WAF Rate Based Rule: %s", err) + return fmt.Errorf("updating WAF Rate Based Rule: %s", err) } } @@ -136,7 +136,7 @@ func resourceRateBasedRuleRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF Rate Based Rule (%s): %w", d.Get("name").(string), err) } var predicates []map[string]interface{} @@ -167,11 +167,11 @@ func resourceRateBasedRuleRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } d.Set("predicates", predicates) @@ -193,7 +193,7 @@ func resourceRateBasedRuleUpdate(d *schema.ResourceData, meta interface{}) error err := updateRateBasedRuleResource(d.Id(), oldP, newP, rateLimit, conn) if err != nil { - return fmt.Errorf("Error Updating WAF Rule: %s", err) + return fmt.Errorf("updating WAF Rule: %s", err) } } @@ -201,7 +201,7 @@ func resourceRateBasedRuleUpdate(d *schema.ResourceData, meta interface{}) error o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("updating tags: %s", err) } } @@ -218,7 +218,7 @@ func resourceRateBasedRuleDelete(d *schema.ResourceData, meta interface{}) error err := updateRateBasedRuleResource(d.Id(), oldPredicates, noPredicates, rateLimit, conn) if err != nil { - return fmt.Errorf("Error updating WAF Rate Based Rule Predicates: %s", err) + return fmt.Errorf("updating WAF Rate Based Rule Predicates: %s", err) } } @@ -232,7 +232,7 @@ func resourceRateBasedRuleDelete(d *schema.ResourceData, meta interface{}) error return conn.DeleteRateBasedRule(req) }) if err != nil { - return fmt.Errorf("Error deleting WAF Rate Based Rule: %s", err) + return fmt.Errorf("deleting WAF Rate Based Rule: %s", err) } return nil @@ -251,7 +251,7 @@ func updateRateBasedRuleResource(id string, oldP, newP []interface{}, rateLimit return conn.UpdateRateBasedRule(req) }) if err != nil { - return fmt.Errorf("Error Updating WAF Rate Based Rule: %s", err) + return fmt.Errorf("updating WAF Rate Based Rule: %s", err) } return nil diff --git a/internal/service/waf/regex_match_set.go b/internal/service/waf/regex_match_set.go index c87d695d30d..5b99ee50a0a 100644 --- a/internal/service/waf/regex_match_set.go +++ b/internal/service/waf/regex_match_set.go @@ -112,7 +112,7 @@ func resourceRegexMatchSetRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF Regex Match Set (%s): %w", d.Get("name").(string), err) } d.Set("name", resp.RegexMatchSet.Name) diff --git a/internal/service/waf/regex_pattern_set.go b/internal/service/waf/regex_pattern_set.go index 6e248278c0c..0e1c844ded2 100644 --- a/internal/service/waf/regex_pattern_set.go +++ b/internal/service/waf/regex_pattern_set.go @@ -79,7 +79,7 @@ func resourceRegexPatternSetRead(d *schema.ResourceData, meta interface{}) error return nil } - return err + return fmt.Errorf("reading WAF Regex Pattern Set (%s): %w", d.Get("name").(string), err) } d.Set("name", resp.RegexPatternSet.Name) diff --git a/internal/service/waf/rule_group.go b/internal/service/waf/rule_group.go index 00feae048e2..dda9546c6f1 100644 --- a/internal/service/waf/rule_group.go +++ b/internal/service/waf/rule_group.go @@ -102,7 +102,7 @@ func resourceRuleGroupCreate(d *schema.ResourceData, meta interface{}) error { return conn.CreateRuleGroup(params) }) if err != nil { - return err + return fmt.Errorf("creating WAF Rule Group (%s): %w", d.Get("name").(string), err) } resp := out.(*waf.CreateRuleGroupOutput) d.SetId(aws.StringValue(resp.RuleGroup.RuleGroupId)) @@ -113,7 +113,7 @@ func resourceRuleGroupCreate(d *schema.ResourceData, meta interface{}) error { err := updateRuleGroupResource(d.Id(), noActivatedRules, activatedRules, conn) if err != nil { - return fmt.Errorf("Error Updating WAF Rule Group: %s", err) + return fmt.Errorf("updating WAF Rule Group: %s", err) } } @@ -137,7 +137,7 @@ func resourceRuleGroupRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF Rule Group (%s): %w", d.Id(), err) } rResp, err := conn.ListActivatedRulesInRuleGroup(&waf.ListActivatedRulesInRuleGroupInput{ @@ -206,9 +206,10 @@ func resourceRuleGroupDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).WAFConn() oldRules := d.Get("activated_rule").(*schema.Set).List() - err := deleteRuleGroup(d.Id(), oldRules, conn) - - return err + if err := deleteRuleGroup(d.Id(), oldRules, conn); err != nil { + return fmt.Errorf("deleting WAF Rule Group (%s): %w", d.Id(), err) + } + return nil } func deleteRuleGroup(id string, oldRules []interface{}, conn *waf.WAF) error { diff --git a/internal/service/waf/size_constraint_set.go b/internal/service/waf/size_constraint_set.go index d60a46b1d62..991122afc38 100644 --- a/internal/service/waf/size_constraint_set.go +++ b/internal/service/waf/size_constraint_set.go @@ -65,7 +65,7 @@ func resourceSizeConstraintSetRead(d *schema.ResourceData, meta interface{}) err return nil } - return err + return fmt.Errorf("reading WAF Size Constraint Set (%s): %w", d.Get("name").(string), err) } d.Set("name", resp.SizeConstraintSet.Name) diff --git a/internal/service/waf/sql_injection_match_set.go b/internal/service/waf/sql_injection_match_set.go index afb394baee8..276e904ced6 100644 --- a/internal/service/waf/sql_injection_match_set.go +++ b/internal/service/waf/sql_injection_match_set.go @@ -98,7 +98,7 @@ func resourceSQLInjectionMatchSetRead(d *schema.ResourceData, meta interface{}) return nil } - return err + return fmt.Errorf("reading WAF SQL Injection Match Set (%s): %w", d.Get("name").(string), err) } d.Set("name", resp.SqlInjectionMatchSet.Name) diff --git a/internal/service/waf/xss_match_set.go b/internal/service/waf/xss_match_set.go index df72c55d093..da0c06fbfa6 100644 --- a/internal/service/waf/xss_match_set.go +++ b/internal/service/waf/xss_match_set.go @@ -113,7 +113,7 @@ func resourceXSSMatchSetRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading WAF XSS Match Set (%s): %w", d.Get("name").(string), err) } d.Set("name", resp.XssMatchSet.Name) From a8cc16e6dc833ef1c3e50f616135f7fcfd776359 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 17:23:49 -0800 Subject: [PATCH 010/106] Fixes bare errors in `transfer` --- internal/service/transfer/access.go | 2 +- internal/service/transfer/server.go | 37 ++++++++++++++-------------- internal/service/transfer/ssh_key.go | 10 +++----- internal/service/transfer/user.go | 2 +- 4 files changed, 23 insertions(+), 28 deletions(-) diff --git a/internal/service/transfer/access.go b/internal/service/transfer/access.go index 00ae8142e31..ec7423f8da2 100644 --- a/internal/service/transfer/access.go +++ b/internal/service/transfer/access.go @@ -207,7 +207,7 @@ func resourceAccessRead(d *schema.ResourceData, meta interface{}) error { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(access.Policy)) if err != nil { - return err + return fmt.Errorf("error reading Transfer Access (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) diff --git a/internal/service/transfer/server.go b/internal/service/transfer/server.go index 7f749c1a6fe..694da5a741d 100644 --- a/internal/service/transfer/server.go +++ b/internal/service/transfer/server.go @@ -321,7 +321,7 @@ func resourceServerCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateServer(input) if err != nil { - return fmt.Errorf("error creating Transfer Server: %w", err) + return fmt.Errorf("creating Transfer Server: %w", err) } d.SetId(aws.StringValue(output.ServerId)) @@ -329,13 +329,13 @@ func resourceServerCreate(d *schema.ResourceData, meta interface{}) error { _, err = waitServerCreated(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return fmt.Errorf("error waiting for Transfer Server (%s) to create: %w", d.Id(), err) + return fmt.Errorf("creating Transfer Server (%s): waiting for completion: %w", d.Id(), err) } // AddressAllocationIds is only valid in the UpdateServer API. if len(addressAllocationIDs) > 0 { if err := stopServer(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("creating Transfer Server (%s): setting address allocations: %w", d.Id(), err) } input := &transfer.UpdateServerInput{ @@ -346,11 +346,11 @@ func resourceServerCreate(d *schema.ResourceData, meta interface{}) error { } if err := updateServer(conn, input); err != nil { - return err + return fmt.Errorf("creating Transfer Server (%s): setting address allocations: %w", d.Id(), err) } if err := startServer(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("creating Transfer Server (%s): setting address allocations: %w", d.Id(), err) } } @@ -613,7 +613,7 @@ func resourceServerUpdate(d *schema.ResourceData, meta interface{}) error { if offlineUpdate { if err := stopServer(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating Transfer Server (%s): %w", d.Id(), err) } } @@ -627,13 +627,13 @@ func resourceServerUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Removing Transfer Server Address Allocation IDs: %s", input) if err := updateServer(conn, input); err != nil { - return err + return fmt.Errorf("updating Transfer Server (%s): removing address allocations: %w", d.Id(), err) } } log.Printf("[DEBUG] Updating Transfer Server: %s", input) if err := updateServer(conn, input); err != nil { - return err + return fmt.Errorf("updating Transfer Server (%s): %w", d.Id(), err) } if len(addressAllocationIDs) > 0 { @@ -646,13 +646,13 @@ func resourceServerUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Adding Transfer Server Address Allocation IDs: %s", input) if err := updateServer(conn, input); err != nil { - return err + return fmt.Errorf("updating Transfer Server (%s): adding address allocations: %w", d.Id(), err) } } if offlineUpdate { if err := startServer(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating Transfer Server (%s): %w", d.Id(), err) } } } @@ -685,7 +685,6 @@ func resourceServerDelete(d *schema.ResourceData, meta interface{}) error { err := userDelete(conn, d.Id(), aws.StringValue(user.UserName)) if err != nil { - log.Printf("[ERROR] %s", err) deletionErrs = multierror.Append(deletionErrs, err) continue @@ -696,13 +695,13 @@ func resourceServerDelete(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - deletionErrs = multierror.Append(deletionErrs, fmt.Errorf("error listing Transfer Users: %w", err)) + deletionErrs = multierror.Append(deletionErrs, fmt.Errorf("listing Transfer Users: %w", err)) } err = deletionErrs.ErrorOrNil() if err != nil { - return err + return fmt.Errorf("deleting Transfer Server (%s): %w", d.Id(), err) } } @@ -720,13 +719,13 @@ func resourceServerDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting Transfer Server (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Transfer Server (%s): %w", d.Id(), err) } _, err = waitServerDeleted(conn, d.Id()) if err != nil { - return fmt.Errorf("error waiting for Transfer Server (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting Transfer Server (%s): waiting for completion: %w", d.Id(), err) } return nil @@ -883,11 +882,11 @@ func stopServer(conn *transfer.Transfer, serverID string, timeout time.Duration) } if _, err := conn.StopServer(input); err != nil { - return fmt.Errorf("error stopping Transfer Server (%s): %w", serverID, err) + return fmt.Errorf("stopping Transfer Server: %w", err) } if _, err := waitServerStopped(conn, serverID, timeout); err != nil { - return fmt.Errorf("error waiting for Transfer Server (%s) to stop: %w", serverID, err) + return fmt.Errorf("stopping Transfer Server: waiting for completion: %w", err) } return nil @@ -899,11 +898,11 @@ func startServer(conn *transfer.Transfer, serverID string, timeout time.Duration } if _, err := conn.StartServer(input); err != nil { - return fmt.Errorf("error starting Transfer Server (%s): %w", serverID, err) + return fmt.Errorf("starting Transfer Server: %w", err) } if _, err := waitServerStarted(conn, serverID, timeout); err != nil { - return fmt.Errorf("error waiting for Transfer Server (%s) to start: %w", serverID, err) + return fmt.Errorf("starting Transfer Server: waiting for completion: %w", err) } return nil diff --git a/internal/service/transfer/ssh_key.go b/internal/service/transfer/ssh_key.go index e7394fa5ce5..c9d7c01f5f0 100644 --- a/internal/service/transfer/ssh_key.go +++ b/internal/service/transfer/ssh_key.go @@ -67,7 +67,7 @@ func resourceSSHKeyCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error importing ssh public key: %s", err) } - d.SetId(fmt.Sprintf("%s/%s/%s", serverID, userName, *resp.SshPublicKeyId)) + d.SetId(fmt.Sprintf("%s/%s/%s", serverID, userName, aws.StringValue(resp.SshPublicKeyId))) return nil } @@ -84,8 +84,6 @@ func resourceSSHKeyRead(d *schema.ResourceData, meta interface{}) error { ServerId: aws.String(serverID), } - log.Printf("[DEBUG] Describe Transfer User Option: %#v", descOpts) - resp, err := conn.DescribeUser(descOpts) if err != nil { if tfawserr.ErrCodeEquals(err, transfer.ErrCodeResourceNotFoundException) { @@ -93,7 +91,7 @@ func resourceSSHKeyRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading Transfer SSH Key (%s): %w", d.Id(), err) } var body string @@ -128,14 +126,12 @@ func resourceSSHKeyDelete(d *schema.ResourceData, meta interface{}) error { SshPublicKeyId: aws.String(sshKeyID), } - log.Printf("[DEBUG] Delete Transfer SSH Public Key Option: %#v", delOpts) - _, err = conn.DeleteSshPublicKey(delOpts) if err != nil { if tfawserr.ErrCodeEquals(err, transfer.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("error deleting Transfer User Ssh Key (%s): %s", d.Id(), err) + return fmt.Errorf("error deleting Transfer User SSH Key (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/transfer/user.go b/internal/service/transfer/user.go index 62f466b0b18..a4ba089a30b 100644 --- a/internal/service/transfer/user.go +++ b/internal/service/transfer/user.go @@ -216,7 +216,7 @@ func resourceUserRead(d *schema.ResourceData, meta interface{}) error { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(user.Policy)) if err != nil { - return err + return fmt.Errorf("reading Transfer User (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) From deef1c0b57a4e8c129f1f63c405a5b25274d0d1c Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 17:36:32 -0800 Subject: [PATCH 011/106] Fixes bare errors in `synthetics` --- internal/service/synthetics/canary.go | 40 +++++++++++++-------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/internal/service/synthetics/canary.go b/internal/service/synthetics/canary.go index 40495d2431b..b5504ccef58 100644 --- a/internal/service/synthetics/canary.go +++ b/internal/service/synthetics/canary.go @@ -275,7 +275,7 @@ func resourceCanaryCreate(d *schema.ResourceData, meta interface{}) error { } if code, err := expandCanaryCode(d); err != nil { - return err + return fmt.Errorf("creating Synthetics Canary (%s): %w", name, err) } else { input.Code = code } @@ -308,11 +308,10 @@ func resourceCanaryCreate(d *schema.ResourceData, meta interface{}) error { input.Tags = Tags(tags.IgnoreAWS()) } - log.Printf("[DEBUG] Creating Synthetics Canary: %s", input) output, err := conn.CreateCanary(input) if err != nil { - return fmt.Errorf("error creating Synthetics Canary (%s): %w", name, err) + return fmt.Errorf("creating Synthetics Canary (%s): %w", name, err) } d.SetId(aws.StringValue(output.Canary.Name)) @@ -342,12 +341,12 @@ func resourceCanaryCreate(d *schema.ResourceData, meta interface{}) error { ) if err != nil { - return fmt.Errorf("error waiting for Synthetics Canary (%s) create: %w", d.Id(), err) + return fmt.Errorf("creating Synthetics Canary (%s): waiting for completion: %w", name, err) } if d.Get("start_canary").(bool) { if err := startCanary(d.Id(), conn); err != nil { - return err + return fmt.Errorf("creating Synthetics Canary (%s): %w", name, err) } } @@ -451,7 +450,7 @@ func resourceCanaryUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChanges("handler", "zip_file", "s3_bucket", "s3_key", "s3_version") { if code, err := expandCanaryCode(d); err != nil { - return err + return fmt.Errorf("updating Synthetics Canary (%s): %w", d.Id(), err) } else { input.Code = code } @@ -487,30 +486,29 @@ func resourceCanaryUpdate(d *schema.ResourceData, meta interface{}) error { status := d.Get("status").(string) if status == synthetics.CanaryStateRunning { if err := stopCanary(d.Id(), conn); err != nil { - return err + return fmt.Errorf("updating Synthetics Canary (%s): %w", d.Id(), err) } } - log.Printf("[DEBUG] Updating Synthetics Canary: %s", input) _, err := conn.UpdateCanary(input) if err != nil { - return fmt.Errorf("error updating Synthetics Canary (%s): %w", d.Id(), err) + return fmt.Errorf("updating Synthetics Canary (%s): %w", d.Id(), err) } if status != synthetics.CanaryStateReady { if _, err := waitCanaryStopped(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for Synthetics Canary (%s) stop: %w", d.Id(), err) + return fmt.Errorf("updating Synthetics Canary (%s): waiting for Canary to stop: %w", d.Id(), err) } } else { if _, err := waitCanaryReady(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for Synthetics Canary (%s) ready: %w", d.Id(), err) + return fmt.Errorf("updating Synthetics Canary (%s): waiting for Canary to be ready: %w", d.Id(), err) } } if d.Get("start_canary").(bool) { if err := startCanary(d.Id(), conn); err != nil { - return err + return fmt.Errorf("updating Synthetics Canary (%s): %w", d.Id(), err) } } } @@ -520,13 +518,13 @@ func resourceCanaryUpdate(d *schema.ResourceData, meta interface{}) error { if d.Get("start_canary").(bool) { if status != synthetics.CanaryStateRunning { if err := startCanary(d.Id(), conn); err != nil { - return err + return fmt.Errorf("updating Synthetics Canary (%s): %w", d.Id(), err) } } } else { if status == synthetics.CanaryStateRunning { if err := stopCanary(d.Id(), conn); err != nil { - return err + return fmt.Errorf("updating Synthetics Canary (%s): %w", d.Id(), err) } } } @@ -548,7 +546,7 @@ func resourceCanaryDelete(d *schema.ResourceData, meta interface{}) error { if status := d.Get("status").(string); status == synthetics.CanaryStateRunning { if err := stopCanary(d.Id(), conn); err != nil { - return err + return fmt.Errorf("deleting Synthetics Canary (%s): %w", d.Id(), err) } } @@ -563,13 +561,13 @@ func resourceCanaryDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting Synthetics Canary (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Synthetics Canary (%s): %w", d.Id(), err) } _, err = waitCanaryDeleted(conn, d.Id()) if err != nil { - return fmt.Errorf("error waiting for Synthetics Canary (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting Synthetics Canary (%s): waiting for completion: %w", d.Id(), err) } return nil @@ -803,13 +801,13 @@ func startCanary(name string, conn *synthetics.Synthetics) error { }) if err != nil { - return fmt.Errorf("error starting Synthetics Canary (%s): %w", name, err) + return fmt.Errorf("starting Synthetics Canary: %w", err) } _, err = waitCanaryRunning(conn, name) if err != nil { - return fmt.Errorf("error waiting for Synthetics Canary (%s) start: %w", name, err) + return fmt.Errorf("starting Synthetics Canary: waiting for completion: %w", err) } return nil @@ -826,13 +824,13 @@ func stopCanary(name string, conn *synthetics.Synthetics) error { } if err != nil { - return fmt.Errorf("error stopping Synthetics Canary (%s): %w", name, err) + return fmt.Errorf("stopping Synthetics Canary: %w", err) } _, err = waitCanaryStopped(conn, name) if err != nil { - return fmt.Errorf("error waiting for Synthetics Canary (%s) stop: %w", name, err) + return fmt.Errorf("stopping Synthetics Canary: waiting for completion: %w", err) } return nil From 8bac032c4ddd184c81cddedf2c20c73cdba236da Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 17:49:51 -0800 Subject: [PATCH 012/106] Fixes bare errors in `storagegateway` --- internal/service/storagegateway/cache.go | 14 ++++++-------- internal/service/storagegateway/nfs_file_share.go | 4 ++-- internal/service/storagegateway/upload_buffer.go | 2 +- .../service/storagegateway/working_storage.go | 15 +++++++-------- 4 files changed, 16 insertions(+), 19 deletions(-) diff --git a/internal/service/storagegateway/cache.go b/internal/service/storagegateway/cache.go index 834cff29dca..fb00dd3a8f6 100644 --- a/internal/service/storagegateway/cache.go +++ b/internal/service/storagegateway/cache.go @@ -49,10 +49,9 @@ func resourceCacheCreate(d *schema.ResourceData, meta interface{}) error { GatewayARN: aws.String(gatewayARN), } - log.Printf("[DEBUG] Adding Storage Gateway cache: %s", input) _, err := conn.AddCache(input) if err != nil { - return fmt.Errorf("error adding Storage Gateway cache: %s", err) + return fmt.Errorf("creating Storage Gateway Cache: %s", err) } d.SetId(fmt.Sprintf("%s:%s", gatewayARN, diskID)) @@ -93,26 +92,25 @@ func resourceCacheRead(d *schema.ResourceData, meta interface{}) error { gatewayARN, diskID, err := DecodeCacheID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Storage Gateway Cache (%s): %s", d.Id(), err) } input := &storagegateway.DescribeCacheInput{ GatewayARN: aws.String(gatewayARN), } - log.Printf("[DEBUG] Reading Storage Gateway cache: %s", input) output, err := conn.DescribeCache(input) if err != nil { if IsErrGatewayNotFound(err) { - log.Printf("[WARN] Storage Gateway cache %q not found - removing from state", d.Id()) + log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("error reading Storage Gateway cache: %s", err) + return fmt.Errorf("reading Storage Gateway Cache (%s): %s", d.Id(), err) } if output == nil || len(output.DiskIds) == 0 { - log.Printf("[WARN] Storage Gateway cache %q not found - removing from state", d.Id()) + log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -126,7 +124,7 @@ func resourceCacheRead(d *schema.ResourceData, meta interface{}) error { } if !found { - log.Printf("[WARN] Storage Gateway cache %q not found - removing from state", d.Id()) + log.Printf("[WARN] Storage Gateway Cache (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/storagegateway/nfs_file_share.go b/internal/service/storagegateway/nfs_file_share.go index 7aa0e5cf471..eedef995bc5 100644 --- a/internal/service/storagegateway/nfs_file_share.go +++ b/internal/service/storagegateway/nfs_file_share.go @@ -217,7 +217,7 @@ func resourceNFSFileShareCreate(d *schema.ResourceData, meta interface{}) error fileShareDefaults, err := expandNFSFileShareDefaults(d.Get("nfs_file_share_defaults").([]interface{})) if err != nil { - return err + return fmt.Errorf("creating Storage Gateway NFS File Share: %w", err) } input := &storagegateway.CreateNFSFileShareInput{ @@ -348,7 +348,7 @@ func resourceNFSFileShareUpdate(d *schema.ResourceData, meta interface{}) error fileShareDefaults, err := expandNFSFileShareDefaults(d.Get("nfs_file_share_defaults").([]interface{})) if err != nil { - return err + return fmt.Errorf("updating Storage Gateway NFS File Share (%s): %w", d.Id(), err) } input := &storagegateway.UpdateNFSFileShareInput{ diff --git a/internal/service/storagegateway/upload_buffer.go b/internal/service/storagegateway/upload_buffer.go index ae242fe1e1c..ed5136d0469 100644 --- a/internal/service/storagegateway/upload_buffer.go +++ b/internal/service/storagegateway/upload_buffer.go @@ -101,7 +101,7 @@ func resourceUploadBufferRead(d *schema.ResourceData, meta interface{}) error { gatewayARN, diskID, err := DecodeUploadBufferID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Storage Gateway Upload Buffer (%s): %w", d.Id(), err) } foundDiskID, err := FindUploadBufferDisk(conn, gatewayARN, diskID) diff --git a/internal/service/storagegateway/working_storage.go b/internal/service/storagegateway/working_storage.go index ebc1b91a903..4b337572248 100644 --- a/internal/service/storagegateway/working_storage.go +++ b/internal/service/storagegateway/working_storage.go @@ -49,10 +49,10 @@ func resourceWorkingStorageCreate(d *schema.ResourceData, meta interface{}) erro GatewayARN: aws.String(gatewayARN), } - log.Printf("[DEBUG] Adding Storage Gateway working storage: %s", input) + log.Printf("[DEBUG] Adding Storage Gateway Working Storage: %s", input) _, err := conn.AddWorkingStorage(input) if err != nil { - return fmt.Errorf("error adding Storage Gateway working storage: %s", err) + return fmt.Errorf("error adding Storage Gateway Working Storage: %s", err) } d.SetId(fmt.Sprintf("%s:%s", gatewayARN, diskID)) @@ -65,26 +65,25 @@ func resourceWorkingStorageRead(d *schema.ResourceData, meta interface{}) error gatewayARN, diskID, err := DecodeWorkingStorageID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Storage Gateway Working Storage (%s): %s", d.Id(), err) } input := &storagegateway.DescribeWorkingStorageInput{ GatewayARN: aws.String(gatewayARN), } - log.Printf("[DEBUG] Reading Storage Gateway working storage: %s", input) output, err := conn.DescribeWorkingStorage(input) if err != nil { if IsErrGatewayNotFound(err) { - log.Printf("[WARN] Storage Gateway working storage %q not found - removing from state", d.Id()) + log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("error reading Storage Gateway working storage: %s", err) + return fmt.Errorf("reading Storage Gateway Working Storage (%s): %s", d.Id(), err) } if output == nil || len(output.DiskIds) == 0 { - log.Printf("[WARN] Storage Gateway working storage %q not found - removing from state", d.Id()) + log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -98,7 +97,7 @@ func resourceWorkingStorageRead(d *schema.ResourceData, meta interface{}) error } if !found { - log.Printf("[WARN] Storage Gateway working storage %q not found - removing from state", d.Id()) + log.Printf("[WARN] Storage Gateway Working Storage (%s) not found, removing from state", d.Id()) d.SetId("") return nil } From 111a821565f3a0f8acd7dae1bad2f9c8306f541a Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 17:57:37 -0800 Subject: [PATCH 013/106] Fixes bare errors in `ssoadmin` --- .../ssoadmin/customer_managed_policy_attachment.go | 8 ++++---- internal/service/ssoadmin/managed_policy_attachment.go | 6 +++--- internal/service/ssoadmin/permission_set.go | 2 +- internal/service/ssoadmin/permission_set_inline_policy.go | 4 ++-- .../service/ssoadmin/permissions_boundary_attachment.go | 8 ++++---- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/internal/service/ssoadmin/customer_managed_policy_attachment.go b/internal/service/ssoadmin/customer_managed_policy_attachment.go index b1a6cd0b20d..dce2a15e94f 100644 --- a/internal/service/ssoadmin/customer_managed_policy_attachment.go +++ b/internal/service/ssoadmin/customer_managed_policy_attachment.go @@ -98,7 +98,7 @@ func resourceCustomerManagedPolicyAttachmentCreate(d *schema.ResourceData, meta // After the policy has been attached to the permission set, provision in all accounts that use this permission set. if err := provisionPermissionSet(conn, permissionSetARN, instanceARN); err != nil { - return err + return fmt.Errorf("creating SSO Customer Managed Policy Attachment (%s): %w", d.Id(), err) } return resourceCustomerManagedPolicyAttachmentRead(d, meta) @@ -110,7 +110,7 @@ func resourceCustomerManagedPolicyAttachmentRead(d *schema.ResourceData, meta in policyName, policyPath, permissionSetARN, instanceARN, err := CustomerManagedPolicyAttachmentParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SSO Customer Managed Policy Attachment (%s): %w", d.Id(), err) } policy, err := FindCustomerManagedPolicy(conn, policyName, policyPath, permissionSetARN, instanceARN) @@ -140,7 +140,7 @@ func resourceCustomerManagedPolicyAttachmentDelete(d *schema.ResourceData, meta policyName, policyPath, permissionSetARN, instanceARN, err := CustomerManagedPolicyAttachmentParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting SSO Customer Managed Policy Attachment (%s): %w", d.Id(), err) } input := &ssoadmin.DetachCustomerManagedPolicyReferenceFromPermissionSetInput{ @@ -167,7 +167,7 @@ func resourceCustomerManagedPolicyAttachmentDelete(d *schema.ResourceData, meta // After the policy has been detached from the permission set, provision in all accounts that use this permission set. if err := provisionPermissionSet(conn, permissionSetARN, instanceARN); err != nil { - return err + return fmt.Errorf("deleting SSO Customer Managed Policy Attachment (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ssoadmin/managed_policy_attachment.go b/internal/service/ssoadmin/managed_policy_attachment.go index 49c75612fc8..ea3694bd4b0 100644 --- a/internal/service/ssoadmin/managed_policy_attachment.go +++ b/internal/service/ssoadmin/managed_policy_attachment.go @@ -67,14 +67,14 @@ func resourceManagedPolicyAttachmentCreate(d *schema.ResourceData, meta interfac _, err := conn.AttachManagedPolicyToPermissionSet(input) if err != nil { - return fmt.Errorf("error attaching Managed Policy to SSO Permission Set (%s): %w", permissionSetArn, err) + return fmt.Errorf("attaching Managed Policy to SSO Permission Set (%s): %w", permissionSetArn, err) } d.SetId(fmt.Sprintf("%s,%s,%s", managedPolicyArn, permissionSetArn, instanceArn)) // Provision ALL accounts after attaching the managed policy if err := provisionPermissionSet(conn, permissionSetArn, instanceArn); err != nil { - return err + return fmt.Errorf("provisioning SSO Permission Set (%s): %w", permissionSetArn, err) } return resourceManagedPolicyAttachmentRead(d, meta) @@ -139,7 +139,7 @@ func resourceManagedPolicyAttachmentDelete(d *schema.ResourceData, meta interfac // Provision ALL accounts after detaching the managed policy if err := provisionPermissionSet(conn, permissionSetArn, instanceArn); err != nil { - return err + return fmt.Errorf("provisioning SSO Permission Set (%s): %w", permissionSetArn, err) } return nil diff --git a/internal/service/ssoadmin/permission_set.go b/internal/service/ssoadmin/permission_set.go index 4cc2a2e4936..bba013955d5 100644 --- a/internal/service/ssoadmin/permission_set.go +++ b/internal/service/ssoadmin/permission_set.go @@ -236,7 +236,7 @@ func resourcePermissionSetUpdate(d *schema.ResourceData, meta interface{}) error // Re-provision ALL accounts after making the above changes if err := provisionPermissionSet(conn, arn, instanceArn); err != nil { - return err + return fmt.Errorf("provisioning SSO Permission Set (%s): %w", arn, err) } return resourcePermissionSetRead(d, meta) diff --git a/internal/service/ssoadmin/permission_set_inline_policy.go b/internal/service/ssoadmin/permission_set_inline_policy.go index 44fab442764..8a38770934d 100644 --- a/internal/service/ssoadmin/permission_set_inline_policy.go +++ b/internal/service/ssoadmin/permission_set_inline_policy.go @@ -78,7 +78,7 @@ func resourcePermissionSetInlinePolicyPut(d *schema.ResourceData, meta interface // (Re)provision ALL accounts after making the above changes if err := provisionPermissionSet(conn, permissionSetArn, instanceArn); err != nil { - return err + return fmt.Errorf("provisioning SSO Permission Set (%s): %w", permissionSetArn, err) } return resourcePermissionSetInlinePolicyRead(d, meta) @@ -116,7 +116,7 @@ func resourcePermissionSetInlinePolicyRead(d *schema.ResourceData, meta interfac policyToSet, err := verify.PolicyToSet(d.Get("inline_policy").(string), aws.StringValue(output.InlinePolicy)) if err != nil { - return err + return fmt.Errorf("error reading Inline Policy for SSO Permission Set (%s): %w", permissionSetArn, err) } d.Set("inline_policy", policyToSet) diff --git a/internal/service/ssoadmin/permissions_boundary_attachment.go b/internal/service/ssoadmin/permissions_boundary_attachment.go index bb76777bd51..bae44633ef9 100644 --- a/internal/service/ssoadmin/permissions_boundary_attachment.go +++ b/internal/service/ssoadmin/permissions_boundary_attachment.go @@ -113,7 +113,7 @@ func resourcePermissionsBoundaryAttachmentCreate(d *schema.ResourceData, meta in // After the policy has been attached to the permission set, provision in all accounts that use this permission set. if err := provisionPermissionSet(conn, permissionSetARN, instanceARN); err != nil { - return err + return fmt.Errorf("provisioning SSO Permission Set (%s): %w", permissionSetARN, err) } return resourcePermissionsBoundaryAttachmentRead(d, meta) @@ -125,7 +125,7 @@ func resourcePermissionsBoundaryAttachmentRead(d *schema.ResourceData, meta inte permissionSetARN, instanceARN, err := PermissionsBoundaryAttachmentParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SSO Permissions Boundary Attachment (%s): %w", d.Id(), err) } policy, err := FindPermissionsBoundary(conn, permissionSetARN, instanceARN) @@ -155,7 +155,7 @@ func resourcePermissionsBoundaryAttachmentDelete(d *schema.ResourceData, meta in permissionSetARN, instanceARN, err := PermissionsBoundaryAttachmentParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting SSO Permissions Boundary Attachment (%s): %w", d.Id(), err) } input := &ssoadmin.DeletePermissionsBoundaryFromPermissionSetInput{ @@ -178,7 +178,7 @@ func resourcePermissionsBoundaryAttachmentDelete(d *schema.ResourceData, meta in // After the policy has been detached from the permission set, provision in all accounts that use this permission set. if err := provisionPermissionSet(conn, permissionSetARN, instanceARN); err != nil { - return err + return fmt.Errorf("provisioning SSO Permission Set (%s): %w", permissionSetARN, err) } return nil From 1ad4efa717bcc6e0b77cca4494b19e4d7f29dad9 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 18:17:34 -0800 Subject: [PATCH 014/106] Fixes bare errors in `ssm` --- internal/service/ssm/association.go | 2 +- internal/service/ssm/document.go | 16 ++++++++-------- .../service/ssm/maintenance_window_target.go | 2 +- internal/service/ssm/maintenance_window_task.go | 2 +- internal/service/ssm/patch_baseline.go | 4 ++-- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/internal/service/ssm/association.go b/internal/service/ssm/association.go index 78985f627de..7cea2e62702 100644 --- a/internal/service/ssm/association.go +++ b/internal/service/ssm/association.go @@ -268,7 +268,7 @@ func resourceAssociationRead(d *schema.ResourceData, meta interface{}) error { d.Set("automation_target_parameter_name", association.AutomationTargetParameterName) if err := d.Set("parameters", flattenParameters(association.Parameters)); err != nil { - return err + return fmt.Errorf("reading SSM Association (%s): %w", d.Id(), err) } if err := d.Set("targets", flattenTargets(association.Targets)); err != nil { diff --git a/internal/service/ssm/document.go b/internal/service/ssm/document.go index 554f597ecfb..ca4837f7ae6 100644 --- a/internal/service/ssm/document.go +++ b/internal/service/ssm/document.go @@ -240,7 +240,7 @@ func resourceDocumentCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("permissions"); ok && v != nil { if err := setDocumentPermissions(d, meta); err != nil { - return err + return fmt.Errorf("creating SSM document: setting permissions: %s", err) } } else { log.Printf("[DEBUG] Not setting permissions for %q", d.Id()) @@ -336,7 +336,7 @@ func resourceDocumentRead(d *schema.ResourceData, meta interface{}) error { gp, err := getDocumentPermissions(d, meta) if err != nil { - return fmt.Errorf("Error reading SSM document permissions: %s", err) + return fmt.Errorf("reading SSM document permissions: %s", err) } d.Set("permissions", gp) @@ -362,7 +362,7 @@ func resourceDocumentRead(d *schema.ResourceData, meta interface{}) error { } if err := d.Set("parameter", params); err != nil { - return err + return fmt.Errorf("setting parameter: %w", err) } tags := KeyValueTags(doc.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -404,7 +404,7 @@ func resourceDocumentUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("permissions") { if err := setDocumentPermissions(d, meta); err != nil { - return err + return fmt.Errorf("updating SSM Document (%s): setting permissions: %s", d.Id(), err) } } else { log.Printf("[DEBUG] Not setting document permissions on %q", d.Id()) @@ -419,7 +419,7 @@ func resourceDocumentUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChangesExcept("tags", "tags_all", "permissions") { if err := updateDocument(d, meta); err != nil { - return err + return fmt.Errorf("updating SSM Document (%s): %s", d.Id(), err) } _, err := waitDocumentActive(conn, d.Id()) @@ -435,7 +435,7 @@ func resourceDocumentDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SSMConn() if err := deleteDocumentPermissions(d, meta); err != nil { - return err + return fmt.Errorf("deleting SSM Document (%s): deleting permissions: %s", d.Id(), err) } log.Printf("[INFO] Deleting SSM Document: %s", d.Id()) @@ -446,7 +446,7 @@ func resourceDocumentDelete(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeleteDocument(params) if err != nil { - return err + return fmt.Errorf("deleting SSM Document (%s): %s", d.Id(), err) } _, err = waitDocumentDeleted(conn, d.Id()) @@ -526,7 +526,7 @@ func setDocumentPermissions(d *schema.ResourceData, meta interface{}) error { } if err := modifyDocumentPermissions(conn, d.Get("name").(string), accountIdsToAdd, accountIdsToRemove); err != nil { - return fmt.Errorf("error modifying SSM document permissions: %s", err) + return err // nosemgrep:bare-error-returns } } diff --git a/internal/service/ssm/maintenance_window_target.go b/internal/service/ssm/maintenance_window_target.go index 698cd85845e..1eae0224f4a 100644 --- a/internal/service/ssm/maintenance_window_target.go +++ b/internal/service/ssm/maintenance_window_target.go @@ -118,7 +118,7 @@ func resourceMaintenanceWindowTargetCreate(d *schema.ResourceData, meta interfac resp, err := conn.RegisterTargetWithMaintenanceWindow(params) if err != nil { - return err + return fmt.Errorf("creating SSM Maintenance Window Target: %w", err) } d.SetId(aws.StringValue(resp.WindowTargetId)) diff --git a/internal/service/ssm/maintenance_window_task.go b/internal/service/ssm/maintenance_window_task.go index e046ecc787b..44bce8ea1cf 100644 --- a/internal/service/ssm/maintenance_window_task.go +++ b/internal/service/ssm/maintenance_window_task.go @@ -716,7 +716,7 @@ func resourceMaintenanceWindowTaskCreate(d *schema.ResourceData, meta interface{ resp, err := conn.RegisterTaskWithMaintenanceWindow(params) if err != nil { - return err + return fmt.Errorf("creating SSM Maintenance Window Task: %w", err) } d.SetId(aws.StringValue(resp.WindowTaskId)) diff --git a/internal/service/ssm/patch_baseline.go b/internal/service/ssm/patch_baseline.go index 004882f0670..eaa6605dbea 100644 --- a/internal/service/ssm/patch_baseline.go +++ b/internal/service/ssm/patch_baseline.go @@ -276,7 +276,7 @@ func resourcePatchBaselineCreate(d *schema.ResourceData, meta interface{}) error resp, err := conn.CreatePatchBaseline(params) if err != nil { - return err + return fmt.Errorf("creating SSM Patch Baseline: %w", err) } d.SetId(aws.StringValue(resp.BaselineId)) @@ -364,7 +364,7 @@ func resourcePatchBaselineRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading SSM Patch Baseline (%s): %w", d.Id(), err) } d.Set("name", resp.Name) From 4c1797bbfe480d705a4b0c7fe8d6d95b3769f2a2 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 18:17:59 -0800 Subject: [PATCH 015/106] Fixes bare errors in `signer` --- .../signer/signing_profile_permission.go | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/internal/service/signer/signing_profile_permission.go b/internal/service/signer/signing_profile_permission.go index 98cdd50d340..038d2cbc836 100644 --- a/internal/service/signer/signing_profile_permission.go +++ b/internal/service/signer/signing_profile_permission.go @@ -93,7 +93,7 @@ func resourceSigningProfilePermissionCreate(d *schema.ResourceData, meta interfa if tfawserr.ErrCodeEquals(err, signer.ErrCodeResourceNotFoundException) { revisionId = "" } else { - return err + return fmt.Errorf("creating Signer Signing Profile Permission: %w", err) } } else { revisionId = aws.StringValue(getProfilePermissionsOutput.RevisionId) @@ -113,7 +113,7 @@ func resourceSigningProfilePermissionCreate(d *schema.ResourceData, meta interfa addProfilePermissionInput.ProfileVersion = aws.String(v.(string)) } - log.Printf("[DEBUG] Adding new Signer signing profile permission: %s", addProfilePermissionInput) + log.Printf("[DEBUG] Adding new Signer Signing Profile Permission: %s", addProfilePermissionInput) // Retry for IAM eventual consistency err = resource.Retry(propagationTimeout, func() *resource.RetryError { _, err := conn.AddProfilePermission(addProfilePermissionInput) @@ -132,7 +132,7 @@ func resourceSigningProfilePermissionCreate(d *schema.ResourceData, meta interfa } if err != nil { - return fmt.Errorf("error adding new Signer signing profile permission for %q: %s", profileName, err) + return fmt.Errorf("error adding new Signer Signing Profile Permission for %q: %s", profileName, err) } err = resource.Retry(propagationTimeout, func() *resource.RetryError { @@ -141,11 +141,11 @@ func resourceSigningProfilePermissionCreate(d *schema.ResourceData, meta interfa if err != nil { if tfawserr.ErrCodeEquals(err, signer.ErrCodeResourceNotFoundException) { return resource.RetryableError( - fmt.Errorf("error reading newly created Signer signing profile permission for %s, retrying: %s", + fmt.Errorf("error reading newly created Signer Signing Profile Permission for %s, retrying: %s", *addProfilePermissionInput.ProfileName, err)) } - log.Printf("[ERROR] An actual error occurred when expecting Signer signing profile permission to be there: %s", err) + log.Printf("[ERROR] An actual error occurred when expecting Signer Signing Profile Permission to be there: %s", err) return resource.NonRetryableError(err) } return nil @@ -170,7 +170,7 @@ func resourceSigningProfilePermissionRead(d *schema.ResourceData, meta interface ProfileName: aws.String(d.Get("profile_name").(string)), } - log.Printf("[DEBUG] Getting Signer signing profile permissions: %s", listProfilePermissionsInput) + log.Printf("[DEBUG] Getting Signer Signing Profile Permissions: %s", listProfilePermissionsInput) var listProfilePermissionsOutput *signer.ListProfilePermissionsOutput err := resource.Retry(propagationTimeout, func() *resource.RetryError { // IAM is eventually consistent :/ @@ -202,7 +202,7 @@ func resourceSigningProfilePermissionRead(d *schema.ResourceData, meta interface statementId := d.Get("statement_id").(string) permission := getProfilePermission(listProfilePermissionsOutput.Permissions, statementId) if permission == nil { - log.Printf("[WARN] No Signer signing profile permission found matching statement id: %s", statementId) + log.Printf("[WARN] No Signer Signing Profile Permission found matching statement id: %s", statementId) d.SetId("") return nil } @@ -252,10 +252,10 @@ func resourceSigningProfilePermissionDelete(d *schema.ResourceData, meta interfa listProfilePermissionsOutput, err := conn.ListProfilePermissions(listProfilePermissionsInput) if err != nil { if tfawserr.ErrCodeEquals(err, signer.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] No Signer signing profile permission found for: %v", listProfilePermissionsInput) + log.Printf("[WARN] No Signer Signing Profile Permission found for: %v", listProfilePermissionsInput) return nil } - return err + return fmt.Errorf("deleting Signer Signing Profile Permission (%s): %w", d.Id(), err) } revisionId := aws.StringValue(listProfilePermissionsOutput.RevisionId) @@ -263,7 +263,7 @@ func resourceSigningProfilePermissionDelete(d *schema.ResourceData, meta interfa statementId := d.Get("statement_id").(string) permission := getProfilePermission(listProfilePermissionsOutput.Permissions, statementId) if permission == nil { - log.Printf("[WARN] No Signer signing profile permission found matching statement id: %s", statementId) + log.Printf("[WARN] No Signer Signing Profile Permission found matching statement id: %s", statementId) return nil } @@ -280,7 +280,7 @@ func resourceSigningProfilePermissionDelete(d *schema.ResourceData, meta interfa log.Printf("[WARN] No Signer Signing Profile Permission found: %v", removeProfilePermissionInput) return nil } - return fmt.Errorf("error removing Signer Signing Profile Permission (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Signer Signing Profile Permission (%s): %w", d.Id(), err) } params := &signer.ListProfilePermissionsInput{ @@ -294,7 +294,7 @@ func resourceSigningProfilePermissionDelete(d *schema.ResourceData, meta interfa } if err != nil { - return fmt.Errorf("error getting Signer signing profile permissions: %s", err) + return fmt.Errorf("error getting Signer Signing Profile Permissions: %s", err) } if len(resp.Permissions) > 0 { @@ -304,7 +304,7 @@ func resourceSigningProfilePermissionDelete(d *schema.ResourceData, meta interfa } } - log.Printf("[DEBUG] Signer signing profile permission with ID %q removed", statementId) + log.Printf("[DEBUG] Signer Signing Profile Permission with ID %q removed", statementId) return nil } From 9d4c5de342abe51b132c37f7c2509e93247b4d94 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 18:18:24 -0800 Subject: [PATCH 016/106] Fixes bare errors in `ses` --- internal/service/ses/active_receipt_rule_set.go | 2 +- internal/service/ses/configuration_set.go | 2 +- internal/service/ses/domain_dkim.go | 5 ++--- internal/service/ses/domain_identity.go | 5 ++--- .../service/ses/domain_identity_verification.go | 5 ++--- internal/service/ses/email_identity.go | 5 ++--- internal/service/ses/event_destination.go | 5 ++++- .../service/ses/identity_notification_topic.go | 12 ++++-------- internal/service/ses/identity_policy.go | 8 ++++---- internal/service/ses/receipt_filter.go | 4 ++-- internal/service/ses/receipt_rule.go | 16 ++++++++-------- 11 files changed, 32 insertions(+), 37 deletions(-) diff --git a/internal/service/ses/active_receipt_rule_set.go b/internal/service/ses/active_receipt_rule_set.go index a1d4b31c627..25733f1a29e 100644 --- a/internal/service/ses/active_receipt_rule_set.go +++ b/internal/service/ses/active_receipt_rule_set.go @@ -65,7 +65,7 @@ func resourceActiveReceiptRuleSetRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return err + return fmt.Errorf("reading SES Active Receipt Rule Set: %w", err) } if response.Metadata == nil { diff --git a/internal/service/ses/configuration_set.go b/internal/service/ses/configuration_set.go index ee6a95be3bf..a40fd72751d 100644 --- a/internal/service/ses/configuration_set.go +++ b/internal/service/ses/configuration_set.go @@ -171,7 +171,7 @@ func resourceConfigurationSetRead(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return err + return fmt.Errorf("reading SES Configuration Set (%s): %w", d.Id(), err) } if err := d.Set("delivery_options", flattenConfigurationSetDeliveryOptions(response.DeliveryOptions)); err != nil { diff --git a/internal/service/ses/domain_dkim.go b/internal/service/ses/domain_dkim.go index 57402c665dc..5b7d6634ad8 100644 --- a/internal/service/ses/domain_dkim.go +++ b/internal/service/ses/domain_dkim.go @@ -67,13 +67,12 @@ func resourceDomainDKIMRead(d *schema.ResourceData, meta interface{}) error { response, err := conn.GetIdentityDkimAttributes(readOpts) if err != nil { - log.Printf("[WARN] Error fetching identity verification attributes for %s: %s", d.Id(), err) - return err + return fmt.Errorf("reading SES Domain DKIM (%s): %w", d.Id(), err) } verificationAttrs, ok := response.DkimAttributes[domainName] if !ok { - log.Printf("[WARN] Domain not listed in response when fetching verification attributes for %s", d.Id()) + log.Printf("[WARN] SES Domain DKIM (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/ses/domain_identity.go b/internal/service/ses/domain_identity.go index 725c10a1069..736bc55ef9d 100644 --- a/internal/service/ses/domain_identity.go +++ b/internal/service/ses/domain_identity.go @@ -74,13 +74,12 @@ func resourceDomainIdentityRead(d *schema.ResourceData, meta interface{}) error response, err := conn.GetIdentityVerificationAttributes(readOpts) if err != nil { - log.Printf("[WARN] Error fetching identity verification attributes for %s: %s", d.Id(), err) - return err + return fmt.Errorf("reading SES Domain Identity (%s): %w", domainName, err) } verificationAttrs, ok := response.VerificationAttributes[domainName] if !ok { - log.Printf("[WARN] Domain not listed in response when fetching verification attributes for %s", d.Id()) + log.Printf("[WARN] SES Domain Identity (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/ses/domain_identity_verification.go b/internal/service/ses/domain_identity_verification.go index 2989ff84019..074778d90ed 100644 --- a/internal/service/ses/domain_identity_verification.go +++ b/internal/service/ses/domain_identity_verification.go @@ -99,12 +99,11 @@ func resourceDomainIdentityVerificationRead(d *schema.ResourceData, meta interfa att, err := getIdentityVerificationAttributes(conn, domainName) if err != nil { - log.Printf("[WARN] Error fetching identity verification attributes for %s: %s", d.Id(), err) - return err + return fmt.Errorf("reading SES Domain Identity Verification (%s): %w", domainName, err) } if att == nil { - log.Printf("[WARN] Domain not listed in response when fetching verification attributes for %s", d.Id()) + log.Printf("[WARN] SES Domain Identity Verification (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/ses/email_identity.go b/internal/service/ses/email_identity.go index 494a1e4a0f3..f8080a2ab33 100644 --- a/internal/service/ses/email_identity.go +++ b/internal/service/ses/email_identity.go @@ -72,13 +72,12 @@ func resourceEmailIdentityRead(d *schema.ResourceData, meta interface{}) error { response, err := conn.GetIdentityVerificationAttributes(readOpts) if err != nil { - log.Printf("[WARN] Error fetching identity verification attributes for %s: %s", d.Id(), err) - return err + return fmt.Errorf("reading SES Identity Verification Attributes (%s): %w", d.Id(), err) } _, ok := response.VerificationAttributes[email] if !ok { - log.Printf("[WARN] Email not listed in response when fetching verification attributes for %s", d.Id()) + log.Printf("[WARN] SES Identity Verification Attributes (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/ses/event_destination.go b/internal/service/ses/event_destination.go index 5141bdfd970..2622ea8e1e1 100644 --- a/internal/service/ses/event_destination.go +++ b/internal/service/ses/event_destination.go @@ -258,7 +258,10 @@ func resourceEventDestinationDelete(d *schema.ResourceData, meta interface{}) er EventDestinationName: aws.String(d.Id()), }) - return err + if err != nil { + return fmt.Errorf("deleting SES Event Destination (%s): %w", d.Id(), err) + } + return nil } func resourceEventDestinationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { diff --git a/internal/service/ses/identity_notification_topic.go b/internal/service/ses/identity_notification_topic.go index 7c342471d43..69b478ec238 100644 --- a/internal/service/ses/identity_notification_topic.go +++ b/internal/service/ses/identity_notification_topic.go @@ -99,7 +99,7 @@ func resourceIdentityNotificationTopicRead(d *schema.ResourceData, meta interfac identity, notificationType, err := decodeIdentityNotificationTopicID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SES Identity Notification Topic (%s): %w", d.Id(), err) } d.Set("identity", identity) @@ -109,12 +109,10 @@ func resourceIdentityNotificationTopicRead(d *schema.ResourceData, meta interfac Identities: []*string{aws.String(identity)}, } - log.Printf("[DEBUG] Reading SES Identity Notification Topic Attributes: %#v", getOpts) - response, err := conn.GetIdentityNotificationAttributes(getOpts) if err != nil { - return fmt.Errorf("Error reading SES Identity Notification Topic: %s", err) + return fmt.Errorf("reading SES Identity Notification Topic (%s): %w", d.Id(), err) } d.Set("topic_arn", "") @@ -147,7 +145,7 @@ func resourceIdentityNotificationTopicDelete(d *schema.ResourceData, meta interf identity, notificationType, err := decodeIdentityNotificationTopicID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting SES Identity Notification Topic (%s): %s", d.Id(), err) } setOpts := &ses.SetIdentityNotificationTopicInput{ @@ -156,10 +154,8 @@ func resourceIdentityNotificationTopicDelete(d *schema.ResourceData, meta interf SnsTopic: nil, } - log.Printf("[DEBUG] Deleting SES Identity Notification Topic: %#v", setOpts) - if _, err := conn.SetIdentityNotificationTopic(setOpts); err != nil { - return fmt.Errorf("Error deleting SES Identity Notification Topic: %s", err) + return fmt.Errorf("deleting SES Identity Notification Topic (%s): %s", d.Id(), err) } return resourceIdentityNotificationTopicRead(d, meta) diff --git a/internal/service/ses/identity_policy.go b/internal/service/ses/identity_policy.go index a7139a2d940..38add09ef49 100644 --- a/internal/service/ses/identity_policy.go +++ b/internal/service/ses/identity_policy.go @@ -87,7 +87,7 @@ func resourceIdentityPolicyUpdate(d *schema.ResourceData, meta interface{}) erro identity, policyName, err := IdentityPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating SES Identity Policy (%s): %s", d.Id(), err) } policy, err := structure.NormalizeJsonString(d.Get("policy").(string)) @@ -114,7 +114,7 @@ func resourceIdentityPolicyRead(d *schema.ResourceData, meta interface{}) error identity, policyName, err := IdentityPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SES Identity Policy (%s): %s", d.Id(), err) } input := &ses.GetIdentityPoliciesInput{ @@ -150,7 +150,7 @@ func resourceIdentityPolicyRead(d *schema.ResourceData, meta interface{}) error policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(policy)) if err != nil { - return err + return fmt.Errorf("reading SES Identity Policy (%s): %s", d.Id(), err) } d.Set("policy", policyToSet) @@ -163,7 +163,7 @@ func resourceIdentityPolicyDelete(d *schema.ResourceData, meta interface{}) erro identity, policyName, err := IdentityPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting SES Identity Policy (%s): %s", d.Id(), err) } input := &ses.DeleteIdentityPolicyInput{ diff --git a/internal/service/ses/receipt_filter.go b/internal/service/ses/receipt_filter.go index f703da286ad..113d310232f 100644 --- a/internal/service/ses/receipt_filter.go +++ b/internal/service/ses/receipt_filter.go @@ -94,7 +94,7 @@ func resourceReceiptFilterRead(d *schema.ResourceData, meta interface{}) error { response, err := conn.ListReceiptFilters(listOpts) if err != nil { - return err + return fmt.Errorf("reading SES Receipt Filter (%s): %s", d.Id(), err) } var filter *ses.ReceiptFilter @@ -107,7 +107,7 @@ func resourceReceiptFilterRead(d *schema.ResourceData, meta interface{}) error { } if filter == nil { - log.Printf("[WARN] SES Receipt Filter (%s) not found", d.Id()) + log.Printf("[WARN] SES Receipt Filter (%s) not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/ses/receipt_rule.go b/internal/service/ses/receipt_rule.go index c353e41753b..5c9238ffebb 100644 --- a/internal/service/ses/receipt_rule.go +++ b/internal/service/ses/receipt_rule.go @@ -485,7 +485,7 @@ func resourceReceiptRuleRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading SES Receipt Rule (%s): %s", d.Id(), err) } d.Set("enabled", response.Rule.Enabled) @@ -607,37 +607,37 @@ func resourceReceiptRuleRead(d *schema.ResourceData, meta interface{}) error { err = d.Set("add_header_action", addHeaderActionList) if err != nil { - return err + return fmt.Errorf("setting add_header_action: %w", err) } err = d.Set("bounce_action", bounceActionList) if err != nil { - return err + return fmt.Errorf("setting bounce_action: %w", err) } err = d.Set("lambda_action", lambdaActionList) if err != nil { - return err + return fmt.Errorf("setting lambda_action: %w", err) } err = d.Set("s3_action", s3ActionList) if err != nil { - return err + return fmt.Errorf("setting s3_action: %w", err) } err = d.Set("sns_action", snsActionList) if err != nil { - return err + return fmt.Errorf("setting sns_action: %w", err) } err = d.Set("stop_action", stopActionList) if err != nil { - return err + return fmt.Errorf("setting stop_action: %w", err) } err = d.Set("workmail_action", workmailActionList) if err != nil { - return err + return fmt.Errorf("setting workmail_action: %w", err) } arn := arn.ARN{ From 24f8be14e386391dc7e91cac038a85431365fc33 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Mon, 9 Jan 2023 18:20:14 -0800 Subject: [PATCH 017/106] Fixes bare errors in `servicequotas` --- internal/service/servicequotas/service_quota.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/servicequotas/service_quota.go b/internal/service/servicequotas/service_quota.go index bfe002cbeb5..dcf94a44085 100644 --- a/internal/service/servicequotas/service_quota.go +++ b/internal/service/servicequotas/service_quota.go @@ -135,7 +135,7 @@ func resourceServiceQuotaRead(d *schema.ResourceData, meta interface{}) error { serviceCode, quotaCode, err := resourceServiceQuotaParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Service Quota (%s): %s", d.Id(), err) } // A Service Quota will always have a default value, but will only have a current value if it has been set. @@ -208,7 +208,7 @@ func resourceServiceQuotaUpdate(d *schema.ResourceData, meta interface{}) error serviceCode, quotaCode, err := resourceServiceQuotaParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Service Quota (%s): %s", d.Id(), err) } input := &servicequotas.RequestServiceQuotaIncreaseInput{ From 0f163db12903fd917b8e5ab12172d0cdab12eea0 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 11:50:23 -0800 Subject: [PATCH 018/106] Fixes bare errors in `serverlessrepo` --- internal/service/serverlessrepo/cloudformation_stack.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/internal/service/serverlessrepo/cloudformation_stack.go b/internal/service/serverlessrepo/cloudformation_stack.go index 662b92c32c7..f0e01570bcc 100644 --- a/internal/service/serverlessrepo/cloudformation_stack.go +++ b/internal/service/serverlessrepo/cloudformation_stack.go @@ -257,22 +257,19 @@ func resourceCloudFormationStackDelete(d *schema.ResourceData, meta interface{}) StackName: aws.String(d.Id()), ClientRequestToken: aws.String(requestToken), } - log.Printf("[DEBUG] Deleting Serverless Application Repository CloudFormation stack %s", input) _, err := conn.DeleteStack(input) if tfawserr.ErrCodeEquals(err, "ValidationError") { return nil } if err != nil { - return err + return fmt.Errorf("deleting Serverless Application Repository CloudFormation Stack (%s): %w", d.Id(), err) } _, err = tfcloudformation.WaitStackDeleted(conn, d.Id(), requestToken, d.Timeout(schema.TimeoutDelete)) if err != nil { - return fmt.Errorf("error waiting for Serverless Application Repository CloudFormation Stack deletion: %w", err) + return fmt.Errorf("deleting Serverless Application Repository CloudFormation Stack (%s): waiting for completion: %w", d.Id(), err) } - log.Printf("[INFO] Serverless Application Repository CloudFormation stack (%s) deleted", d.Id()) - return nil } From 4873e02259db58d4aabd197972acb44878d4d7ee Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 11:50:42 -0800 Subject: [PATCH 019/106] Fixes bare errors in `securityhub` --- internal/service/securityhub/action_target.go | 16 ++++++------ .../service/securityhub/invite_accepter.go | 6 ++--- internal/service/securityhub/member.go | 26 +++++++++---------- .../securityhub/product_subscription.go | 20 +++++++------- 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/internal/service/securityhub/action_target.go b/internal/service/securityhub/action_target.go index 61fe6fa9e44..619f01459a2 100644 --- a/internal/service/securityhub/action_target.go +++ b/internal/service/securityhub/action_target.go @@ -58,7 +58,7 @@ func resourceActionTargetCreate(d *schema.ResourceData, meta interface{}) error name := d.Get("name").(string) identifier := d.Get("identifier").(string) - log.Printf("[DEBUG] Creating Security Hub custom action target %s", identifier) + log.Printf("[DEBUG] Creating Security Hub Action Target %s", identifier) resp, err := conn.CreateActionTarget(&securityhub.CreateActionTargetInput{ Description: aws.String(description), @@ -67,7 +67,7 @@ func resourceActionTargetCreate(d *schema.ResourceData, meta interface{}) error }) if err != nil { - return fmt.Errorf("Error creating Security Hub custom action target %s: %s", identifier, err) + return fmt.Errorf("creating Security Hub Action Target %s: %s", identifier, err) } d.SetId(aws.StringValue(resp.ActionTargetArn)) @@ -88,22 +88,22 @@ func resourceActionTargetParseIdentifier(identifier string) (string, error) { func resourceActionTargetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SecurityHubConn() - log.Printf("[DEBUG] Reading Security Hub custom action targets to find %s", d.Id()) + log.Printf("[DEBUG] Reading Security Hub Action Targets to find %s", d.Id()) actionTargetIdentifier, err := resourceActionTargetParseIdentifier(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Security Hub Action Targets (%s): %s", d.Id(), err) } actionTarget, err := ActionTargetCheckExists(conn, d.Id()) if err != nil { - return fmt.Errorf("Error reading Security Hub custom action targets to find %s: %s", d.Id(), err) + return fmt.Errorf("reading Security Hub Action Targets (%s): %s", d.Id(), err) } if actionTarget == nil { - log.Printf("[WARN] Security Hub custom action target (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] Security Hub Action Target (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -154,14 +154,14 @@ func ActionTargetCheckExists(conn *securityhub.SecurityHub, actionTargetArn stri func resourceActionTargetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SecurityHubConn() - log.Printf("[DEBUG] Deleting Security Hub custom action target %s", d.Id()) + log.Printf("[DEBUG] Deleting Security Hub Action Target %s", d.Id()) _, err := conn.DeleteActionTarget(&securityhub.DeleteActionTargetInput{ ActionTargetArn: aws.String(d.Id()), }) if err != nil { - return fmt.Errorf("Error deleting Security Hub custom action target %s: %s", d.Id(), err) + return fmt.Errorf("deleting Security Hub Action Target %s: %s", d.Id(), err) } return nil diff --git a/internal/service/securityhub/invite_accepter.go b/internal/service/securityhub/invite_accepter.go index fd7d770e930..e4e2a96a634 100644 --- a/internal/service/securityhub/invite_accepter.go +++ b/internal/service/securityhub/invite_accepter.go @@ -42,7 +42,7 @@ func resourceInviteAccepterCreate(d *schema.ResourceData, meta interface{}) erro invitationId, err := resourceInviteAccepterGetInvitationID(conn, d.Get("master_id").(string)) if err != nil { - return err + return fmt.Errorf("accepting Security Hub invitation: %w", err) } _, err = conn.AcceptInvitation(&securityhub.AcceptInvitationInput{ @@ -51,7 +51,7 @@ func resourceInviteAccepterCreate(d *schema.ResourceData, meta interface{}) erro }) if err != nil { - return fmt.Errorf("error accepting Security Hub invitation: %w", err) + return fmt.Errorf("accepting Security Hub invitation: %w", err) } d.SetId(meta.(*conns.AWSClient).AccountID) @@ -65,7 +65,7 @@ func resourceInviteAccepterGetInvitationID(conn *securityhub.SecurityHub, master resp, err := conn.ListInvitations(&securityhub.ListInvitationsInput{}) if err != nil { - return "", fmt.Errorf("error listing Security Hub invitations: %w", err) + return "", fmt.Errorf("listing Security Hub invitations: %w", err) } for _, invitation := range resp.Invitations { diff --git a/internal/service/securityhub/member.go b/internal/service/securityhub/member.go index a0c5bd7c111..658ef862d7f 100644 --- a/internal/service/securityhub/member.go +++ b/internal/service/securityhub/member.go @@ -60,7 +60,7 @@ func ResourceMember() *schema.Resource { func resourceMemberCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SecurityHubConn() - log.Printf("[DEBUG] Creating Security Hub member %s", d.Get("account_id").(string)) + log.Printf("[DEBUG] Creating Security Hub Member %s", d.Get("account_id").(string)) resp, err := conn.CreateMembers(&securityhub.CreateMembersInput{ AccountDetails: []*securityhub.AccountDetails{ @@ -72,27 +72,27 @@ func resourceMemberCreate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("Error creating Security Hub member %s: %s", d.Get("account_id").(string), err) + return fmt.Errorf("Error creating Security Hub Member %s: %s", d.Get("account_id").(string), err) } if len(resp.UnprocessedAccounts) > 0 { - return fmt.Errorf("Error creating Security Hub member %s: UnprocessedAccounts is not empty", d.Get("account_id").(string)) + return fmt.Errorf("Error creating Security Hub Member %s: UnprocessedAccounts is not empty", d.Get("account_id").(string)) } d.SetId(d.Get("account_id").(string)) if d.Get("invite").(bool) { - log.Printf("[INFO] Inviting Security Hub member %s", d.Id()) + log.Printf("[INFO] Inviting Security Hub Member %s", d.Id()) iresp, err := conn.InviteMembers(&securityhub.InviteMembersInput{ AccountIds: []*string{aws.String(d.Get("account_id").(string))}, }) if err != nil { - return fmt.Errorf("Error inviting Security Hub member %s: %s", d.Id(), err) + return fmt.Errorf("Error inviting Security Hub Member %s: %s", d.Id(), err) } if len(iresp.UnprocessedAccounts) > 0 { - return fmt.Errorf("Error inviting Security Hub member %s: UnprocessedAccounts is not empty", d.Id()) + return fmt.Errorf("Error inviting Security Hub Member %s: UnprocessedAccounts is not empty", d.Id()) } } @@ -102,22 +102,22 @@ func resourceMemberCreate(d *schema.ResourceData, meta interface{}) error { func resourceMemberRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SecurityHubConn() - log.Printf("[DEBUG] Reading Security Hub member %s", d.Id()) + log.Printf("[DEBUG] Reading Security Hub Member %s", d.Id()) resp, err := conn.GetMembers(&securityhub.GetMembersInput{ AccountIds: []*string{aws.String(d.Id())}, }) if err != nil { if tfawserr.ErrCodeEquals(err, securityhub.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] Security Hub member (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] Security Hub Member (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading Security Hub Member (%s): %w", d.Id(), err) } if len(resp.Members) == 0 { - log.Printf("[WARN] Security Hub member (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] Security Hub Member (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -147,7 +147,7 @@ func resourceMemberDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error disassociating Security Hub member %s: %w", d.Id(), err) + return fmt.Errorf("Error disassociating Security Hub Member %s: %w", d.Id(), err) } resp, err := conn.DeleteMembers(&securityhub.DeleteMembersInput{ @@ -158,11 +158,11 @@ func resourceMemberDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error deleting Security Hub member %s: %w", d.Id(), err) + return fmt.Errorf("Error deleting Security Hub Member %s: %w", d.Id(), err) } if len(resp.UnprocessedAccounts) > 0 { - return fmt.Errorf("Error deleting Security Hub member %s: UnprocessedAccounts is not empty", d.Get("account_id").(string)) + return fmt.Errorf("Error deleting Security Hub Member %s: UnprocessedAccounts is not empty", d.Get("account_id").(string)) } return nil diff --git a/internal/service/securityhub/product_subscription.go b/internal/service/securityhub/product_subscription.go index baa07713eeb..806c0d63c45 100644 --- a/internal/service/securityhub/product_subscription.go +++ b/internal/service/securityhub/product_subscription.go @@ -40,14 +40,14 @@ func resourceProductSubscriptionCreate(d *schema.ResourceData, meta interface{}) conn := meta.(*conns.AWSClient).SecurityHubConn() productArn := d.Get("product_arn").(string) - log.Printf("[DEBUG] Enabling Security Hub product subscription for product %s", productArn) + log.Printf("[DEBUG] Enabling Security Hub Product Subscription for product %s", productArn) resp, err := conn.EnableImportFindingsForProduct(&securityhub.EnableImportFindingsForProductInput{ ProductArn: aws.String(productArn), }) if err != nil { - return fmt.Errorf("Error enabling Security Hub product subscription for product %s: %s", productArn, err) + return fmt.Errorf("Error enabling Security Hub Product Subscription for product %s: %s", productArn, err) } d.SetId(fmt.Sprintf("%s,%s", productArn, *resp.ProductSubscriptionArn)) @@ -61,19 +61,19 @@ func resourceProductSubscriptionRead(d *schema.ResourceData, meta interface{}) e productArn, productSubscriptionArn, err := ProductSubscriptionParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Security Hub Product Subscription (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Reading Security Hub product subscriptions to find %s", d.Id()) + log.Printf("[DEBUG] Reading Security Hub Product Subscriptions to find %s", d.Id()) exists, err := ProductSubscriptionCheckExists(conn, productSubscriptionArn) if err != nil { - return fmt.Errorf("Error reading Security Hub product subscriptions to find %s: %s", d.Id(), err) + return fmt.Errorf("reading Security Hub Product Subscription (%s): %s", d.Id(), err) } if !exists { - log.Printf("[WARN] Security Hub product subscriptions (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] Security Hub Product Subscription (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -109,7 +109,7 @@ func ProductSubscriptionParseID(id string) (string, string, error) { parts := strings.SplitN(id, ",", 2) if len(parts) != 2 { - return "", "", fmt.Errorf("Expected Security Hub product subscription ID in format , - received: %s", id) + return "", "", fmt.Errorf("Expected Security Hub Product Subscription ID in format , - received: %s", id) } return parts[0], parts[1], nil @@ -117,12 +117,12 @@ func ProductSubscriptionParseID(id string) (string, string, error) { func resourceProductSubscriptionDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).SecurityHubConn() - log.Printf("[DEBUG] Disabling Security Hub product subscription %s", d.Id()) + log.Printf("[DEBUG] Disabling Security Hub Product Subscription %s", d.Id()) _, productSubscriptionArn, err := ProductSubscriptionParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("disabling Security Hub Product Subscription (%s): %s", d.Id(), err) } _, err = conn.DisableImportFindingsForProduct(&securityhub.DisableImportFindingsForProductInput{ @@ -130,7 +130,7 @@ func resourceProductSubscriptionDelete(d *schema.ResourceData, meta interface{}) }) if err != nil { - return fmt.Errorf("Error disabling Security Hub product subscription %s: %s", d.Id(), err) + return fmt.Errorf("disabling Security Hub Product Subscription (%s): %s", d.Id(), err) } return nil From f00e9260fcad5a6eb6e292746c156518e0b09d0f Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 11:50:58 -0800 Subject: [PATCH 020/106] Fixes bare errors in `secretsmanager` --- internal/service/secretsmanager/secret.go | 2 +- internal/service/secretsmanager/secret_policy.go | 2 +- internal/service/secretsmanager/secret_version.go | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/service/secretsmanager/secret.go b/internal/service/secretsmanager/secret.go index 08c9c27103a..5339094be77 100644 --- a/internal/service/secretsmanager/secret.go +++ b/internal/service/secretsmanager/secret.go @@ -300,7 +300,7 @@ func resourceSecretRead(d *schema.ResourceData, meta interface{}) error { } else if v := output.ResourcePolicy; v != nil { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(v)) if err != nil { - return err + return fmt.Errorf("reading Secrets Manager Secret (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) diff --git a/internal/service/secretsmanager/secret_policy.go b/internal/service/secretsmanager/secret_policy.go index 2a1c196d182..a5cbd8f9d14 100644 --- a/internal/service/secretsmanager/secret_policy.go +++ b/internal/service/secretsmanager/secret_policy.go @@ -126,7 +126,7 @@ func resourceSecretPolicyRead(d *schema.ResourceData, meta interface{}) error { if output.ResourcePolicy != nil { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(output.ResourcePolicy)) if err != nil { - return err + return fmt.Errorf("reading Secrets Manager Secret Policy (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) diff --git a/internal/service/secretsmanager/secret_version.go b/internal/service/secretsmanager/secret_version.go index d801c6c1fb0..6b35f4c3810 100644 --- a/internal/service/secretsmanager/secret_version.go +++ b/internal/service/secretsmanager/secret_version.go @@ -112,7 +112,7 @@ func resourceSecretVersionRead(d *schema.ResourceData, meta interface{}) error { secretID, versionID, err := DecodeSecretVersionID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Secrets Manager Secret Version (%s): %w", d.Id(), err) } input := &secretsmanager.GetSecretValueInput{ @@ -184,7 +184,7 @@ func resourceSecretVersionUpdate(d *schema.ResourceData, meta interface{}) error secretID, versionID, err := DecodeSecretVersionID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Secrets Manager Secret Version (%s): %w", d.Id(), err) } o, n := d.GetChange("version_stages") @@ -233,7 +233,7 @@ func resourceSecretVersionDelete(d *schema.ResourceData, meta interface{}) error secretID, versionID, err := DecodeSecretVersionID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Secrets Manager Secret Version (%s): %w", d.Id(), err) } if v, ok := d.GetOk("version_stages"); ok { From a2743ba4b3b1262de239a9b6bd7ad3a784fc4e04 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 11:51:19 -0800 Subject: [PATCH 021/106] Fixes bare errors in `sagemaker` --- internal/service/sagemaker/app.go | 6 +- internal/service/sagemaker/device.go | 10 +- internal/service/sagemaker/domain.go | 20 ++-- .../sagemaker/model_package_group_policy.go | 2 +- .../service/sagemaker/notebook_instance.go | 94 +++++++++---------- internal/service/sagemaker/space.go | 2 +- internal/service/sagemaker/user_profile.go | 6 +- internal/service/sagemaker/wait.go | 26 +++++ 8 files changed, 94 insertions(+), 72 deletions(-) diff --git a/internal/service/sagemaker/app.go b/internal/service/sagemaker/app.go index e57404056b0..979cb305788 100644 --- a/internal/service/sagemaker/app.go +++ b/internal/service/sagemaker/app.go @@ -141,13 +141,13 @@ func resourceAppCreate(d *schema.ResourceData, meta interface{}) error { appArn := aws.StringValue(output.AppArn) domainID, userProfileOrSpaceName, appType, appName, err := decodeAppID(appArn) if err != nil { - return err + return fmt.Errorf("creating SageMaker App (%s): %w", appArn, err) } d.SetId(appArn) if _, err := WaitAppInService(conn, domainID, userProfileOrSpaceName, appType, appName); err != nil { - return fmt.Errorf("waiting for SageMaker App (%s) to create: %w", d.Id(), err) + return fmt.Errorf("create SageMaker App (%s): waiting for completion: %w", d.Id(), err) } return resourceAppRead(d, meta) @@ -160,7 +160,7 @@ func resourceAppRead(d *schema.ResourceData, meta interface{}) error { domainID, userProfileOrSpaceName, appType, appName, err := decodeAppID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SageMaker App (%s): %w", d.Id(), err) } app, err := FindAppByName(conn, domainID, userProfileOrSpaceName, appType, appName) diff --git a/internal/service/sagemaker/device.go b/internal/service/sagemaker/device.go index 2d8d4882dac..a3850882575 100644 --- a/internal/service/sagemaker/device.go +++ b/internal/service/sagemaker/device.go @@ -96,7 +96,7 @@ func resourceDeviceRead(d *schema.ResourceData, meta interface{}) error { deviceFleetName, deviceName, err := DecodeDeviceId(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SageMaker Device (%s): %w", d.Id(), err) } device, err := FindDeviceByName(conn, deviceFleetName, deviceName) if !d.IsNewResource() && tfresource.NotFound(err) { @@ -126,7 +126,7 @@ func resourceDeviceUpdate(d *schema.ResourceData, meta interface{}) error { deviceFleetName, _, err := DecodeDeviceId(d.Id()) if err != nil { - return err + return fmt.Errorf("updating SageMaker Device (%s): %w", d.Id(), err) } input := &sagemaker.UpdateDevicesInput{ @@ -134,10 +134,10 @@ func resourceDeviceUpdate(d *schema.ResourceData, meta interface{}) error { Devices: expandDevice(d.Get("device").([]interface{})), } - log.Printf("[DEBUG] sagemaker Device update config: %s", input.String()) + log.Printf("[DEBUG] SageMaker Device update config: %s", input.String()) _, err = conn.UpdateDevices(input) if err != nil { - return fmt.Errorf("updating SageMaker Device: %w", err) + return fmt.Errorf("updating SageMaker Device (%s): %w", d.Id(), err) } return resourceDeviceRead(d, meta) @@ -148,7 +148,7 @@ func resourceDeviceDelete(d *schema.ResourceData, meta interface{}) error { deviceFleetName, deviceName, err := DecodeDeviceId(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting SageMaker Device (%s): %w", d.Id(), err) } input := &sagemaker.DeregisterDevicesInput{ diff --git a/internal/service/sagemaker/domain.go b/internal/service/sagemaker/domain.go index 1f5c0e5b57b..1efe2d2d698 100644 --- a/internal/service/sagemaker/domain.go +++ b/internal/service/sagemaker/domain.go @@ -618,22 +618,22 @@ func resourceDomainCreate(d *schema.ResourceData, meta interface{}) error { input.Tags = Tags(tags.IgnoreAWS()) } - log.Printf("[DEBUG] sagemaker domain create config: %#v", *input) + log.Printf("[DEBUG] SageMaker Domain create config: %#v", *input) output, err := conn.CreateDomain(input) if err != nil { - return fmt.Errorf("creating SageMaker domain: %w", err) + return fmt.Errorf("creating SageMaker Domain: %w", err) } domainArn := aws.StringValue(output.DomainArn) domainID, err := DecodeDomainID(domainArn) if err != nil { - return err + return fmt.Errorf("creating SageMaker Domain (%s): %w", d.Id(), err) } d.SetId(domainID) if _, err := WaitDomainInService(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for SageMaker domain (%s) to create: %w", d.Id(), err) + return fmt.Errorf("creating SageMaker Domain (%s): waiting for completion: %w", d.Id(), err) } return resourceDomainRead(d, meta) @@ -723,14 +723,14 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { input.DefaultSpaceSettings = expanDefaultSpaceSettings(v.([]interface{})) } - log.Printf("[DEBUG] sagemaker domain update config: %#v", *input) + log.Printf("[DEBUG] SageMaker Domain update config: %#v", *input) _, err := conn.UpdateDomain(input) if err != nil { - return fmt.Errorf("updating SageMaker domain: %w", err) + return fmt.Errorf("updating SageMaker Domain: %w", err) } if _, err := WaitDomainInService(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for SageMaker domain (%s) to update: %w", d.Id(), err) + return fmt.Errorf("waiting for SageMaker Domain (%s) to update: %w", d.Id(), err) } } @@ -738,7 +738,7 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("updating SageMaker domain (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating SageMaker Domain (%s) tags: %w", d.Id(), err) } } @@ -758,13 +758,13 @@ func resourceDomainDelete(d *schema.ResourceData, meta interface{}) error { if _, err := conn.DeleteDomain(input); err != nil { if !tfawserr.ErrCodeEquals(err, sagemaker.ErrCodeResourceNotFound) { - return fmt.Errorf("deleting SageMaker domain (%s): %w", d.Id(), err) + return fmt.Errorf("deleting SageMaker Domain (%s): %w", d.Id(), err) } } if _, err := WaitDomainDeleted(conn, d.Id()); err != nil { if !tfawserr.ErrCodeEquals(err, sagemaker.ErrCodeResourceNotFound) { - return fmt.Errorf("waiting for SageMaker domain (%s) to delete: %w", d.Id(), err) + return fmt.Errorf("waiting for SageMaker Domain (%s) to delete: %w", d.Id(), err) } } diff --git a/internal/service/sagemaker/model_package_group_policy.go b/internal/service/sagemaker/model_package_group_policy.go index 2d634bcf1ff..8201a2a199e 100644 --- a/internal/service/sagemaker/model_package_group_policy.go +++ b/internal/service/sagemaker/model_package_group_policy.go @@ -88,7 +88,7 @@ func resourceModelPackageGroupPolicyRead(d *schema.ResourceData, meta interface{ policyToSet, err := verify.PolicyToSet(d.Get("resource_policy").(string), aws.StringValue(mpg.ResourcePolicy)) if err != nil { - return err + return fmt.Errorf("reading SageMaker Model Package Group Policy (%s): %w", d.Id(), err) } d.Set("resource_policy", policyToSet) diff --git a/internal/service/sagemaker/notebook_instance.go b/internal/service/sagemaker/notebook_instance.go index 15c7b66b368..d01cba4525b 100644 --- a/internal/service/sagemaker/notebook_instance.go +++ b/internal/service/sagemaker/notebook_instance.go @@ -357,14 +357,14 @@ func resourceNotebookInstanceUpdate(d *schema.ResourceData, meta interface{}) er notebook, err := FindNotebookInstanceByName(conn, d.Id()) if err != nil { - return fmt.Errorf("reading SageMaker Notebook Instance (%s): %w", d.Id(), err) + return fmt.Errorf("updating SageMaker Notebook Instance (%s): %w", d.Id(), err) } previousStatus := aws.StringValue(notebook.NotebookInstanceStatus) if previousStatus != sagemaker.NotebookInstanceStatusStopped { if err := StopNotebookInstance(conn, d.Id()); err != nil { - return err + return fmt.Errorf("updating SageMaker Notebook Instance (%s): %w", d.Id(), err) } } @@ -378,49 +378,8 @@ func resourceNotebookInstanceUpdate(d *schema.ResourceData, meta interface{}) er // Restart if needed if previousStatus == sagemaker.NotebookInstanceStatusInService { - startOpts := &sagemaker.StartNotebookInstanceInput{ - NotebookInstanceName: aws.String(d.Id()), - } - stateConf := &resource.StateChangeConf{ - Pending: []string{ - sagemaker.NotebookInstanceStatusStopped, - }, - Target: []string{ - sagemaker.NotebookInstanceStatusInService, - sagemaker.NotebookInstanceStatusPending, - }, - Refresh: StatusNotebookInstance(conn, d.Id()), - Timeout: 30 * time.Second, - } - // StartNotebookInstance sometimes doesn't take so we'll check for a state change and if - // it doesn't change we'll send another request - err := resource.Retry(5*time.Minute, func() *resource.RetryError { - _, err := conn.StartNotebookInstance(startOpts) - if err != nil { - return resource.NonRetryableError(fmt.Errorf("starting sagemaker notebook instance (%s): %s", d.Id(), err)) - } - - _, err = stateConf.WaitForState() - if err != nil { - return resource.RetryableError(fmt.Errorf("waiting for sagemaker notebook instance (%s) to start: %s", d.Id(), err)) - } - - return nil - }) - if tfresource.TimedOut(err) { - _, err = conn.StartNotebookInstance(startOpts) - if err != nil { - return fmt.Errorf("starting sagemaker notebook instance (%s): %s", d.Id(), err) - } - - _, err = stateConf.WaitForState() - } - if err != nil { - return fmt.Errorf("Error waiting for sagemaker notebook instance to start: %s", err) - } - - if _, err := WaitNotebookInstanceInService(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for sagemaker notebook instance (%s) to start after update: %w", d.Id(), err) + if err := StartNotebookInstance(conn, d.Id()); err != nil { + return fmt.Errorf("updating SageMaker Notebook Instance (%s): %w", d.Id(), err) } } } @@ -443,7 +402,7 @@ func resourceNotebookInstanceDelete(d *schema.ResourceData, meta interface{}) er if status := aws.StringValue(notebook.NotebookInstanceStatus); status != sagemaker.NotebookInstanceStatusFailed && status != sagemaker.NotebookInstanceStatusStopped { if err := StopNotebookInstance(conn, d.Id()); err != nil { - return err + return fmt.Errorf("deleting SageMaker Notebook Instance (%s): %w", d.Id(), err) } } @@ -463,6 +422,43 @@ func resourceNotebookInstanceDelete(d *schema.ResourceData, meta interface{}) er return nil } +func StartNotebookInstance(conn *sagemaker.SageMaker, id string) error { + startOpts := &sagemaker.StartNotebookInstanceInput{ + NotebookInstanceName: aws.String(id), + } + // StartNotebookInstance sometimes doesn't take so we'll check for a state change and if + // it doesn't change we'll send another request + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + _, err := conn.StartNotebookInstance(startOpts) + if err != nil { + return resource.NonRetryableError(fmt.Errorf("starting: %s", err)) + } + + _, err = WaitNotebookInstanceStarted(conn, id) + if err != nil { + return resource.RetryableError(fmt.Errorf("starting: waiting for completion: %s", err)) + } + + return nil + }) + if tfresource.TimedOut(err) { + _, err = conn.StartNotebookInstance(startOpts) + if err != nil { + return fmt.Errorf("starting: %s", err) + } + + _, err = WaitNotebookInstanceStarted(conn, id) + if err != nil { + return fmt.Errorf("starting: waiting for completion: %s", err) + } + } + + if _, err := WaitNotebookInstanceInService(conn, id); err != nil { + return fmt.Errorf("starting: waiting to be in service: %s", err) + } + return nil +} + func StopNotebookInstance(conn *sagemaker.SageMaker, id string) error { notebook, err := FindNotebookInstanceByName(conn, id) @@ -470,7 +466,7 @@ func StopNotebookInstance(conn *sagemaker.SageMaker, id string) error { if tfresource.NotFound(err) { return nil } - return fmt.Errorf("reading SageMaker Notebook Instance (%s): %w", id, err) + return err } if aws.StringValue(notebook.NotebookInstanceStatus) == sagemaker.NotebookInstanceStatusStopped { @@ -482,11 +478,11 @@ func StopNotebookInstance(conn *sagemaker.SageMaker, id string) error { } if _, err := conn.StopNotebookInstance(stopOpts); err != nil { - return fmt.Errorf("Error stopping sagemaker notebook instance: %s", err) + return fmt.Errorf("stopping: %s", err) } if _, err := WaitNotebookInstanceStopped(conn, id); err != nil { - return fmt.Errorf("waiting for sagemaker notebook instance (%s) to stop: %w", id, err) + return fmt.Errorf("stopping: waiting for completion: %s", err) } return nil diff --git a/internal/service/sagemaker/space.go b/internal/service/sagemaker/space.go index 05592741b0a..e4d21df7fb5 100644 --- a/internal/service/sagemaker/space.go +++ b/internal/service/sagemaker/space.go @@ -236,7 +236,7 @@ func resourceSpaceRead(d *schema.ResourceData, meta interface{}) error { domainID, name, err := decodeSpaceName(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SageMaker Space (%s): %w", d.Id(), err) } Space, err := FindSpaceByName(conn, domainID, name) diff --git a/internal/service/sagemaker/user_profile.go b/internal/service/sagemaker/user_profile.go index b815d9339b4..309e1b32106 100644 --- a/internal/service/sagemaker/user_profile.go +++ b/internal/service/sagemaker/user_profile.go @@ -400,13 +400,13 @@ func resourceUserProfileCreate(d *schema.ResourceData, meta interface{}) error { userProfileArn := aws.StringValue(output.UserProfileArn) domainID, userProfileName, err := decodeUserProfileName(userProfileArn) if err != nil { - return err + return fmt.Errorf("creating SageMaker User Profile: %w", err) } d.SetId(userProfileArn) if _, err := WaitUserProfileInService(conn, domainID, userProfileName); err != nil { - return fmt.Errorf("waiting for SageMaker User Profile (%s) to create: %w", d.Id(), err) + return fmt.Errorf("creating SageMaker User Profile (%s): waiting for completion: %w", d.Id(), err) } return resourceUserProfileRead(d, meta) @@ -419,7 +419,7 @@ func resourceUserProfileRead(d *schema.ResourceData, meta interface{}) error { domainID, userProfileName, err := decodeUserProfileName(d.Id()) if err != nil { - return err + return fmt.Errorf("reading SageMaker User Profile (%s): %w", d.Id(), err) } userProfile, err := FindUserProfileByName(conn, domainID, userProfileName) diff --git a/internal/service/sagemaker/wait.go b/internal/service/sagemaker/wait.go index 44b69453b29..f5bf72b9eea 100644 --- a/internal/service/sagemaker/wait.go +++ b/internal/service/sagemaker/wait.go @@ -65,6 +65,32 @@ func WaitNotebookInstanceInService(conn *sagemaker.SageMaker, notebookName strin return nil, err } +func WaitNotebookInstanceStarted(conn *sagemaker.SageMaker, notebookName string) (*sagemaker.DescribeNotebookInstanceOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + sagemaker.NotebookInstanceStatusStopped, + }, + Target: []string{ + sagemaker.NotebookInstanceStatusInService, + sagemaker.NotebookInstanceStatusPending, + }, + Refresh: StatusNotebookInstance(conn, notebookName), + Timeout: 30 * time.Second, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*sagemaker.DescribeNotebookInstanceOutput); ok { + if status := aws.StringValue(output.NotebookInstanceStatus); status == sagemaker.NotebookInstanceStatusFailed { + tfresource.SetLastError(err, errors.New(aws.StringValue(output.FailureReason))) + } + + return output, err + } + + return nil, err +} + // WaitNotebookInstanceStopped waits for a NotebookInstance to return Stopped func WaitNotebookInstanceStopped(conn *sagemaker.SageMaker, notebookName string) (*sagemaker.DescribeNotebookInstanceOutput, error) { stateConf := &resource.StateChangeConf{ From 592d3f785afcf8a37bec83122e5ebffe6ab0d4ea Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 11:51:32 -0800 Subject: [PATCH 022/106] Fixes bare errors in `s3` --- internal/service/s3/bucket.go | 20 +++++++------------ .../s3/bucket_analytics_configuration.go | 6 +++--- internal/service/s3/bucket_data_source.go | 2 +- ...ucket_intelligent_tiering_configuration.go | 8 ++++---- internal/service/s3/bucket_inventory.go | 6 +++--- internal/service/s3/bucket_metric.go | 12 +++++------ internal/service/s3/bucket_policy.go | 8 +++----- .../s3/canonical_user_id_data_source.go | 2 +- 8 files changed, 28 insertions(+), 36 deletions(-) diff --git a/internal/service/s3/bucket.go b/internal/service/s3/bucket.go index 4d815e2e2ef..ce6445cb758 100644 --- a/internal/service/s3/bucket.go +++ b/internal/service/s3/bucket.go @@ -1087,7 +1087,7 @@ func resourceBucketRead(d *schema.ResourceData, meta interface{}) error { if ws, ok := wsResponse.(*s3.GetBucketWebsiteOutput); ok { website, err := flattenBucketWebsite(ws) if err != nil { - return err + return fmt.Errorf("setting website: %w", err) } if err := d.Set("website", website); err != nil { return fmt.Errorf("setting website: %w", err) @@ -1358,14 +1358,12 @@ func resourceBucketRead(d *schema.ResourceData, meta interface{}) error { } region := discoveredRegion.(string) - if err := d.Set("region", region); err != nil { - return err - } + d.Set("region", region) // Add the bucket_regional_domain_name as an attribute regionalEndpoint, err := BucketRegionalDomainName(d.Get("bucket").(string), region) if err != nil { - return err + return fmt.Errorf("getting S3 Bucket regional domain name: %s", err) } d.Set("bucket_regional_domain_name", regionalEndpoint) @@ -1388,17 +1386,13 @@ func resourceBucketRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - if err != nil { - return err + return fmt.Errorf("reading S3 Bucket (%s): %w", d.Id(), err) } + if websiteEndpoint != nil { - if err := d.Set("website_endpoint", websiteEndpoint.Endpoint); err != nil { - return err - } - if err := d.Set("website_domain", websiteEndpoint.Domain); err != nil { - return err - } + d.Set("website_endpoint", websiteEndpoint.Endpoint) + d.Set("website_domain", websiteEndpoint.Domain) } // Retry due to S3 eventual consistency diff --git a/internal/service/s3/bucket_analytics_configuration.go b/internal/service/s3/bucket_analytics_configuration.go index cb02b10967f..7b654998057 100644 --- a/internal/service/s3/bucket_analytics_configuration.go +++ b/internal/service/s3/bucket_analytics_configuration.go @@ -178,7 +178,7 @@ func resourceBucketAnalyticsConfigurationRead(d *schema.ResourceData, meta inter bucket, name, err := BucketAnalyticsConfigurationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading S3 Bucket Analytics Configuration (%s): %w", d.Id(), err) } d.Set("bucket", bucket) @@ -228,7 +228,7 @@ func resourceBucketAnalyticsConfigurationDelete(d *schema.ResourceData, meta int bucket, name, err := BucketAnalyticsConfigurationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting S3 analytics configuration (%s): %w", d.Id(), err) } input := &s3.DeleteBucketAnalyticsConfigurationInput{ @@ -242,7 +242,7 @@ func resourceBucketAnalyticsConfigurationDelete(d *schema.ResourceData, meta int if tfawserr.ErrCodeEquals(err, s3.ErrCodeNoSuchBucket) || tfawserr.ErrMessageContains(err, "NoSuchConfiguration", "The specified configuration does not exist.") { return nil } - return fmt.Errorf("Error deleting S3 analytics configuration: %w", err) + return fmt.Errorf("deleting S3 analytics configuration (%s): %w", d.Id(), err) } return WaitForDeleteBucketAnalyticsConfiguration(conn, bucket, name, 1*time.Minute) diff --git a/internal/service/s3/bucket_data_source.go b/internal/service/s3/bucket_data_source.go index 281c7abae09..46033b0da98 100644 --- a/internal/service/s3/bucket_data_source.go +++ b/internal/service/s3/bucket_data_source.go @@ -87,7 +87,7 @@ func dataSourceBucketRead(d *schema.ResourceData, meta interface{}) error { regionalDomainName, err := BucketRegionalDomainName(bucket, d.Get("region").(string)) if err != nil { - return err + return fmt.Errorf("getting S3 Bucket regional domain name: %w", err) } d.Set("bucket_regional_domain_name", regionalDomainName) diff --git a/internal/service/s3/bucket_intelligent_tiering_configuration.go b/internal/service/s3/bucket_intelligent_tiering_configuration.go index 297f96dc2b3..f21c3d52bf6 100644 --- a/internal/service/s3/bucket_intelligent_tiering_configuration.go +++ b/internal/service/s3/bucket_intelligent_tiering_configuration.go @@ -130,7 +130,7 @@ func resourceBucketIntelligentTieringConfigurationRead(d *schema.ResourceData, m bucketName, configurationName, err := BucketIntelligentTieringConfigurationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading S3 Intelligent-Tiering Configuration (%s): %w", d.Id(), err) } output, err := FindBucketIntelligentTieringConfiguration(conn, bucketName, configurationName) @@ -142,7 +142,7 @@ func resourceBucketIntelligentTieringConfigurationRead(d *schema.ResourceData, m } if err != nil { - return fmt.Errorf("error reading S3 Intelligent-Tiering Configuration (%s): %w", d.Id(), err) + return fmt.Errorf("reading S3 Intelligent-Tiering Configuration (%s): %w", d.Id(), err) } d.Set("bucket", bucketName) @@ -168,7 +168,7 @@ func resourceBucketIntelligentTieringConfigurationDelete(d *schema.ResourceData, bucketName, configurationName, err := BucketIntelligentTieringConfigurationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting S3 Intelligent-Tiering Configuration (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting S3 Intelligent-Tiering Configuration: (%s)", d.Id()) @@ -182,7 +182,7 @@ func resourceBucketIntelligentTieringConfigurationDelete(d *schema.ResourceData, } if err != nil { - return fmt.Errorf("error deleting S3 Intelligent-Tiering Configuration (%s): %w", d.Id(), err) + return fmt.Errorf("deleting S3 Intelligent-Tiering Configuration (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/s3/bucket_inventory.go b/internal/service/s3/bucket_inventory.go index 817df0668d8..861deca7fef 100644 --- a/internal/service/s3/bucket_inventory.go +++ b/internal/service/s3/bucket_inventory.go @@ -256,7 +256,7 @@ func resourceBucketInventoryDelete(d *schema.ResourceData, meta interface{}) err bucket, name, err := BucketInventoryParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting S3 Bucket Inventory Configuration (%s): %w", d.Id(), err) } input := &s3.DeleteBucketInventoryConfigurationInput{ @@ -276,7 +276,7 @@ func resourceBucketInventoryDelete(d *schema.ResourceData, meta interface{}) err } if err != nil { - return fmt.Errorf("error deleting S3 Bucket Inventory Configuration (%s): %w", d.Id(), err) + return fmt.Errorf("deleting S3 Bucket Inventory Configuration (%s): %w", d.Id(), err) } return nil @@ -287,7 +287,7 @@ func resourceBucketInventoryRead(d *schema.ResourceData, meta interface{}) error bucket, name, err := BucketInventoryParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading S3 Bucket Inventory Configuration (%s): %w", d.Id(), err) } d.Set("bucket", bucket) diff --git a/internal/service/s3/bucket_metric.go b/internal/service/s3/bucket_metric.go index b9539de85be..66c7f940834 100644 --- a/internal/service/s3/bucket_metric.go +++ b/internal/service/s3/bucket_metric.go @@ -117,7 +117,7 @@ func resourceBucketMetricDelete(d *schema.ResourceData, meta interface{}) error bucket, name, err := BucketMetricParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting S3 Bucket Metrics Configuration (%s): %w", d.Id(), err) } input := &s3.DeleteBucketMetricsConfigurationInput{ @@ -137,7 +137,7 @@ func resourceBucketMetricDelete(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error deleting S3 Bucket Metrics Configuration (%s): %w", d.Id(), err) + return fmt.Errorf("deleting S3 Bucket Metrics Configuration (%s): %w", d.Id(), err) } return nil @@ -148,7 +148,7 @@ func resourceBucketMetricRead(d *schema.ResourceData, meta interface{}) error { bucket, name, err := BucketMetricParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading S3 Bucket Metrics Configuration (%s): %w", d.Id(), err) } d.Set("bucket", bucket) @@ -175,16 +175,16 @@ func resourceBucketMetricRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading S3 Bucket Metrics Configuration (%s): %w", d.Id(), err) + return fmt.Errorf("reading S3 Bucket Metrics Configuration (%s): %w", d.Id(), err) } if output == nil || output.MetricsConfiguration == nil { - return fmt.Errorf("error reading S3 Bucket Metrics Configuration (%s): empty response", d.Id()) + return fmt.Errorf("reading S3 Bucket Metrics Configuration (%s): empty response", d.Id()) } if output.MetricsConfiguration.Filter != nil { if err := d.Set("filter", []interface{}{FlattenMetricsFilter(output.MetricsConfiguration.Filter)}); err != nil { - return err + return fmt.Errorf("setting filter") } } diff --git a/internal/service/s3/bucket_policy.go b/internal/service/s3/bucket_policy.go index 5fb5b336b74..347e2b09c6e 100644 --- a/internal/service/s3/bucket_policy.go +++ b/internal/service/s3/bucket_policy.go @@ -115,16 +115,14 @@ func resourceBucketPolicyRead(d *schema.ResourceData, meta interface{}) error { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(pol.Policy)) if err != nil { - return fmt.Errorf("while setting policy (%s), encountered: %w", policyToSet, err) + return fmt.Errorf("setting policy: %w", err) } if err := d.Set("policy", policyToSet); err != nil { - return err + return fmt.Errorf("setting policy: %w", err) } - if err := d.Set("bucket", d.Id()); err != nil { - return err - } + d.Set("bucket", d.Id()) return nil } diff --git a/internal/service/s3/canonical_user_id_data_source.go b/internal/service/s3/canonical_user_id_data_source.go index 1a77506f3d6..95a00c15bd0 100644 --- a/internal/service/s3/canonical_user_id_data_source.go +++ b/internal/service/s3/canonical_user_id_data_source.go @@ -31,7 +31,7 @@ func dataSourceCanonicalUserIDRead(d *schema.ResourceData, meta interface{}) err req := &s3.ListBucketsInput{} resp, err := conn.ListBuckets(req) if err != nil { - return err + return fmt.Errorf("listing S3 Buckets: %w", err) } if resp == nil || resp.Owner == nil { return fmt.Errorf("no canonical user ID found") From 58ea7ca055c24e62663d4ed3433d6a2afeabfe43 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 11:51:53 -0800 Subject: [PATCH 023/106] Fixes bare errors in `route53` --- internal/service/route53/delegation_set.go | 12 +++------- internal/service/route53/record.go | 22 +++++++++++-------- .../route53/vpc_association_authorization.go | 7 +++--- internal/service/route53/zone.go | 6 ++--- internal/service/route53/zone_association.go | 8 +++---- 5 files changed, 26 insertions(+), 29 deletions(-) diff --git a/internal/service/route53/delegation_set.go b/internal/service/route53/delegation_set.go index 65498cf1268..ed2191bcfcd 100644 --- a/internal/service/route53/delegation_set.go +++ b/internal/service/route53/delegation_set.go @@ -2,7 +2,6 @@ package route53 import ( "fmt" - "log" "strings" "github.com/aws/aws-sdk-go/aws" @@ -58,12 +57,10 @@ func resourceDelegationSetCreate(d *schema.ResourceData, meta interface{}) error CallerReference: aws.String(callerRef), } - log.Printf("[DEBUG] Creating Route53 reusable delegation set: %#v", input) out, err := r53.CreateReusableDelegationSet(input) if err != nil { - return err + return fmt.Errorf("creating Route 53 Reusable Delegation Set: %w", err) } - log.Printf("[DEBUG] Route53 reusable delegation set created: %#v", out) set := out.DelegationSet d.SetId(CleanDelegationSetID(*set.Id)) @@ -77,16 +74,14 @@ func resourceDelegationSetRead(d *schema.ResourceData, meta interface{}) error { input := &route53.GetReusableDelegationSetInput{ Id: aws.String(CleanDelegationSetID(d.Id())), } - log.Printf("[DEBUG] Reading Route53 reusable delegation set: %#v", input) out, err := r53.GetReusableDelegationSet(input) if err != nil { if tfawserr.ErrCodeEquals(err, route53.ErrCodeNoSuchDelegationSet) { d.SetId("") return nil } - return err + return fmt.Errorf("reading Route 53 Reusable Delegation Set: %w", err) } - log.Printf("[DEBUG] Route53 reusable delegation set received: %#v", out) set := out.DelegationSet d.Set("name_servers", aws.StringValueSlice(set.NameServers)) @@ -107,14 +102,13 @@ func resourceDelegationSetDelete(d *schema.ResourceData, meta interface{}) error input := &route53.DeleteReusableDelegationSetInput{ Id: aws.String(CleanDelegationSetID(d.Id())), } - log.Printf("[DEBUG] Deleting Route53 reusable delegation set: %#v", input) _, err := r53.DeleteReusableDelegationSet(input) if tfawserr.ErrCodeEquals(err, route53.ErrCodeNoSuchDelegationSet) { return nil } if err != nil { - return fmt.Errorf("deleting Route53 reusable delegation set (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Route53 Reusable Delegation Set (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/route53/record.go b/internal/service/route53/record.go index 346d4799f49..b947bbac96e 100644 --- a/internal/service/route53/record.go +++ b/internal/service/route53/record.go @@ -474,7 +474,7 @@ func resourceRecordCreate(d *schema.ResourceData, meta interface{}) error { respRaw, err := ChangeRecordSet(conn, req) if err != nil { - return fmt.Errorf("[ERR]: Error building changeset: %w", err) + return fmt.Errorf("creating Route 53 Record (%s): updating record set: %w", d.Id(), err) } changeInfo := respRaw.(*route53.ChangeResourceRecordSetsOutput).ChangeInfo @@ -493,11 +493,13 @@ func resourceRecordCreate(d *schema.ResourceData, meta interface{}) error { err = WaitForRecordSetToSync(conn, CleanChangeID(aws.StringValue(changeInfo.Id))) if err != nil { - return err + return fmt.Errorf("creating Route 53 Record (%s): updating record set: wating for completion: %w", d.Id(), err) } - _, err = findRecord(d, meta) - return err + if _, err := findRecord(d, meta); err != nil { + return fmt.Errorf("creating Route 53 Record (%s): %w", d.Id(), err) + } + return nil } func ChangeRecordSet(conn *route53.Route53, input *route53.ChangeResourceRecordSetsInput) (interface{}, error) { @@ -568,7 +570,7 @@ func resourceRecordRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil default: - return err + return fmt.Errorf("reading Route 53 Record (%s): %w", d.Id(), err) } } @@ -765,7 +767,7 @@ func resourceRecordDelete(d *schema.ResourceData, meta interface{}) error { case errNoHostedZoneFound, errNoRecordsFound: return nil default: - return err + return fmt.Errorf("deleting Route 53 Record (%s): %w", d.Id(), err) } } @@ -789,7 +791,7 @@ func resourceRecordDelete(d *schema.ResourceData, meta interface{}) error { respRaw, err := DeleteRecordSet(conn, req) if err != nil { - return fmt.Errorf("[ERR]: Error building changeset: %w", err) + return fmt.Errorf("deleting Route 53 Record (%s): deleting record set: %w", d.Id(), err) } changeInfo := respRaw.(*route53.ChangeResourceRecordSetsOutput).ChangeInfo @@ -798,8 +800,10 @@ func resourceRecordDelete(d *schema.ResourceData, meta interface{}) error { return nil } - err = WaitForRecordSetToSync(conn, CleanChangeID(aws.StringValue(changeInfo.Id))) - return err + if err := WaitForRecordSetToSync(conn, CleanChangeID(aws.StringValue(changeInfo.Id))); err != nil { + return fmt.Errorf("deleting Route 53 Record (%s): deleting record set: waiting for completion: %w", d.Id(), err) + } + return nil } func DeleteRecordSet(conn *route53.Route53, input *route53.ChangeResourceRecordSetsInput) (interface{}, error) { diff --git a/internal/service/route53/vpc_association_authorization.go b/internal/service/route53/vpc_association_authorization.go index 2ddea42c106..fa1f735538d 100644 --- a/internal/service/route53/vpc_association_authorization.go +++ b/internal/service/route53/vpc_association_authorization.go @@ -76,7 +76,7 @@ func resourceVPCAssociationAuthorizationRead(d *schema.ResourceData, meta interf zone_id, vpc_id, err := VPCAssociationAuthorizationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Route53 VPC Association Authorization (%s): %s", d.Id(), err) } req := route53.ListVPCAssociationAuthorizationsInput{ @@ -125,7 +125,7 @@ func resourceVPCAssociationAuthorizationDelete(d *schema.ResourceData, meta inte zone_id, vpc_id, err := VPCAssociationAuthorizationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Route53 VPC Association Authorization (%s): %s", d.Id(), err) } req := route53.DeleteVPCAssociationAuthorizationInput{ @@ -136,10 +136,9 @@ func resourceVPCAssociationAuthorizationDelete(d *schema.ResourceData, meta inte }, } - log.Printf("[DEBUG] Deleting Route53 Assocatiation Authorization for hosted zone %s for VPC %s", zone_id, vpc_id) _, err = conn.DeleteVPCAssociationAuthorization(&req) if err != nil { - return fmt.Errorf("Error deleting Route53 VPC Association Authorization: %s", err) + return fmt.Errorf("deleting Route53 VPC Association Authorization (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/route53/zone.go b/internal/service/route53/zone.go index 5d847f7f195..c936a6fe9c4 100644 --- a/internal/service/route53/zone.go +++ b/internal/service/route53/zone.go @@ -169,7 +169,7 @@ func resourceZoneCreate(d *schema.ResourceData, meta interface{}) error { err := hostedZoneVPCAssociate(conn, d.Id(), vpc) if err != nil { - return err + return fmt.Errorf("creating Route53 Hosted Zone (%s): associating VPC (%s) %s", d.Id(), aws.StringValue(vpc.VPCId), err) } } } @@ -302,7 +302,7 @@ func resourceZoneUpdate(d *schema.ResourceData, meta interface{}) error { err := hostedZoneVPCAssociate(conn, d.Id(), vpc) if err != nil { - return err + return fmt.Errorf("updating Route53 Hosted Zone (%s): associating VPC (%s) %s", d.Id(), aws.StringValue(vpc.VPCId), err) } } @@ -315,7 +315,7 @@ func resourceZoneUpdate(d *schema.ResourceData, meta interface{}) error { err := hostedZoneVPCDisassociate(conn, d.Id(), vpc) if err != nil { - return err + return fmt.Errorf("updating Route53 Hosted Zone (%s): disassociating VPC (%s) %s", d.Id(), aws.StringValue(vpc.VPCId), err) } } } diff --git a/internal/service/route53/zone_association.go b/internal/service/route53/zone_association.go index ec67c3f6c21..053844b94cf 100644 --- a/internal/service/route53/zone_association.go +++ b/internal/service/route53/zone_association.go @@ -103,7 +103,7 @@ func resourceZoneAssociationRead(d *schema.ResourceData, meta interface{}) error zoneID, vpcID, vpcRegion, err := ZoneAssociationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Route 53 Zone Association (%s): %w", d.Id(), err) } // Continue supporting older resources without VPC Region in ID @@ -124,12 +124,12 @@ func resourceZoneAssociationRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("getting Route 53 Zone Association (%s): %w", d.Id(), err) + return fmt.Errorf("reading Route 53 Zone Association (%s): %w", d.Id(), err) } if hostedZoneSummary == nil { if d.IsNewResource() { - return fmt.Errorf("getting Route 53 Zone Association (%s): missing after creation", d.Id()) + return fmt.Errorf("reading Route 53 Zone Association (%s): missing after creation", d.Id()) } log.Printf("[WARN] Route 53 Hosted Zone (%s) Association (%s) not found, removing from state", zoneID, vpcID) @@ -151,7 +151,7 @@ func resourceZoneAssociationDelete(d *schema.ResourceData, meta interface{}) err zoneID, vpcID, vpcRegion, err := ZoneAssociationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Route 53 Hosted Zone Association (%s): %w", zoneID, err) } // Continue supporting older resources without VPC Region in ID From 4bf93e0b70fd73d09b27e469c28d8097920522a3 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 12:13:22 -0800 Subject: [PATCH 024/106] Fixes bare errors in `redshiftserverless` --- internal/service/redshiftserverless/endpoint_access.go | 4 ++-- internal/service/redshiftserverless/workgroup.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/service/redshiftserverless/endpoint_access.go b/internal/service/redshiftserverless/endpoint_access.go index bf43e4d6d5f..cbc4c02cdb7 100644 --- a/internal/service/redshiftserverless/endpoint_access.go +++ b/internal/service/redshiftserverless/endpoint_access.go @@ -212,11 +212,11 @@ func resourceEndpointAccessDelete(d *schema.ResourceData, meta interface{}) erro if tfawserr.ErrCodeEquals(err, redshiftserverless.ErrCodeResourceNotFoundException) { return nil } - return err + return fmt.Errorf("deleting Redshift Serverless Endpoint Access (%s): %w", d.Id(), err) } if _, err := waitEndpointAccessDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for Redshift Serverless Endpoint Access (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting Redshift Serverless Endpoint Access (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/redshiftserverless/workgroup.go b/internal/service/redshiftserverless/workgroup.go index 873fe7d4e9c..ef144384532 100644 --- a/internal/service/redshiftserverless/workgroup.go +++ b/internal/service/redshiftserverless/workgroup.go @@ -336,11 +336,11 @@ func resourceWorkgroupDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, redshiftserverless.ErrCodeResourceNotFoundException) { return nil } - return err + return fmt.Errorf("deleting Redshift Serverless Workgroup (%s): %w", d.Id(), err) } if _, err := waitWorkgroupDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for Redshift Serverless Workgroup (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting Redshift Serverless Workgroup (%s): waiting for completion: %w", d.Id(), err) } return nil From 6ff207a108317e980bc3e245bcb62d2e28e67662 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:15:34 -0800 Subject: [PATCH 025/106] Fixes bare errors in `redshift` --- .../redshift/authentication_profile.go | 4 +- internal/service/redshift/cluster.go | 84 +++++++++++-------- .../service/redshift/cluster_data_source.go | 2 +- internal/service/redshift/endpoint_access.go | 4 +- .../redshift/endpoint_authorization.go | 10 +-- .../redshift/hsm_client_certificate.go | 14 ++-- internal/service/redshift/parameter_group.go | 6 +- internal/service/redshift/partner.go | 2 +- internal/service/redshift/security_group.go | 37 +++++--- .../service/redshift/snapshot_copy_grant.go | 11 +-- .../service/redshift/snapshot_schedule.go | 8 +- .../redshift/snapshot_schedule_association.go | 10 +-- internal/service/redshift/usage_limit.go | 7 +- 13 files changed, 111 insertions(+), 88 deletions(-) diff --git a/internal/service/redshift/authentication_profile.go b/internal/service/redshift/authentication_profile.go index f53e33c034e..46384968539 100644 --- a/internal/service/redshift/authentication_profile.go +++ b/internal/service/redshift/authentication_profile.go @@ -118,8 +118,8 @@ func resourceAuthenticationProfileDelete(d *schema.ResourceData, meta interface{ if tfawserr.ErrCodeEquals(err, redshift.ErrCodeAuthenticationProfileNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting Redshift Authentication Profile (%s): %w", d.Id(), err) } - return err + return nil } diff --git a/internal/service/redshift/cluster.go b/internal/service/redshift/cluster.go index c4444d87cc0..d08ae96e986 100644 --- a/internal/service/redshift/cluster.go +++ b/internal/service/redshift/cluster.go @@ -541,16 +541,16 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { } if _, err := waitClusterCreated(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("waiting for Redshift Cluster (%s) create: %w", d.Id(), err) + return fmt.Errorf("creating Redshift Cluster (%s): waiting for completion: %w", d.Id(), err) } if _, err := waitClusterRelocationStatusResolved(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for Redshift Cluster (%s) Availability Zone Relocation Status resolution: %w", d.Id(), err) + return fmt.Errorf("creating Redshift Cluster (%s): waiting for relocation: %w", d.Id(), err) } if v, ok := d.GetOk("snapshot_copy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { if err := enableSnapshotCopy(conn, d.Id(), v.([]interface{})[0].(map[string]interface{})); err != nil { - return err + return fmt.Errorf("creating Redshift Cluster (%s): %w", d.Id(), err) } } @@ -558,10 +558,8 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { tfMap := v.([]interface{})[0].(map[string]interface{}) if v, ok := tfMap["enable"].(bool); ok && v { - err := enableLogging(conn, d.Id(), tfMap) - - if err != nil { - return err + if err := enableLogging(conn, d.Id(), tfMap); err != nil { + return fmt.Errorf("creating Redshift Cluster (%s): %w", d.Id(), err) } } } @@ -610,7 +608,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { d.Set("availability_zone", rsc.AvailabilityZone) azr, err := clusterAvailabilityZoneRelocationStatus(rsc) if err != nil { - return err + return fmt.Errorf("reading Redshift Cluster (%s): %w", d.Id(), err) } d.Set("availability_zone_relocation_enabled", azr) d.Set("cluster_identifier", rsc.ClusterIdentifier) @@ -886,18 +884,12 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("snapshot_copy") { if v, ok := d.GetOk("snapshot_copy"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - err := enableSnapshotCopy(conn, d.Id(), v.([]interface{})[0].(map[string]interface{})) - - if err != nil { - return err + if err := enableSnapshotCopy(conn, d.Id(), v.([]interface{})[0].(map[string]interface{})); err != nil { + return fmt.Errorf("updating Redshift Cluster (%s): %w", d.Id(), err) } } else { - _, err := conn.DisableSnapshotCopy(&redshift.DisableSnapshotCopyInput{ - ClusterIdentifier: aws.String(d.Id()), - }) - - if err != nil { - return fmt.Errorf("disabling Redshift Cluster (%s) snapshot copy: %w", d.Id(), err) + if err := disableSnapshotCopy(conn, d.Id()); err != nil { + return fmt.Errorf("updating Redshift Cluster (%s): %w", d.Id(), err) } } } @@ -907,24 +899,12 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { tfMap := v.([]interface{})[0].(map[string]interface{}) if v, ok := tfMap["enable"].(bool); ok && v { - err := enableLogging(conn, d.Id(), tfMap) - - if err != nil { - return err + if err := enableLogging(conn, d.Id(), tfMap); err != nil { + return fmt.Errorf("updating Redshift Cluster (%s): %w", d.Id(), err) } } else { - _, err := tfresource.RetryWhenAWSErrCodeEquals( - clusterInvalidClusterStateFaultTimeout, - func() (interface{}, error) { - return conn.DisableLogging(&redshift.DisableLoggingInput{ - ClusterIdentifier: aws.String(d.Id()), - }) - }, - redshift.ErrCodeInvalidClusterStateFault, - ) - - if err != nil { - return fmt.Errorf("disabling Redshift Cluster (%s) logging: %w", d.Id(), err) + if err := disableLogging(conn, d.Id()); err != nil { + return fmt.Errorf("updating Redshift Cluster (%s): %w", d.Id(), err) } } } @@ -1021,7 +1001,27 @@ func enableLogging(conn *redshift.Redshift, clusterID string, tfMap map[string]i ) if err != nil { - return fmt.Errorf("enabling Redshift Cluster (%s) logging: %w", clusterID, err) + return fmt.Errorf("enabling logging: %w", err) + } + + return nil +} + +func disableLogging(conn *redshift.Redshift, clusterID string) error { + input := &redshift.DisableLoggingInput{ + ClusterIdentifier: aws.String(clusterID), + } + + _, err := tfresource.RetryWhenAWSErrCodeEquals( + clusterInvalidClusterStateFaultTimeout, + func() (interface{}, error) { + return conn.DisableLogging(input) + }, + redshift.ErrCodeInvalidClusterStateFault, + ) + + if err != nil { + return fmt.Errorf("disabling logging: %w", err) } return nil @@ -1042,9 +1042,21 @@ func enableSnapshotCopy(conn *redshift.Redshift, clusterID string, tfMap map[str } _, err := conn.EnableSnapshotCopy(input) + if err != nil { + return fmt.Errorf("enabling snapshot copy: %w", err) + } + + return nil +} + +func disableSnapshotCopy(conn *redshift.Redshift, clusterID string) error { + input := &redshift.DisableSnapshotCopyInput{ + ClusterIdentifier: aws.String(clusterID), + } + _, err := conn.DisableSnapshotCopy(input) if err != nil { - return fmt.Errorf("enabling Redshift Cluster (%s) snapshot copy: %w", clusterID, err) + return fmt.Errorf("disabling snapshot copy: %w", err) } return nil diff --git a/internal/service/redshift/cluster_data_source.go b/internal/service/redshift/cluster_data_source.go index 64c78c9bf9e..89ab2ea3a45 100644 --- a/internal/service/redshift/cluster_data_source.go +++ b/internal/service/redshift/cluster_data_source.go @@ -222,7 +222,7 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { d.Set("availability_zone", rsc.AvailabilityZone) azr, err := clusterAvailabilityZoneRelocationStatus(rsc) if err != nil { - return err + return fmt.Errorf("reading Redshift Cluster (%s): %w", clusterID, err) } d.Set("availability_zone_relocation_enabled", azr) d.Set("cluster_identifier", rsc.ClusterIdentifier) diff --git a/internal/service/redshift/endpoint_access.go b/internal/service/redshift/endpoint_access.go index b5a85132ffc..c8c59cace5f 100644 --- a/internal/service/redshift/endpoint_access.go +++ b/internal/service/redshift/endpoint_access.go @@ -217,11 +217,11 @@ func resourceEndpointAccessDelete(d *schema.ResourceData, meta interface{}) erro if tfawserr.ErrCodeEquals(err, redshift.ErrCodeEndpointNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting Redshift Endpoint Access (%s): %w", d.Id(), err) } if _, err := waitEndpointAccessDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for Redshift Endpoint Access (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting Redshift Endpoint Access (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/redshift/endpoint_authorization.go b/internal/service/redshift/endpoint_authorization.go index 8aeac107be3..fb1bc678f30 100644 --- a/internal/service/redshift/endpoint_authorization.go +++ b/internal/service/redshift/endpoint_authorization.go @@ -123,7 +123,7 @@ func resourceEndpointAuthorizationUpdate(d *schema.ResourceData, meta interface{ if d.HasChanges("vpc_ids") { account, clusterId, err := DecodeEndpointAuthorizationID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Redshift Endpoint Authorization (%s): %w", d.Id(), err) } o, n := d.GetChange("vpc_ids") @@ -140,7 +140,7 @@ func resourceEndpointAuthorizationUpdate(d *schema.ResourceData, meta interface{ }) if err != nil { - return fmt.Errorf("authorizing Redshift Endpoint Authorization VPCs (%s): %w", d.Id(), err) + return fmt.Errorf("updating Redshift Endpoint Authorization (%s): authorizing VPCs: %w", d.Id(), err) } } @@ -152,7 +152,7 @@ func resourceEndpointAuthorizationUpdate(d *schema.ResourceData, meta interface{ }) if err != nil { - return fmt.Errorf("revoking Redshift Endpoint Authorization VPCs (%s): %w", d.Id(), err) + return fmt.Errorf("updating Redshift Endpoint Authorization (%s): revoking VPCs: %w", d.Id(), err) } } } @@ -165,7 +165,7 @@ func resourceEndpointAuthorizationDelete(d *schema.ResourceData, meta interface{ account, clusterId, err := DecodeEndpointAuthorizationID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Redshift Endpoint Authorization (%s): %w", d.Id(), err) } input := &redshift.RevokeEndpointAccessInput{ @@ -180,7 +180,7 @@ func resourceEndpointAuthorizationDelete(d *schema.ResourceData, meta interface{ if tfawserr.ErrCodeEquals(err, redshift.ErrCodeEndpointAuthorizationNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting Redshift Endpoint Authorization (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/redshift/hsm_client_certificate.go b/internal/service/redshift/hsm_client_certificate.go index 7a72c3d8480..f8fb61ad535 100644 --- a/internal/service/redshift/hsm_client_certificate.go +++ b/internal/service/redshift/hsm_client_certificate.go @@ -63,7 +63,7 @@ func resourceHSMClientCertificateCreate(d *schema.ResourceData, meta interface{} out, err := conn.CreateHsmClientCertificate(&input) if err != nil { - return fmt.Errorf("creating Redshift Hsm Client Certificate (%s): %s", certIdentifier, err) + return fmt.Errorf("creating Redshift HSM Client Certificate (%s): %s", certIdentifier, err) } d.SetId(aws.StringValue(out.HsmClientCertificate.HsmClientCertificateIdentifier)) @@ -78,13 +78,13 @@ func resourceHSMClientCertificateRead(d *schema.ResourceData, meta interface{}) out, err := FindHSMClientCertificateByID(conn, d.Id()) if !d.IsNewResource() && tfresource.NotFound(err) { - log.Printf("[WARN] Redshift Hsm Client Certificate (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] Redshift HSM Client Certificate (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("reading Redshift Hsm Client Certificate (%s): %w", d.Id(), err) + return fmt.Errorf("reading Redshift HSM Client Certificate (%s): %w", d.Id(), err) } arn := arn.ARN{ @@ -121,7 +121,7 @@ func resourceHSMClientCertificateUpdate(d *schema.ResourceData, meta interface{} o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("updating Redshift Hsm Client Certificate (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating Redshift HSM Client Certificate (%s) tags: %s", d.Get("arn").(string), err) } } @@ -135,15 +135,15 @@ func resourceHSMClientCertificateDelete(d *schema.ResourceData, meta interface{} HsmClientCertificateIdentifier: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting Redshift Hsm Client Certificate: %s", d.Id()) + log.Printf("[DEBUG] Deleting Redshift HSM Client Certificate: %s", d.Id()) _, err := conn.DeleteHsmClientCertificate(&deleteInput) if err != nil { if tfawserr.ErrCodeEquals(err, redshift.ErrCodeHsmClientCertificateNotFoundFault) { return nil } - return err + return fmt.Errorf("updating Redshift HSM Client Certificate (%s) tags: %s", d.Get("arn").(string), err) } - return err + return nil } diff --git a/internal/service/redshift/parameter_group.go b/internal/service/redshift/parameter_group.go index aa020e02d16..5110fadd08a 100644 --- a/internal/service/redshift/parameter_group.go +++ b/internal/service/redshift/parameter_group.go @@ -134,7 +134,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error describeResp, err := conn.DescribeClusterParameterGroups(&describeOpts) if err != nil { - return err + return fmt.Errorf("reading Redshift Parameter Group (%s): %w", d.Id(), err) } if len(describeResp.ParameterGroups) != 1 || @@ -174,7 +174,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error describeParametersResp, err := conn.DescribeClusterParameters(&describeParametersOpts) if err != nil { - return err + return fmt.Errorf("reading Redshift Parameter Group (%s): %w", d.Id(), err) } d.Set("parameter", FlattenParameters(describeParametersResp.Parameters)) @@ -233,7 +233,7 @@ func resourceParameterGroupDelete(d *schema.ResourceData, meta interface{}) erro if err != nil && tfawserr.ErrCodeEquals(err, "RedshiftParameterGroupNotFoundFault") { return nil } - return err + return fmt.Errorf("deleting Redshift Parameter Group (%s): %w", d.Id(), err) } func resourceParameterHash(v interface{}) int { diff --git a/internal/service/redshift/partner.go b/internal/service/redshift/partner.go index 8f9c98c8d25..301b948d5c1 100644 --- a/internal/service/redshift/partner.go +++ b/internal/service/redshift/partner.go @@ -110,7 +110,7 @@ func resourcePartnerDelete(d *schema.ResourceData, meta interface{}) error { account, clusterId, dbName, partnerName, err := DecodePartnerID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Redshift Partner (%s): %w", d.Id(), err) } deleteInput := redshift.DeletePartnerInput{ diff --git a/internal/service/redshift/security_group.go b/internal/service/redshift/security_group.go index 79027e4ee3a..0a67665b604 100644 --- a/internal/service/redshift/security_group.go +++ b/internal/service/redshift/security_group.go @@ -10,10 +10,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/hashicorp/terraform-provider-aws/internal/conns" "github.com/hashicorp/terraform-provider-aws/internal/create" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func ResourceSecurityGroup() *schema.Resource { @@ -83,7 +85,7 @@ func resourceSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error func resourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { sg, err := resourceSecurityGroupRetrieve(d, meta) if err != nil { - return err + return fmt.Errorf("reading Redshift Security Group (%s): %w", d.Id(), err) } rules := &schema.Set{ @@ -132,7 +134,7 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error _, err := conn.RevokeClusterSecurityGroupIngress(&r) if err != nil { - return err + return fmt.Errorf("updating Redshift Security Group (%s): revoking ingress: %w", d.Id(), err) } } } @@ -144,7 +146,7 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error _, err := conn.AuthorizeClusterSecurityGroupIngress(&r) if err != nil { - return err + return fmt.Errorf("updating Redshift Security Group (%s): authorizing ingress: %w", d.Id(), err) } } } @@ -160,7 +162,6 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error ClusterSecurityGroupName: aws.String(d.Id()), } - log.Printf("[DEBUG] Redshift Security Group destroy configuration: %v", opts) _, err := conn.DeleteClusterSecurityGroup(&opts) if err != nil { @@ -168,7 +169,7 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error if ok && newerr.Code() == "InvalidRedshiftSecurityGroup.NotFound" { return nil } - return err + return fmt.Errorf("deleting Redshift Security Group (%s): %w", d.Id(), err) } return nil @@ -181,20 +182,30 @@ func resourceSecurityGroupRetrieve(d *schema.ResourceData, meta interface{}) (*r ClusterSecurityGroupName: aws.String(d.Id()), } - log.Printf("[DEBUG] Redshift Security Group describe configuration: %#v", opts) - resp, err := conn.DescribeClusterSecurityGroups(&opts) - if err != nil { - return nil, fmt.Errorf("Error retrieving Redshift Security Groups: %s", err) + return nil, &resource.NotFoundError{ + LastError: err, + LastRequest: opts, + } + } + + if len(resp.ClusterSecurityGroups) == 0 || resp.ClusterSecurityGroups[0] == nil { + return nil, tfresource.NewEmptyResultError(opts) + } + + if l := len(resp.ClusterSecurityGroups); l > 1 { + return nil, tfresource.NewTooManyResultsError(l, opts) } - if len(resp.ClusterSecurityGroups) != 1 || - aws.StringValue(resp.ClusterSecurityGroups[0].ClusterSecurityGroupName) != d.Id() { - return nil, fmt.Errorf("Unable to find Redshift Security Group: %#v", resp.ClusterSecurityGroups) + result := resp.ClusterSecurityGroups[0] + if aws.StringValue(result.ClusterSecurityGroupName) != d.Id() { + return nil, &resource.NotFoundError{ + LastRequest: opts, + } } - return resp.ClusterSecurityGroups[0], nil + return result, nil } func resourceSecurityGroupIngressHash(v interface{}) int { diff --git a/internal/service/redshift/snapshot_copy_grant.go b/internal/service/redshift/snapshot_copy_grant.go index 52c365bf57d..5c720b2c86b 100644 --- a/internal/service/redshift/snapshot_copy_grant.go +++ b/internal/service/redshift/snapshot_copy_grant.go @@ -143,7 +143,7 @@ func resourceSnapshotCopyGrantUpdate(d *schema.ResourceData, meta interface{}) e o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("updating Redshift Snapshot Copy Grant (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating Redshift Snapshot Copy Grant (%s) tags: %s", d.Id(), err) } } @@ -166,13 +166,14 @@ func resourceSnapshotCopyGrantDelete(d *schema.ResourceData, meta interface{}) e if tfawserr.ErrCodeEquals(err, redshift.ErrCodeSnapshotCopyGrantNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting Redshift Snapshot Copy Grant (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Checking if grant is deleted: %s", grantName) - err = WaitForSnapshotCopyGrantToBeDeleted(conn, grantName) + if err := WaitForSnapshotCopyGrantToBeDeleted(conn, grantName); err != nil { + return fmt.Errorf("deleting Redshift Snapshot Copy Grant (%s): waiting for completion: %s", d.Id(), err) + } - return err + return nil } // Used by the tests as well diff --git a/internal/service/redshift/snapshot_schedule.go b/internal/service/redshift/snapshot_schedule.go index 80bb7fd48a0..1c0bb4344cc 100644 --- a/internal/service/redshift/snapshot_schedule.go +++ b/internal/service/redshift/snapshot_schedule.go @@ -183,7 +183,7 @@ func resourceSnapshotScheduleDelete(d *schema.ResourceData, meta interface{}) er if d.Get("force_destroy").(bool) { if err := resourceSnapshotScheduleDeleteAllAssociatedClusters(conn, d.Id()); err != nil { - return err + return fmt.Errorf("deleting Redshift Snapshot Schedule (%s): %s", d.Id(), err) } } @@ -194,7 +194,7 @@ func resourceSnapshotScheduleDelete(d *schema.ResourceData, meta interface{}) er return nil } if err != nil { - return fmt.Errorf("Error deleting Redshift Snapshot Schedule %s: %s", d.Id(), err) + return fmt.Errorf("deleting Redshift Snapshot Schedule (%s): %s", d.Id(), err) } return nil @@ -208,7 +208,7 @@ func resourceSnapshotScheduleDeleteAllAssociatedClusters(conn *redshift.Redshift return nil } if err != nil { - return fmt.Errorf("Error describing Redshift Cluster Snapshot Schedule %s: %s", scheduleIdentifier, err) + return err } if resp.SnapshotSchedules == nil || len(resp.SnapshotSchedules) != 1 { log.Printf("[WARN] Unable to find Redshift Cluster Snapshot Schedule (%s)", scheduleIdentifier) @@ -235,7 +235,7 @@ func resourceSnapshotScheduleDeleteAllAssociatedClusters(conn *redshift.Redshift continue } if err != nil { - return fmt.Errorf("Error disassociate Redshift Cluster (%s) and Snapshot Schedule (%s) Association: %s", clusterId, scheduleIdentifier, err) + return fmt.Errorf("disassociating Redshift Cluster (%s): %s", clusterId, err) } } diff --git a/internal/service/redshift/snapshot_schedule_association.go b/internal/service/redshift/snapshot_schedule_association.go index 4d6bf673ea3..f23eda17946 100644 --- a/internal/service/redshift/snapshot_schedule_association.go +++ b/internal/service/redshift/snapshot_schedule_association.go @@ -49,13 +49,13 @@ func resourceSnapshotScheduleAssociationCreate(d *schema.ResourceData, meta inte }) if err != nil { - return fmt.Errorf("Error associating Redshift Cluster (%s) and Snapshot Schedule (%s): %s", clusterIdentifier, scheduleIdentifier, err) + return fmt.Errorf("creating Redshift Cluster Snapshot Schedule (%s/%s): %w", clusterIdentifier, scheduleIdentifier, err) } d.SetId(fmt.Sprintf("%s/%s", clusterIdentifier, scheduleIdentifier)) if _, err := WaitScheduleAssociationActive(conn, d.Id()); err != nil { - return err + return fmt.Errorf("creating Redshift Cluster Snapshot Schedule (%s): waiting for completion: %w", d.Id(), err) } return resourceSnapshotScheduleAssociationRead(d, meta) @@ -85,7 +85,7 @@ func resourceSnapshotScheduleAssociationDelete(d *schema.ResourceData, meta inte conn := meta.(*conns.AWSClient).RedshiftConn() clusterIdentifier, scheduleIdentifier, err := SnapshotScheduleAssociationParseID(d.Id()) if err != nil { - return fmt.Errorf("Error parse Redshift Cluster Snapshot Schedule Association ID %s: %s", d.Id(), err) + return fmt.Errorf("deleting Redshift Cluster Snapshot Schedule (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting Redshift Cluster Snapshot Schedule Association: %s", d.Id()) @@ -100,11 +100,11 @@ func resourceSnapshotScheduleAssociationDelete(d *schema.ResourceData, meta inte } if err != nil { - return fmt.Errorf("Error disassociate Redshift Cluster (%s) and Snapshot Schedule (%s) Association: %s", clusterIdentifier, scheduleIdentifier, err) + return fmt.Errorf("deleting Redshift Cluster Snapshot Schedule (%s): %w", d.Id(), err) } if _, err := waitScheduleAssociationDeleted(conn, d.Id()); err != nil { - return err + return fmt.Errorf("deleting Redshift Cluster Snapshot Schedule (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/redshift/usage_limit.go b/internal/service/redshift/usage_limit.go index d4ed075eb2e..6433631cd23 100644 --- a/internal/service/redshift/usage_limit.go +++ b/internal/service/redshift/usage_limit.go @@ -181,7 +181,7 @@ func resourceUsageLimitUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("updating Redshift Usage Limit (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating Redshift Usage Limit (%s) tags: %s", d.Id(), err) } } @@ -195,15 +195,14 @@ func resourceUsageLimitDelete(d *schema.ResourceData, meta interface{}) error { UsageLimitId: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting snapshot copy grant: %s", d.Id()) _, err := conn.DeleteUsageLimit(&deleteInput) if err != nil { if tfawserr.ErrCodeEquals(err, redshift.ErrCodeUsageLimitNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting Redshift Usage Limit (%s): %s", d.Id(), err) } - return err + return nil } From afe3427f2af1a905166afb72399d5a59ebbf5e30 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:15:50 -0800 Subject: [PATCH 026/106] Fixes bare errors in `rds` --- internal/service/rds/cluster_endpoint.go | 8 ++++---- internal/service/rds/cluster_parameter_group.go | 4 ++-- internal/service/rds/cluster_snapshot_data_source.go | 2 +- internal/service/rds/global_cluster.go | 6 +++--- .../rds/instance_automated_backups_replication.go | 8 ++++---- internal/service/rds/parameter_group.go | 4 ++-- internal/service/rds/proxy_target.go | 2 +- internal/service/rds/security_group.go | 11 +++++------ internal/service/rds/snapshot.go | 5 ++--- internal/service/rds/snapshot_data_source.go | 3 +-- 10 files changed, 25 insertions(+), 28 deletions(-) diff --git a/internal/service/rds/cluster_endpoint.go b/internal/service/rds/cluster_endpoint.go index af3d6ac1f81..e0967f66f4f 100644 --- a/internal/service/rds/cluster_endpoint.go +++ b/internal/service/rds/cluster_endpoint.go @@ -109,14 +109,14 @@ func resourceClusterEndpointCreate(d *schema.ResourceData, meta interface{}) err _, err := conn.CreateDBClusterEndpoint(createClusterEndpointInput) if err != nil { - return fmt.Errorf("Error creating RDS Cluster Endpoint: %s", err) + return fmt.Errorf("creating RDS Cluster Endpoint: %s", err) } d.SetId(endpointId) err = resourceClusterEndpointWaitForAvailable(clusterEndpointCreateTimeout, d.Id(), conn) if err != nil { - return err + return fmt.Errorf("creating RDS Cluster Endpoint: waiting for completion: %s", err) } return resourceClusterEndpointRead(d, meta) @@ -235,11 +235,11 @@ func resourceClusterEndpointDelete(d *schema.ResourceData, meta interface{}) err } _, err := conn.DeleteDBClusterEndpoint(input) if err != nil { - return fmt.Errorf("Error deleting RDS Cluster Endpoint: %s", err) + return fmt.Errorf("deleting RDS Cluster Endpoint (%s): %s", d.Id(), err) } if err := resourceClusterEndpointWaitForDestroy(d.Timeout(schema.TimeoutDelete), d.Id(), conn); err != nil { - return err + return fmt.Errorf("deleting RDS Cluster Endpoint (%s): waiting for completion: %s", d.Id(), err) } return nil diff --git a/internal/service/rds/cluster_parameter_group.go b/internal/service/rds/cluster_parameter_group.go index 0a214578504..9bbd1f698ae 100644 --- a/internal/service/rds/cluster_parameter_group.go +++ b/internal/service/rds/cluster_parameter_group.go @@ -138,12 +138,12 @@ func resourceClusterParameterGroupRead(d *schema.ResourceData, meta interface{}) describeResp, err := conn.DescribeDBClusterParameterGroups(&describeOpts) if err != nil { if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "DBParameterGroupNotFound" { - log.Printf("[WARN] DB Cluster Parameter Group (%s) not found, error code (404)", d.Id()) + log.Printf("[WARN] DB Cluster Parameter Group (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading RDS Cluster Parameter Group (%s): %s", d.Id(), err) } if len(describeResp.DBClusterParameterGroups) != 1 || diff --git a/internal/service/rds/cluster_snapshot_data_source.go b/internal/service/rds/cluster_snapshot_data_source.go index a2dd9431e7a..8aef1e7a8c4 100644 --- a/internal/service/rds/cluster_snapshot_data_source.go +++ b/internal/service/rds/cluster_snapshot_data_source.go @@ -140,7 +140,7 @@ func dataSourceClusterSnapshotRead(d *schema.ResourceData, meta interface{}) err log.Printf("[DEBUG] Reading DB Cluster Snapshot: %s", params) resp, err := conn.DescribeDBClusterSnapshots(params) if err != nil { - return err + return fmt.Errorf("reading RDS Cluster Snapshot (%s): %s", d.Id(), err) } if len(resp.DBClusterSnapshots) < 1 { diff --git a/internal/service/rds/global_cluster.go b/internal/service/rds/global_cluster.go index 557e13a2072..5e5b0c03d98 100644 --- a/internal/service/rds/global_cluster.go +++ b/internal/service/rds/global_cluster.go @@ -242,7 +242,7 @@ func resourceGlobalClusterUpdate(d *schema.ResourceData, meta interface{}) error if d.HasChange("engine_version") { if err := globalClusterUpgradeEngineVersion(d, meta, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating RDS Global Cluster (%s): %s", d.Id(), err) } } @@ -254,11 +254,11 @@ func resourceGlobalClusterUpdate(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error deleting RDS Global Cluster: %s", err) + return fmt.Errorf("updating RDS Global Cluster (%s): %s", d.Id(), err) } if err := waitForGlobalClusterUpdate(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for RDS Global Cluster (%s) update: %s", d.Id(), err) + return fmt.Errorf("updating RDS Global Cluster (%s): waiting for completion: %s", d.Id(), err) } return resourceGlobalClusterRead(d, meta) diff --git a/internal/service/rds/instance_automated_backups_replication.go b/internal/service/rds/instance_automated_backups_replication.go index 685860b4ca1..5b8833d088b 100644 --- a/internal/service/rds/instance_automated_backups_replication.go +++ b/internal/service/rds/instance_automated_backups_replication.go @@ -130,14 +130,14 @@ func resourceInstanceAutomatedBackupsReplicationDelete(d *schema.ResourceData, m } if err != nil { - return fmt.Errorf("error reading RDS instance automated backup (%s): %w", d.Id(), err) + return fmt.Errorf("deleting RDS DB Instance Automated Backup (%s): %w", d.Id(), err) } dbInstanceID := aws.StringValue(backup.DBInstanceIdentifier) sourceDatabaseARN, err := arn.Parse(aws.StringValue(backup.DBInstanceArn)) if err != nil { - return err + return fmt.Errorf("deleting RDS DB Instance Automated Backup (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Stopping RDS Instance Automated Backups Replication: %s", d.Id()) @@ -150,7 +150,7 @@ func resourceInstanceAutomatedBackupsReplicationDelete(d *schema.ResourceData, m } if err != nil { - return fmt.Errorf("stopping RDS Instance Automated Backups Replication (%s): %w", d.Id(), err) + return fmt.Errorf("deleting RDS DB Instance Automated Backup (%s): %w", d.Id(), err) } // Create a new client to the source region. @@ -160,7 +160,7 @@ func resourceInstanceAutomatedBackupsReplicationDelete(d *schema.ResourceData, m } if _, err := waitDBInstanceAutomatedBackupDeleted(ctx, sourceDatabaseConn, dbInstanceID, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("error waiting for DB instance automated backup (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting RDS DB Instance Automated Backup (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/rds/parameter_group.go b/internal/service/rds/parameter_group.go index 341131a911f..17f02b1df07 100644 --- a/internal/service/rds/parameter_group.go +++ b/internal/service/rds/parameter_group.go @@ -148,7 +148,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error d.SetId("") return nil } - return err + return fmt.Errorf("reading RDS DB Parameter Group (%s): %w", d.Id(), err) } if len(describeResp.DBParameterGroups) != 1 || @@ -184,7 +184,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error return !lastPage }) if err != nil { - return err + return fmt.Errorf("reading RDS DB Parameter Group (%s): %w", d.Id(), err) } var userParams []*rds.Parameter diff --git a/internal/service/rds/proxy_target.go b/internal/service/rds/proxy_target.go index 6e69d8d0a68..3ec93303a5d 100644 --- a/internal/service/rds/proxy_target.go +++ b/internal/service/rds/proxy_target.go @@ -133,7 +133,7 @@ func resourceProxyTargetRead(d *schema.ResourceData, meta interface{}) error { dbProxyName, targetGroupName, targetType, rdsResourceId, err := ProxyTargetParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading RDS Proxy Target (%s): %w", d.Id(), err) } dbProxyTarget, err := FindDBProxyTarget(conn, dbProxyName, targetGroupName, targetType, rdsResourceId) diff --git a/internal/service/rds/security_group.go b/internal/service/rds/security_group.go index b8021a24031..f3091957068 100644 --- a/internal/service/rds/security_group.go +++ b/internal/service/rds/security_group.go @@ -97,7 +97,7 @@ func resourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { sg, err := resourceSecurityGroupRetrieve(d, meta) if err != nil { - return err + return fmt.Errorf("reading RDS DB Security Group (%s): %s", d.Id(), err) } d.Set("name", sg.DBSecurityGroupName) @@ -168,7 +168,7 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error if d.HasChange("ingress") { sg, err := resourceSecurityGroupRetrieve(d, meta) if err != nil { - return err + return fmt.Errorf("updating RDS DB Security Group (%s): %s", d.Id(), err) } oi, ni := d.GetChange("ingress") @@ -188,7 +188,7 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error for _, ing := range removeIngress { err := resourceSecurityGroupRevokeRule(ing, *sg.DBSecurityGroupName, conn) if err != nil { - return err + return fmt.Errorf("updating RDS DB Security Group (%s): revoking ingress: %s", d.Id(), err) } } @@ -196,7 +196,7 @@ func resourceSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error for _, ing := range newIngress { err := resourceSecurityGroupAuthorizeRule(ing, *sg.DBSecurityGroupName, conn) if err != nil { - return err + return fmt.Errorf("updating RDS DB Security Group (%s): authorizing ingress: %s", d.Id(), err) } } } @@ -211,14 +211,13 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error opts := rds.DeleteDBSecurityGroupInput{DBSecurityGroupName: aws.String(d.Id())} - log.Printf("[DEBUG] DB Security Group destroy configuration: %v", opts) _, err := conn.DeleteDBSecurityGroup(&opts) if err != nil { if tfawserr.ErrCodeEquals(err, "InvalidDBSecurityGroup.NotFound") { return nil } - return err + return fmt.Errorf("deleting RDS DB Security Group (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/rds/snapshot.go b/internal/service/rds/snapshot.go index 2e07e415037..a37a5c09f22 100644 --- a/internal/service/rds/snapshot.go +++ b/internal/service/rds/snapshot.go @@ -131,7 +131,7 @@ func resourceSnapshotCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateDBSnapshot(params) if err != nil { - return fmt.Errorf("Error creating AWS DB Snapshot %s: %s", dBInstanceIdentifier, err) + return fmt.Errorf("creating AWS DB Snapshot (%s): %s", dBInstanceIdentifier, err) } d.SetId(aws.StringValue(resp.DBSnapshot.DBSnapshotIdentifier)) @@ -144,10 +144,9 @@ func resourceSnapshotCreate(d *schema.ResourceData, meta interface{}) error { Delay: 30 * time.Second, // Wait 30 secs before starting } - // Wait, catching any errors _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("creating AWS DB Snapshot (%s): waiting for completion: %s", dBInstanceIdentifier, err) } return resourceSnapshotRead(d, meta) diff --git a/internal/service/rds/snapshot_data_source.go b/internal/service/rds/snapshot_data_source.go index e296a786d0b..c965cd03356 100644 --- a/internal/service/rds/snapshot_data_source.go +++ b/internal/service/rds/snapshot_data_source.go @@ -147,10 +147,9 @@ func dataSourceSnapshotRead(d *schema.ResourceData, meta interface{}) error { params.DBSnapshotIdentifier = aws.String(snapshotIdentifier.(string)) } - log.Printf("[DEBUG] Reading DB Snapshot: %s", params) resp, err := conn.DescribeDBSnapshots(params) if err != nil { - return err + return fmt.Errorf("reading RDS Snapshot: %w", err) } if len(resp.DBSnapshots) < 1 { From c1bed80c06f3f4457151a2b86557822d620b0b02 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:16:00 -0800 Subject: [PATCH 027/106] Fixes bare errors in `ram` --- internal/service/ram/principal_association.go | 6 +++--- internal/service/ram/resource_association.go | 10 +++++----- internal/service/ram/resource_share_accepter.go | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/service/ram/principal_association.go b/internal/service/ram/principal_association.go index 237577f3e97..d60d75765b4 100644 --- a/internal/service/ram/principal_association.go +++ b/internal/service/ram/principal_association.go @@ -127,7 +127,7 @@ func resourcePrincipalAssociationDelete(d *schema.ResourceData, meta interface{} resourceShareArn, principal, err := PrincipalAssociationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting RAM Resource Share Principal Association (%s): %s", d.Id(), err) } request := &ram.DisassociateResourceShareInput{ @@ -143,11 +143,11 @@ func resourcePrincipalAssociationDelete(d *schema.ResourceData, meta interface{} } if err != nil { - return fmt.Errorf("error disassociating RAM Resource Share (%s) Principal Association (%s): %s", resourceShareArn, principal, err) + return fmt.Errorf("deleting RAM Resource Share Principal Association (%s): %s", d.Id(), err) } if _, err := WaitResourceSharePrincipalDisassociated(conn, resourceShareArn, principal); err != nil { - return fmt.Errorf("error waiting for RAM Resource Share (%s) Principal Association (%s) disassociation: %s", resourceShareArn, principal, err) + return fmt.Errorf("deleting RAM Resource Share Principal Association (%s): waiting for completion: %s", d.Id(), err) } return nil diff --git a/internal/service/ram/resource_association.go b/internal/service/ram/resource_association.go index 2cb9c9a40ed..533b806614a 100644 --- a/internal/service/ram/resource_association.go +++ b/internal/service/ram/resource_association.go @@ -72,7 +72,7 @@ func resourceResourceAssociationRead(d *schema.ResourceData, meta interface{}) e resourceShareARN, resourceARN, err := DecodeResourceAssociationID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading RAM Resource Share Resource Association (%s): %w", d.Id(), err) } resourceShareAssociation, err := GetResourceShareAssociation(conn, resourceShareARN, resourceARN) @@ -82,7 +82,7 @@ func resourceResourceAssociationRead(d *schema.ResourceData, meta interface{}) e return nil } if err != nil { - return fmt.Errorf("error reading RAM Resource Share (%s) Resource Association (%s): %w", resourceShareARN, resourceARN, err) + return fmt.Errorf("reading RAM Resource Share Resource Association (%s): %w", d.Id(), err) } if !d.IsNewResource() && aws.StringValue(resourceShareAssociation.Status) != ram.ResourceShareAssociationStatusAssociated { @@ -102,7 +102,7 @@ func resourceResourceAssociationDelete(d *schema.ResourceData, meta interface{}) resourceShareARN, resourceARN, err := DecodeResourceAssociationID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting RAM Resource Share Resource Association (%s): %w", d.Id(), err) } input := &ram.DisassociateResourceShareInput{ @@ -118,11 +118,11 @@ func resourceResourceAssociationDelete(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error disassociating RAM Resource Share (%s) Resource Association (%s): %s", resourceShareARN, resourceARN, err) + return fmt.Errorf("deleting RAM Resource Share Resource Association (%s): %w", d.Id(), err) } if err := WaitForResourceShareResourceDisassociation(conn, resourceShareARN, resourceARN); err != nil { - return fmt.Errorf("error waiting for RAM Resource Share (%s) Resource Association (%s) disassociation: %s", resourceShareARN, resourceARN, err) + return fmt.Errorf("deleting RAM Resource Share Resource Association (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ram/resource_share_accepter.go b/internal/service/ram/resource_share_accepter.go index 4a86124cc9f..e6f2340c622 100644 --- a/internal/service/ram/resource_share_accepter.go +++ b/internal/service/ram/resource_share_accepter.go @@ -88,7 +88,7 @@ func resourceResourceShareAccepterCreate(d *schema.ResourceData, meta interface{ invitation, err := FindResourceShareInvitationByResourceShareARNAndStatus(conn, shareARN, ram.ResourceShareInvitationStatusPending) if err != nil { - return err + return fmt.Errorf("creating RAM Resource Share Accepter: %w", err) } if invitation == nil || aws.StringValue(invitation.ResourceShareInvitationArn) == "" { From c9d0b506d288b61c301ad288801813645723ddb5 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:16:16 -0800 Subject: [PATCH 028/106] Fixes bare errors in `quicksight` --- internal/service/quicksight/group.go | 8 ++++---- internal/service/quicksight/user.go | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/service/quicksight/group.go b/internal/service/quicksight/group.go index 83e19013dbe..758d5a2c8b2 100644 --- a/internal/service/quicksight/group.go +++ b/internal/service/quicksight/group.go @@ -96,7 +96,7 @@ func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { awsAccountID, namespace, groupName, err := GroupParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading QuickSight Group (%s): %s", d.Id(), err) } descOpts := &quicksight.DescribeGroupInput{ @@ -112,7 +112,7 @@ func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error describing QuickSight Group (%s): %s", d.Id(), err) + return fmt.Errorf("reading QuickSight Group (%s): %s", d.Id(), err) } d.Set("arn", resp.Group.Arn) @@ -129,7 +129,7 @@ func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { awsAccountID, namespace, groupName, err := GroupParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating QuickSight Group (%s): %s", d.Id(), err) } updateOpts := &quicksight.UpdateGroupInput{ @@ -155,7 +155,7 @@ func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { awsAccountID, namespace, groupName, err := GroupParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting QuickSight Group (%s): %s", d.Id(), err) } deleteOpts := &quicksight.DeleteGroupInput{ diff --git a/internal/service/quicksight/user.go b/internal/service/quicksight/user.go index 1ec4b8536a9..5368f354572 100644 --- a/internal/service/quicksight/user.go +++ b/internal/service/quicksight/user.go @@ -139,7 +139,7 @@ func resourceUserRead(d *schema.ResourceData, meta interface{}) error { awsAccountID, namespace, userName, err := UserParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading QuickSight User (%s): %s", d.Id(), err) } descOpts := &quicksight.DescribeUserInput{ @@ -155,7 +155,7 @@ func resourceUserRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error describing QuickSight User (%s): %s", d.Id(), err) + return fmt.Errorf("reading QuickSight User (%s): %s", d.Id(), err) } d.Set("arn", resp.User.Arn) @@ -173,7 +173,7 @@ func resourceUserUpdate(d *schema.ResourceData, meta interface{}) error { awsAccountID, namespace, userName, err := UserParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating QuickSight User (%s): %s", d.Id(), err) } updateOpts := &quicksight.UpdateUserInput{ @@ -186,7 +186,7 @@ func resourceUserUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateUser(updateOpts) if err != nil { - return fmt.Errorf("Error updating QuickSight User %s: %s", d.Id(), err) + return fmt.Errorf("updating QuickSight User (%s): %s", d.Id(), err) } return resourceUserRead(d, meta) @@ -197,7 +197,7 @@ func resourceUserDelete(d *schema.ResourceData, meta interface{}) error { awsAccountID, namespace, userName, err := UserParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting QuickSight User (%s): %s", d.Id(), err) } deleteOpts := &quicksight.DeleteUserInput{ @@ -210,7 +210,7 @@ func resourceUserDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, quicksight.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("Error deleting QuickSight User %s: %s", d.Id(), err) + return fmt.Errorf("deleting QuickSight User (%s): %s", d.Id(), err) } return nil From b49e33312fd2da3a145c62ddfa5c89c78bdc97a1 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:16:34 -0800 Subject: [PATCH 029/106] Fixes bare errors in `pinpoint` --- internal/service/pinpoint/adm_channel.go | 4 ++-- internal/service/pinpoint/apns_channel.go | 2 +- internal/service/pinpoint/apns_sandbox_channel.go | 2 +- internal/service/pinpoint/apns_voip_channel.go | 2 +- .../service/pinpoint/apns_voip_sandbox_channel.go | 2 +- internal/service/pinpoint/app.go | 12 ++++++------ internal/service/pinpoint/baidu_channel.go | 2 +- internal/service/pinpoint/email_channel.go | 2 +- internal/service/pinpoint/event_stream.go | 2 +- internal/service/pinpoint/gcm_channel.go | 2 +- internal/service/pinpoint/sms_channel.go | 2 +- 11 files changed, 17 insertions(+), 17 deletions(-) diff --git a/internal/service/pinpoint/adm_channel.go b/internal/service/pinpoint/adm_channel.go index 6945da50038..ccb1754f3c1 100644 --- a/internal/service/pinpoint/adm_channel.go +++ b/internal/service/pinpoint/adm_channel.go @@ -64,7 +64,7 @@ func resourceADMChannelUpsert(d *schema.ResourceData, meta interface{}) error { _, err := conn.UpdateAdmChannel(&req) if err != nil { - return err + return fmt.Errorf("updating Pinpoint ADM Channel: %w", err) } d.SetId(applicationId) @@ -82,7 +82,7 @@ func resourceADMChannelRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint ADM Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint ADM Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/apns_channel.go b/internal/service/pinpoint/apns_channel.go index 0f20b6e99a3..0d04e6c3603 100644 --- a/internal/service/pinpoint/apns_channel.go +++ b/internal/service/pinpoint/apns_channel.go @@ -126,7 +126,7 @@ func resourceAPNSChannelRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint APNs Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint APNs Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/apns_sandbox_channel.go b/internal/service/pinpoint/apns_sandbox_channel.go index 6c83c811878..971c5a4dcf8 100644 --- a/internal/service/pinpoint/apns_sandbox_channel.go +++ b/internal/service/pinpoint/apns_sandbox_channel.go @@ -126,7 +126,7 @@ func resourceAPNSSandboxChannelRead(d *schema.ResourceData, meta interface{}) er }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint APNs Sandbox Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint APNs Sandbox Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/apns_voip_channel.go b/internal/service/pinpoint/apns_voip_channel.go index f95afedae09..a789997561a 100644 --- a/internal/service/pinpoint/apns_voip_channel.go +++ b/internal/service/pinpoint/apns_voip_channel.go @@ -126,7 +126,7 @@ func resourceAPNSVoIPChannelRead(d *schema.ResourceData, meta interface{}) error }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint APNs Voip Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint APNs Voip Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/apns_voip_sandbox_channel.go b/internal/service/pinpoint/apns_voip_sandbox_channel.go index 006a1defc30..5ee6ade9d44 100644 --- a/internal/service/pinpoint/apns_voip_sandbox_channel.go +++ b/internal/service/pinpoint/apns_voip_sandbox_channel.go @@ -126,7 +126,7 @@ func resourceAPNSVoIPSandboxChannelRead(d *schema.ResourceData, meta interface{} }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint APNs Voip Sandbox Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint APNs Voip Sandbox Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/app.go b/internal/service/pinpoint/app.go index 082f0bd8beb..6eba4eb439f 100644 --- a/internal/service/pinpoint/app.go +++ b/internal/service/pinpoint/app.go @@ -214,7 +214,7 @@ func resourceAppUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.UpdateApplicationSettings(&req) if err != nil { - return err + return fmt.Errorf("updating Pinpoint Application (%s): %s", d.Id(), err) } if !d.IsNewResource() { @@ -243,12 +243,12 @@ func resourceAppRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint App (%s) not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint App (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading Pinpoint Application (%s): %s", d.Id(), err) } settings, err := conn.GetApplicationSettings(&pinpoint.GetApplicationSettingsInput{ @@ -256,12 +256,12 @@ func resourceAppRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint App (%s) not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint App (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading Pinpoint Application (%s) settings: %s", d.Id(), err) } arn := aws.StringValue(app.ApplicationResponse.Arn) @@ -311,7 +311,7 @@ func resourceAppDelete(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("deleting Pinpoint Application (%s): %s", d.Id(), err) } func expandCampaignHook(configs []interface{}) *pinpoint.CampaignHook { diff --git a/internal/service/pinpoint/baidu_channel.go b/internal/service/pinpoint/baidu_channel.go index 56b8ced83d9..a259831c687 100644 --- a/internal/service/pinpoint/baidu_channel.go +++ b/internal/service/pinpoint/baidu_channel.go @@ -82,7 +82,7 @@ func resourceBaiduChannelRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint Baidu Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint Baidu Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/email_channel.go b/internal/service/pinpoint/email_channel.go index af80aa74b4d..d865b659bbb 100644 --- a/internal/service/pinpoint/email_channel.go +++ b/internal/service/pinpoint/email_channel.go @@ -103,7 +103,7 @@ func resourceEmailChannelRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint Email Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint Email Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/event_stream.go b/internal/service/pinpoint/event_stream.go index 5a52a6341fc..255c7361364 100644 --- a/internal/service/pinpoint/event_stream.go +++ b/internal/service/pinpoint/event_stream.go @@ -97,7 +97,7 @@ func resourceEventStreamRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint Event Stream for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint Event Stream for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/gcm_channel.go b/internal/service/pinpoint/gcm_channel.go index ddf9aaa142f..1213f6be506 100644 --- a/internal/service/pinpoint/gcm_channel.go +++ b/internal/service/pinpoint/gcm_channel.go @@ -76,7 +76,7 @@ func resourceGCMChannelRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint GCM Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint GCM Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } diff --git a/internal/service/pinpoint/sms_channel.go b/internal/service/pinpoint/sms_channel.go index 8002ed212c3..0509ea475b6 100644 --- a/internal/service/pinpoint/sms_channel.go +++ b/internal/service/pinpoint/sms_channel.go @@ -94,7 +94,7 @@ func resourceSMSChannelRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, pinpoint.ErrCodeNotFoundException) { - log.Printf("[WARN] Pinpoint SMS Channel for application %s not found, error code (404)", d.Id()) + log.Printf("[WARN] Pinpoint SMS Channel for application %s not found, removing from state", d.Id()) d.SetId("") return nil } From fe30bd69fecdcfc9cb714d09e58591bf34390dba Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:16:56 -0800 Subject: [PATCH 030/106] Fixes bare errors in `organizations` --- internal/service/organizations/policy_attachment.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/organizations/policy_attachment.go b/internal/service/organizations/policy_attachment.go index 58096081278..cbb630a3c50 100644 --- a/internal/service/organizations/policy_attachment.go +++ b/internal/service/organizations/policy_attachment.go @@ -68,7 +68,7 @@ func resourcePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) erro targetID, policyID, err := DecodePolicyAttachmentID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Organizations Policy Attachment (%s): %w", d.Id(), err) } _, err = FindPolicyAttachmentByTwoPartKey(conn, targetID, policyID) @@ -94,7 +94,7 @@ func resourcePolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) er targetID, policyID, err := DecodePolicyAttachmentID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Organizations Policy Attachment (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting Organizations Policy Attachment: %s", d.Id()) From ad7930bc035cf7599ddc4eb048b472b89f91c350 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:45:21 -0800 Subject: [PATCH 031/106] Fixes bare errors in `opsworks` --- internal/service/opsworks/application.go | 19 +++++----- internal/service/opsworks/instance.go | 48 ++++++++++++------------ internal/service/opsworks/permission.go | 5 ++- 3 files changed, 37 insertions(+), 35 deletions(-) diff --git a/internal/service/opsworks/application.go b/internal/service/opsworks/application.go index 6a51f4c6f34..f3d525ea036 100644 --- a/internal/service/opsworks/application.go +++ b/internal/service/opsworks/application.go @@ -273,7 +273,7 @@ func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("describing OpsWorks Application (%s): %w", d.Id(), err) + return fmt.Errorf("reading OpsWorks Application (%s): %w", d.Id(), err) } app := resp.Apps[0] @@ -287,11 +287,11 @@ func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { d.Set("enable_ssl", app.EnableSsl) err = resourceSetApplicationSSL(d, app.SslConfiguration) if err != nil { - return err + return fmt.Errorf("reading OpsWorks Application (%s): setting ssl_configuration: %w", d.Id(), err) } err = resourceSetApplicationSource(d, app.AppSource) if err != nil { - return err + return fmt.Errorf("reading OpsWorks Application (%s): setting app_source: %w", d.Id(), err) } resourceSetApplicationsDataSource(d, app.DataSources) resourceSetApplicationEnvironmentVariable(d, app.Environment) @@ -305,7 +305,7 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { err := resourceApplicationValidate(d) if err != nil { - return err + return fmt.Errorf("creating OpsWorks Application: %s", err) } req := &opsworks.CreateAppInput{ @@ -325,7 +325,7 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateApp(req) if err != nil { - return fmt.Errorf("Error creating OpsWorks application: %s", err) + return fmt.Errorf("creating OpsWorks Application: %s", err) } d.SetId(aws.StringValue(resp.AppId)) @@ -338,7 +338,7 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { err := resourceApplicationValidate(d) if err != nil { - return err + return fmt.Errorf("updating OpsWorks Application (%s): %s", d.Id(), err) } req := &opsworks.UpdateAppInput{ @@ -355,11 +355,11 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { Attributes: resourceApplicationAttributes(d), } - log.Printf("[DEBUG] Updating OpsWorks layer: %s", d.Id()) + log.Printf("[DEBUG] Updating OpsWorks Application: %s", d.Id()) _, err = conn.UpdateApp(req) if err != nil { - return fmt.Errorf("Error updating OpsWorks app: %s", err) + return fmt.Errorf("updating OpsWorks Application (%s): %s", d.Id(), err) } return resourceApplicationRead(d, meta) @@ -377,11 +377,10 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeleteApp(req) if tfawserr.ErrCodeEquals(err, opsworks.ErrCodeResourceNotFoundException) { - log.Printf("[DEBUG] OpsWorks Application (%s) not found to delete; removed from state", d.Id()) return nil } - return err + return fmt.Errorf("deleting OpsWorks Application (%s): %s", d.Id(), err) } func resourceFindEnvironmentVariable(key string, vs []*opsworks.EnvironmentVariable) *opsworks.EnvironmentVariable { diff --git a/internal/service/opsworks/instance.go b/internal/service/opsworks/instance.go index 7e48fc2c513..ad2efbc4201 100644 --- a/internal/service/opsworks/instance.go +++ b/internal/service/opsworks/instance.go @@ -2,6 +2,7 @@ package opsworks import ( "bytes" + "errors" "fmt" "log" "time" @@ -469,7 +470,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Opsworks intance (%s): %w", d.Id(), err) + return fmt.Errorf("reading OpsWorks Instance (%s): %w", d.Id(), err) } // If nothing was found, then return no state @@ -535,14 +536,14 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { ibds := readBlockDevices(instance) if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { - return err + return fmt.Errorf("reading OpsWorks Instance (%s): setting ebs_block_device: %w", d.Id(), err) } if err := d.Set("ephemeral_block_device", ibds["ephemeral"]); err != nil { - return err + return fmt.Errorf("reading OpsWorks Instance (%s): setting ephemeral_block_device: %w", d.Id(), err) } if ibds["root"] != nil { if err := d.Set("root_block_device", []interface{}{ibds["root"]}); err != nil { - return err + return fmt.Errorf("reading OpsWorks Instance (%s): setting root_block_device: %w", d.Id(), err) } } else { d.Set("root_block_device", []interface{}{}) @@ -553,8 +554,10 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { for _, sg := range instance.SecurityGroupIds { sgs = append(sgs, *sg) } - err1 := d.Set("security_group_ids", sgs) - return err1 + if err := d.Set("security_group_ids", sgs); err != nil { + return fmt.Errorf("reading OpsWorks Instance (%s): setting security_group_ids: %w", d.Id(), err) + } + return nil } func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { @@ -562,7 +565,7 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { err := resourceInstanceValidate(d) if err != nil { - return err + return fmt.Errorf("reading OpsWorks Instance: %w", err) } req := &opsworks.CreateInstanceInput{ @@ -700,11 +703,11 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { resp, err = conn.CreateInstance(req) if err != nil { - return err + return fmt.Errorf("creating OpsWorks Instance: %w", err) } if resp.InstanceId == nil { - return fmt.Errorf("Error launching instance: no instance returned in response") + return errors.New("creating OpsWorks Instance: no instance returned") } instanceId := aws.StringValue(resp.InstanceId) @@ -713,7 +716,7 @@ func resourceInstanceCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("state"); ok && v.(string) == instanceStatusRunning { err := startInstance(d, meta, true, d.Timeout(schema.TimeoutCreate)) if err != nil { - return err + return fmt.Errorf("creating OpsWorks Instance: %w", err) } } @@ -725,7 +728,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { err := resourceInstanceValidate(d) if err != nil { - return err + return fmt.Errorf("updating OpsWorks Instance (%s): %w", d.Id(), err) } req := &opsworks.UpdateInstanceInput{ @@ -768,7 +771,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateInstance(req) if err != nil { - return err + return fmt.Errorf("updating OpsWorks Instance (%s): %w", d.Id(), err) } var status string @@ -785,14 +788,14 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { if status == instanceStatusStopped || status == instanceStatusStopping || status == instanceStatusShuttingDown { err := startInstance(d, meta, false, d.Timeout(schema.TimeoutUpdate)) if err != nil { - return err + return fmt.Errorf("updating OpsWorks Instance (%s): %w", d.Id(), err) } } } else { if status != instanceStatusStopped && status != instanceStatusStopping && status != instanceStatusShuttingDown { err := stopInstance(d, meta, d.Timeout(schema.TimeoutUpdate)) if err != nil { - return err + return fmt.Errorf("updating OpsWorks Instance (%s): %w", d.Id(), err) } } } @@ -807,7 +810,7 @@ func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("status"); ok && v.(string) != instanceStatusStopped { err := stopInstance(d, meta, d.Timeout(schema.TimeoutDelete)) if err != nil { - return err + return fmt.Errorf("deleting OpsWorks instance (%s): %w", d.Id(), err) } } @@ -826,18 +829,17 @@ func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting OpsWorks instance (%s): %w", d.Id(), err) + return fmt.Errorf("deleting OpsWorks instance (%s): %w", d.Id(), err) } if err := waitInstanceDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("error waiting for OpsWorks instance (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting OpsWorks instance (%s): waiting for completion: %w", d.Id(), err) } return nil } -func resourceInstanceImport( - d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { +func resourceInstanceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { // Neither delete_eip nor delete_ebs can be fetched // from any API call, so we need to default to the values // we set in the schema by default @@ -858,14 +860,14 @@ func startInstance(d *schema.ResourceData, meta interface{}, wait bool, timeout _, err := conn.StartInstance(req) if err != nil { - return err + return fmt.Errorf("starting instance: %w", err) } if wait { log.Printf("[DEBUG] Waiting for OpsWorks instance (%s) to start", d.Id()) if err := waitInstanceStarted(conn, d.Id(), timeout); err != nil { - return fmt.Errorf("error waiting for OpsWorks instance (%s) to start: %w", d.Id(), err) + return fmt.Errorf("starting instance: waiting for completion: %w", err) } } @@ -884,13 +886,13 @@ func stopInstance(d *schema.ResourceData, meta interface{}, timeout time.Duratio _, err := conn.StopInstance(req) if err != nil { - return err + return fmt.Errorf("stopping instance: %w", err) } log.Printf("[DEBUG] Waiting for OpsWorks instance (%s) to become stopped", d.Id()) if err := waitInstanceStopped(conn, d.Id(), timeout); err != nil { - return fmt.Errorf("error waiting for OpsWorks instance (%s) to become stopped: %w", d.Id(), err) + return fmt.Errorf("stopping instance: waiting for completion: %w", err) } return nil diff --git a/internal/service/opsworks/permission.go b/internal/service/opsworks/permission.go index 362c9175b65..afa0c0936dd 100644 --- a/internal/service/opsworks/permission.go +++ b/internal/service/opsworks/permission.go @@ -1,6 +1,7 @@ package opsworks import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" @@ -80,7 +81,7 @@ func resourcePermissionRead(d *schema.ResourceData, meta interface{}) error { return nil } } - return err + return fmt.Errorf("reading OpsWorks Permissions (%s): %w", d.Id(), err) } found := false @@ -137,7 +138,7 @@ func resourceSetPermission(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return err + return fmt.Errorf("setting OpsWorks Permissions (%s): %w", d.Id(), err) } return resourcePermissionRead(d, meta) From a8468574cca53819faa57eab393a6f96177e10e8 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 14:45:43 -0800 Subject: [PATCH 032/106] Fixes bare errors in `opensearch` --- internal/service/opensearch/domain.go | 25 ++++++++----------- internal/service/opensearch/domain_policy.go | 14 +++++------ .../service/opensearch/domain_saml_options.go | 8 +++--- 3 files changed, 21 insertions(+), 26 deletions(-) diff --git a/internal/service/opensearch/domain.go b/internal/service/opensearch/domain.go index 8373e774db3..5cb6030f1b2 100644 --- a/internal/service/opensearch/domain.go +++ b/internal/service/opensearch/domain.go @@ -756,7 +756,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading OpenSearch domain (%s): %w", d.Id(), err) + return fmt.Errorf("reading OpenSearch Domain (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Received OpenSearch domain: %s", ds) @@ -766,7 +766,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("reading OpenSearch Domain (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Received config for OpenSearch domain: %s", outDescribeDomainConfig) @@ -777,7 +777,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.StringValue(ds.AccessPolicies)) if err != nil { - return err + return fmt.Errorf("reading OpenSearch Domain (%s): %w", d.Id(), err) } d.Set("access_policies", policies) @@ -828,7 +828,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { if v := dc.AutoTuneOptions; v != nil { err = d.Set("auto_tune_options", []interface{}{flattenAutoTuneOptions(v.Options)}) if err != nil { - return err + return fmt.Errorf("reading OpenSearch Domain (%s): setting auto_tune_options: %w", d.Id(), err) } } @@ -842,10 +842,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { } endpoints := flex.PointersMapToStringList(ds.Endpoints) - err = d.Set("endpoint", endpoints["vpc"]) - if err != nil { - return err - } + d.Set("endpoint", endpoints["vpc"]) d.Set("kibana_endpoint", getKibanaEndpoint(d)) if ds.Endpoint != nil { return fmt.Errorf("%q: OpenSearch domain in VPC expected to have null Endpoint value", d.Id()) @@ -1010,11 +1007,11 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.UpdateDomainConfig(&input) if err != nil { - return err + return fmt.Errorf("updating OpenSearch Domain (%s): %w", d.Id(), err) } if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain Update (%s) to succeed: %w", d.Id(), err) + return fmt.Errorf("updating OpenSearch Domain (%s): waiting for completion: %w", d.Id(), err) } if d.HasChange("engine_version") { @@ -1025,11 +1022,11 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.UpgradeDomain(&upgradeInput) if err != nil { - return fmt.Errorf("Failed to upgrade OpenSearch domain: %w", err) + return fmt.Errorf("updating OpenSearch Domain (%s): upgrading: %w", d.Id(), err) } if _, err := waitUpgradeSucceeded(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain Upgrade (%s) to succeed: %w", d.Id(), err) + return fmt.Errorf("updating OpenSearch Domain (%s): upgrading: waiting for completion: %w", d.Id(), err) } } } @@ -1057,12 +1054,12 @@ func resourceDomainDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, opensearchservice.ErrCodeResourceNotFoundException) { return nil } - return err + return fmt.Errorf("deleting OpenSearch Domain (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Waiting for OpenSearch domain %q to be deleted", domainName) if err := waitForDomainDelete(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting OpenSearch Domain (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/opensearch/domain_policy.go b/internal/service/opensearch/domain_policy.go index a19dd46a85e..3880f4b749b 100644 --- a/internal/service/opensearch/domain_policy.go +++ b/internal/service/opensearch/domain_policy.go @@ -58,15 +58,13 @@ func resourceDomainPolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading OpenSearch Domain Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading OpenSearch Domain Policy (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Received OpenSearch domain: %s", ds) - policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.StringValue(ds.AccessPolicies)) if err != nil { - return err + return fmt.Errorf("reading OpenSearch Domain Policy (%s): %w", d.Id(), err) } d.Set("access_policies", policies) @@ -89,13 +87,13 @@ func resourceDomainPolicyUpsert(d *schema.ResourceData, meta interface{}) error AccessPolicies: aws.String(policy), }) if err != nil { - return err + return fmt.Errorf("updating OpenSearch Domain Policy (%s): %w", d.Id(), err) } d.SetId("esd-policy-" + domainName) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain Policy (%s) to be updated: %w", d.Id(), err) + return fmt.Errorf("updating OpenSearch Domain Policy (%s): waiting for completion: %w", d.Id(), err) } return resourceDomainPolicyRead(d, meta) @@ -109,13 +107,13 @@ func resourceDomainPolicyDelete(d *schema.ResourceData, meta interface{}) error AccessPolicies: aws.String(""), }) if err != nil { - return err + return fmt.Errorf("deleting OpenSearch Domain Policy (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Waiting for OpenSearch domain policy %q to be deleted", d.Get("domain_name").(string)) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain Policy (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting OpenSearch Domain Policy (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/opensearch/domain_saml_options.go b/internal/service/opensearch/domain_saml_options.go index 20c98b31358..5368ab1362b 100644 --- a/internal/service/opensearch/domain_saml_options.go +++ b/internal/service/opensearch/domain_saml_options.go @@ -150,13 +150,13 @@ func resourceDomainSAMLOptionsPut(d *schema.ResourceData, meta interface{}) erro }) if err != nil { - return err + return fmt.Errorf("updating OpenSearch Domain SAML Options (%s): %w", d.Id(), err) } d.SetId(domainName) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain SAML Options update (%s) to succeed: %w", d.Id(), err) + return fmt.Errorf("updating OpenSearch Domain SAML Options (%s): waiting for completion: %w", d.Id(), err) } return resourceDomainSAMLOptionsRead(d, meta) @@ -174,13 +174,13 @@ func resourceDomainSAMLOptionsDelete(d *schema.ResourceData, meta interface{}) e AdvancedSecurityOptions: &config, }) if err != nil { - return err + return fmt.Errorf("deleting OpenSearch Domain SAML Options (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Waiting for OpenSearch domain SAML Options %q to be deleted", d.Get("domain_name").(string)) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for OpenSearch Domain SAML Options (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting OpenSearch Domain SAML Options (%s): waiting for completion: %w", d.Id(), err) } return nil From 567164c6d0c3d003300a3c409408513ee4c3f013 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:48:40 -0800 Subject: [PATCH 033/106] Fixes bare errors in `networkmanager` --- .../core_network_policy_document_data_source.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/service/networkmanager/core_network_policy_document_data_source.go b/internal/service/networkmanager/core_network_policy_document_data_source.go index 3bd675ee4f8..29bbf4bcb6c 100644 --- a/internal/service/networkmanager/core_network_policy_document_data_source.go +++ b/internal/service/networkmanager/core_network_policy_document_data_source.go @@ -315,35 +315,35 @@ func dataSourceCoreNetworkPolicyDocumentRead(d *schema.ResourceData, meta interf // CoreNetworkConfiguration networkConfiguration, err := expandDataCoreNetworkPolicyNetworkConfiguration(d.Get("core_network_configuration").([]interface{})) if err != nil { - return err + return fmt.Errorf("writing Network Manager Core Network Policy Document: %w", err) } mergedDoc.CoreNetworkConfiguration = networkConfiguration // AttachmentPolicies attachmentPolicies, err := expandDataCoreNetworkPolicyAttachmentPolicies(d.Get("attachment_policies").([]interface{})) if err != nil { - return err + return fmt.Errorf("writing Network Manager Core Network Policy Document: %w", err) } mergedDoc.AttachmentPolicies = attachmentPolicies // SegmentActions segment_actions, err := expandDataCoreNetworkPolicySegmentActions(d.Get("segment_actions").([]interface{})) if err != nil { - return err + return fmt.Errorf("writing Network Manager Core Network Policy Document: %w", err) } mergedDoc.SegmentActions = segment_actions // Segments segments, err := expandDataCoreNetworkPolicySegments(d.Get("segments").([]interface{})) if err != nil { - return err + return fmt.Errorf("writing Network Manager Core Network Policy Document: %w", err) } mergedDoc.Segments = segments jsonDoc, err := json.MarshalIndent(mergedDoc, "", " ") if err != nil { // should never happen if the above code is correct - return err + return fmt.Errorf("writing Network Manager Core Network Policy Document: formatting JSON: %w", err) } jsonString := string(jsonDoc) From 76fc089e6f29c015452974138d5d1739e969b557 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:48:56 -0800 Subject: [PATCH 034/106] Fixes bare errors in `neptune` --- internal/service/neptune/cluster.go | 16 ++++++------ internal/service/neptune/cluster_instance.go | 26 +++++++------------ .../neptune/cluster_parameter_group.go | 2 +- .../service/neptune/event_subscription.go | 8 +++--- internal/service/neptune/parameter_group.go | 8 +++--- internal/service/neptune/subnet_group.go | 6 ++--- 6 files changed, 29 insertions(+), 37 deletions(-) diff --git a/internal/service/neptune/cluster.go b/internal/service/neptune/cluster.go index 6b2bcdc2ec7..81707d39faf 100644 --- a/internal/service/neptune/cluster.go +++ b/internal/service/neptune/cluster.go @@ -435,14 +435,14 @@ func resourceClusterCreate(d *schema.ResourceData, meta interface{}) error { _, err = WaitDBClusterAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return fmt.Errorf("waiting for Neptune Cluster (%q) to be Available: %w", d.Id(), err) + return fmt.Errorf("creating Neptune Cluster (%s): waiting for completion: %w", d.Id(), err) } if v, ok := d.GetOk("iam_roles"); ok { for _, role := range v.(*schema.Set).List() { - err := setIAMRoleToCluster(d.Id(), role.(string), conn) + err := addIAMRoleToCluster(d.Id(), role.(string), conn) if err != nil { - return err + return fmt.Errorf("creating Neptune Cluster (%s): adding IAM Role (%s): %w", d.Id(), role.(string), err) } } } @@ -468,7 +468,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { return nil } log.Printf("[DEBUG] Error describing Neptune Cluster (%s) when waiting: %s", d.Id(), err) - return err + return fmt.Errorf("reading Neptune Cluster (%s): %w", d.Id(), err) } var dbc *neptune.DBCluster @@ -752,16 +752,16 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { enableRoles := ns.Difference(os) for _, role := range enableRoles.List() { - err := setIAMRoleToCluster(d.Id(), role.(string), conn) + err := addIAMRoleToCluster(d.Id(), role.(string), conn) if err != nil { - return err + return fmt.Errorf("updating Neptune Cluster (%s): adding IAM Role (%s): %w", d.Id(), role.(string), err) } } for _, role := range removeRoles.List() { err := removeIAMRoleFromCluster(d.Id(), role.(string), conn) if err != nil { - return err + return fmt.Errorf("updating Neptune Cluster (%s): removing IAM Role (%s): %w", d.Id(), role.(string), err) } } } @@ -848,7 +848,7 @@ func resourceClusterDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func setIAMRoleToCluster(clusterIdentifier string, roleArn string, conn *neptune.Neptune) error { +func addIAMRoleToCluster(clusterIdentifier string, roleArn string, conn *neptune.Neptune) error { params := &neptune.AddRoleToDBClusterInput{ DBClusterIdentifier: aws.String(clusterIdentifier), RoleArn: aws.String(roleArn), diff --git a/internal/service/neptune/cluster_instance.go b/internal/service/neptune/cluster_instance.go index 56bf06e68dc..3d86e0d4a2d 100644 --- a/internal/service/neptune/cluster_instance.go +++ b/internal/service/neptune/cluster_instance.go @@ -242,8 +242,6 @@ func resourceClusterInstanceCreate(d *schema.ResourceData, meta interface{}) err createOpts.PreferredMaintenanceWindow = aws.String(attr.(string)) } - log.Printf("[DEBUG] Creating Neptune Instance: %s", createOpts) - var resp *neptune.CreateDBInstanceOutput err := resource.Retry(propagationTimeout, func() *resource.RetryError { var err error @@ -260,7 +258,7 @@ func resourceClusterInstanceCreate(d *schema.ResourceData, meta interface{}) err resp, err = conn.CreateDBInstance(createOpts) } if err != nil { - return fmt.Errorf("creating Neptune Instance: %s", err) + return fmt.Errorf("creating Neptune Cluster Instance: %s", err) } d.SetId(aws.StringValue(resp.DBInstance.DBInstanceIdentifier)) @@ -277,7 +275,7 @@ func resourceClusterInstanceCreate(d *schema.ResourceData, meta interface{}) err // Wait, catching any errors _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("creating Neptune Cluster Instance: waiting for completion: %s", err) } return resourceClusterInstanceRead(d, meta) @@ -286,7 +284,7 @@ func resourceClusterInstanceCreate(d *schema.ResourceData, meta interface{}) err func resourceClusterInstanceRead(d *schema.ResourceData, meta interface{}) error { db, err := resourceInstanceRetrieve(d.Id(), meta.(*conns.AWSClient).NeptuneConn()) if err != nil { - return fmt.Errorf("Error on retrieving Neptune Cluster Instance (%s): %s", d.Id(), err) + return fmt.Errorf("reading Neptune Cluster Instance (%s): %s", d.Id(), err) } if db == nil { @@ -418,9 +416,7 @@ func resourceClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) err requestUpdate = true } - log.Printf("[DEBUG] Send Neptune Instance Modification request: %#v", requestUpdate) if requestUpdate { - log.Printf("[DEBUG] Neptune Instance Modification request: %#v", req) err := resource.Retry(propagationTimeout, func() *resource.RetryError { _, err := conn.ModifyDBInstance(req) if err != nil { @@ -435,7 +431,7 @@ func resourceClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) err _, err = conn.ModifyDBInstance(req) } if err != nil { - return fmt.Errorf("Error modifying Neptune Instance %s: %s", d.Id(), err) + return fmt.Errorf("updating Neptune Cluster Instance (%s): %s", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -450,7 +446,7 @@ func resourceClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) err // Wait, catching any errors _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("updating Neptune Cluster Instance (%s): waiting for completion: %s", d.Id(), err) } } @@ -472,12 +468,11 @@ func resourceClusterInstanceDelete(d *schema.ResourceData, meta interface{}) err opts := neptune.DeleteDBInstanceInput{DBInstanceIdentifier: aws.String(d.Id())} - log.Printf("[DEBUG] Neptune Cluster Instance destroy configuration: %s", opts) if _, err := conn.DeleteDBInstance(&opts); err != nil { if tfawserr.ErrCodeEquals(err, neptune.ErrCodeDBInstanceNotFoundFault) { return nil } - return fmt.Errorf("deleting Neptune cluster instance %q: %s", d.Id(), err) + return fmt.Errorf("deleting Neptune Cluster Instance (%s): %s", d.Id(), err) } log.Println("[INFO] Waiting for Neptune Cluster Instance to be destroyed") @@ -491,7 +486,7 @@ func resourceClusterInstanceDelete(d *schema.ResourceData, meta interface{}) err } _, err := stateConf.WaitForState() - return err + return fmt.Errorf("deleting Neptune Cluster Instance (%s): waiting for completion: %s", d.Id(), err) } var resourceClusterInstanceCreateUpdatePendingStates = []string{ @@ -520,7 +515,6 @@ func resourceInstanceStateRefreshFunc(id string, conn *neptune.Neptune) resource v, err := resourceInstanceRetrieve(id, conn) if err != nil { - log.Printf("Error on retrieving Neptune Instance when waiting: %s", err) return nil, "", err } @@ -529,7 +523,7 @@ func resourceInstanceStateRefreshFunc(id string, conn *neptune.Neptune) resource } if v.DBInstanceStatus != nil { - log.Printf("[DEBUG] Neptune Instance status for instance %s: %s", id, aws.StringValue(v.DBInstanceStatus)) + log.Printf("[DEBUG] Neptune Cluster Instance status for instance %s: %s", id, aws.StringValue(v.DBInstanceStatus)) } return v, aws.StringValue(v.DBInstanceStatus), nil @@ -541,14 +535,12 @@ func resourceInstanceRetrieve(id string, conn *neptune.Neptune) (*neptune.DBInst DBInstanceIdentifier: aws.String(id), } - log.Printf("[DEBUG] Neptune Instance describe configuration: %#v", opts) - resp, err := conn.DescribeDBInstances(&opts) if err != nil { if tfawserr.ErrCodeEquals(err, neptune.ErrCodeDBInstanceNotFoundFault) { return nil, nil } - return nil, fmt.Errorf("Error retrieving Neptune Instances: %s", err) + return nil, err } if len(resp.DBInstances) != 1 || diff --git a/internal/service/neptune/cluster_parameter_group.go b/internal/service/neptune/cluster_parameter_group.go index 7aa34ab6366..3ba57e1503a 100644 --- a/internal/service/neptune/cluster_parameter_group.go +++ b/internal/service/neptune/cluster_parameter_group.go @@ -175,7 +175,7 @@ func resourceClusterParameterGroupRead(d *schema.ResourceData, meta interface{}) describeParametersResp, err := conn.DescribeDBClusterParameters(&describeParametersOpts) if err != nil { - return err + return fmt.Errorf("reading Neptune Cluster Parameter Group (%s): %w", d.Id(), err) } if err := d.Set("parameter", flattenParameters(describeParametersResp.Parameters)); err != nil { diff --git a/internal/service/neptune/event_subscription.go b/internal/service/neptune/event_subscription.go index 30960a3d404..00463b7f8d0 100644 --- a/internal/service/neptune/event_subscription.go +++ b/internal/service/neptune/event_subscription.go @@ -258,7 +258,7 @@ func resourceEventSubscriptionUpdate(d *schema.ResourceData, meta interface{}) e log.Printf("[DEBUG] Neptune Event Subscription modification request: %#v", req) _, err := conn.ModifyEventSubscription(req) if err != nil { - return fmt.Errorf("Modifying Neptune Event Subscription %s failed: %s", d.Id(), err) + return fmt.Errorf("updating Neptune Event Subscription (%s): %s", d.Id(), err) } log.Println("[INFO] Waiting for Neptune Event Subscription modification to finish") @@ -275,7 +275,7 @@ func resourceEventSubscriptionUpdate(d *schema.ResourceData, meta interface{}) e // Wait, catching any errors _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("updating Neptune Event Subscription (%s): waiting for completion: %s", d.Id(), err) } } @@ -309,7 +309,7 @@ func resourceEventSubscriptionUpdate(d *schema.ResourceData, meta interface{}) e SubscriptionName: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("updating Neptune Event Subscription (%s): removing Source Identifier (%s): %s", d.Id(), aws.StringValue(removing), err) } } } @@ -322,7 +322,7 @@ func resourceEventSubscriptionUpdate(d *schema.ResourceData, meta interface{}) e SubscriptionName: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("updating Neptune Event Subscription (%s): adding Source Identifier (%s): %s", d.Id(), aws.StringValue(adding), err) } } } diff --git a/internal/service/neptune/parameter_group.go b/internal/service/neptune/parameter_group.go index b357b26a82c..17362c89f82 100644 --- a/internal/service/neptune/parameter_group.go +++ b/internal/service/neptune/parameter_group.go @@ -129,16 +129,16 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error d.SetId("") return nil } - return err + return fmt.Errorf("reading Neptune Parameter Group (%s): %w", d.Id(), err) } if describeResp == nil { - return fmt.Errorf("Unable to get Describe Response for Neptune Parameter Group (%s)", d.Id()) + return fmt.Errorf("reading Neptune Parameter Group (%s): empty result", d.Id()) } if len(describeResp.DBParameterGroups) != 1 || aws.StringValue(describeResp.DBParameterGroups[0].DBParameterGroupName) != d.Id() { - return fmt.Errorf("Unable to find Parameter Group: %#v", describeResp.DBParameterGroups) + return fmt.Errorf("reading Neptune Parameter Group (%s): no match", d.Id()) } arn := aws.StringValue(describeResp.DBParameterGroups[0].DBParameterGroupArn) @@ -160,7 +160,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error return !lastPage }) if err != nil { - return err + return fmt.Errorf("reading Neptune Parameter Group (%s) parameters: %w", d.Id(), err) } if err := d.Set("parameter", flattenParameters(parameters)); err != nil { diff --git a/internal/service/neptune/subnet_group.go b/internal/service/neptune/subnet_group.go index 6eef4ba445c..7b5279600cb 100644 --- a/internal/service/neptune/subnet_group.go +++ b/internal/service/neptune/subnet_group.go @@ -126,7 +126,7 @@ func resourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading Neptune Subnet Group (%s): %w", d.Id(), err) } if len(subnetGroups) == 0 { @@ -197,7 +197,7 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("updating Neptune Subnet Group (%s): %s", d.Id(), err) } } @@ -205,7 +205,7 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("updating Neptune Subnet Group (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating Neptune Subnet Group (%s) tags: %s", d.Id(), err) } } From 0cdb2710695278b9fd22b1d8f2bbd59f32cb9e48 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:49:13 -0800 Subject: [PATCH 035/106] Fixes bare errors in `mediastore` --- internal/service/mediastore/container.go | 14 ++++++------- .../service/mediastore/container_policy.go | 20 +++++++++---------- internal/service/mediastore/container_test.go | 2 +- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/internal/service/mediastore/container.go b/internal/service/mediastore/container.go index 9c9f256e62e..cd56a28861f 100644 --- a/internal/service/mediastore/container.go +++ b/internal/service/mediastore/container.go @@ -65,7 +65,7 @@ func resourceContainerCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateContainer(input) if err != nil { - return err + return fmt.Errorf("creating MediaStore Container: %w", err) } d.SetId(aws.StringValue(resp.Container.Name)) @@ -81,7 +81,7 @@ func resourceContainerCreate(d *schema.ResourceData, meta interface{}) error { _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("creating MediaStore Container (%s): waiting for completion: %w", d.Id(), err) } return resourceContainerRead(d, meta) @@ -102,7 +102,7 @@ func resourceContainerRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error describing media store container %s: %s", d.Id(), err) + return fmt.Errorf("reading MediaStore Container %s: %s", d.Id(), err) } arn := aws.StringValue(resp.Container.ARN) @@ -113,7 +113,7 @@ func resourceContainerRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) if err != nil { - return fmt.Errorf("error listing tags for media store container (%s): %s", arn, err) + return fmt.Errorf("error listing tags for MediaStore Container (%s): %s", arn, err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -138,7 +138,7 @@ func resourceContainerUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating media store container (%s) tags: %s", arn, err) + return fmt.Errorf("error updating MediaStore Container (%s) tags: %s", arn, err) } } @@ -156,7 +156,7 @@ func resourceContainerDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, mediastore.ErrCodeContainerNotFoundException) { return nil } - return err + return fmt.Errorf("deleting MediaStore Container (%s): %w", d.Id(), err) } dcinput := &mediastore.DescribeContainerInput{ @@ -176,7 +176,7 @@ func resourceContainerDelete(d *schema.ResourceData, meta interface{}) error { _, err = conn.DescribeContainer(dcinput) } if err != nil { - return fmt.Errorf("error waiting for Media Store Container (%s) deletion: %s", d.Id(), err) + return fmt.Errorf("deleting MediaStore Container (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/mediastore/container_policy.go b/internal/service/mediastore/container_policy.go index 3c915cae43b..89745e2259a 100644 --- a/internal/service/mediastore/container_policy.go +++ b/internal/service/mediastore/container_policy.go @@ -46,23 +46,24 @@ func ResourceContainerPolicy() *schema.Resource { func resourceContainerPolicyPut(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).MediaStoreConn() + name := d.Get("container_name").(string) policy, err := structure.NormalizeJsonString(d.Get("policy").(string)) if err != nil { - return fmt.Errorf("policy (%s) is invalid JSON: %w", policy, err) + return fmt.Errorf("putting MediaStore Container Policy (%s): %w", name, err) } input := &mediastore.PutContainerPolicyInput{ - ContainerName: aws.String(d.Get("container_name").(string)), + ContainerName: aws.String(name), Policy: aws.String(policy), } _, err = conn.PutContainerPolicy(input) if err != nil { - return err + return fmt.Errorf("putting MediaStore Container Policy (%s): %w", name, err) } - d.SetId(d.Get("container_name").(string)) + d.SetId(name) return resourceContainerPolicyRead(d, meta) } @@ -76,24 +77,23 @@ func resourceContainerPolicyRead(d *schema.ResourceData, meta interface{}) error resp, err := conn.GetContainerPolicy(input) if err != nil { if tfawserr.ErrCodeEquals(err, mediastore.ErrCodeContainerNotFoundException) { - log.Printf("[WARN] MediaContainer Policy %q not found, removing from state", d.Id()) + log.Printf("[WARN] MediaStore Container Policy (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if tfawserr.ErrCodeEquals(err, mediastore.ErrCodePolicyNotFoundException) { - log.Printf("[WARN] MediaContainer Policy %q not found, removing from state", d.Id()) + log.Printf("[WARN] MediaStore Container Policy (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading MediaStore Container Policy (%s): %w", d.Id(), err) } d.Set("container_name", d.Id()) policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(resp.Policy)) - if err != nil { - return err + return fmt.Errorf("reading MediaStore Container Policy (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) @@ -119,7 +119,7 @@ func resourceContainerPolicyDelete(d *schema.ResourceData, meta interface{}) err // if isAWSErr(err, mediastore.ErrCodeContainerInUseException, "Container must be ACTIVE in order to perform this operation") { // return nil // } - return err + return fmt.Errorf("deleting MediaStore Container Policy (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/mediastore/container_test.go b/internal/service/mediastore/container_test.go index 31f22d85723..ac9fbfb5c20 100644 --- a/internal/service/mediastore/container_test.go +++ b/internal/service/mediastore/container_test.go @@ -105,7 +105,7 @@ func testAccCheckContainerDestroy(s *terraform.State) error { } if *resp.Container.Status != mediastore.ContainerStatusDeleting { - return fmt.Errorf("Media Store Container (%s) not deleted", rs.Primary.ID) + return fmt.Errorf("MediaStore Container (%s) not deleted", rs.Primary.ID) } } return nil From 7d2d5b03145eb1987ddfeee797587c04e4ab0ce2 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:49:29 -0800 Subject: [PATCH 036/106] Fixes bare errors in `lightsail` --- internal/service/lightsail/domain.go | 20 ++++----- internal/service/lightsail/key_pair.go | 41 ++++++++----------- internal/service/lightsail/static_ip.go | 26 +++++------- .../service/lightsail/static_ip_attachment.go | 34 +++++++-------- 4 files changed, 51 insertions(+), 70 deletions(-) diff --git a/internal/service/lightsail/domain.go b/internal/service/lightsail/domain.go index 90f95ade088..ff8044b98c6 100644 --- a/internal/service/lightsail/domain.go +++ b/internal/service/lightsail/domain.go @@ -1,11 +1,12 @@ package lightsail import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -37,7 +38,7 @@ func resourceDomainCreate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("creating Lightsail Domain: %w", err) } d.SetId(d.Get("domain_name").(string)) @@ -52,15 +53,12 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "NotFoundException" { - log.Printf("[WARN] Lightsail Domain (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return err + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + log.Printf("[WARN] Lightsail Domain (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - return err + return fmt.Errorf("reading Lightsail Domain (%s):%w", d.Id(), err) } d.Set("arn", resp.Domain.Arn) @@ -73,5 +71,5 @@ func resourceDomainDelete(d *schema.ResourceData, meta interface{}) error { DomainName: aws.String(d.Id()), }) - return err + return fmt.Errorf("deleting Lightsail Domain (%s):%w", d.Id(), err) } diff --git a/internal/service/lightsail/key_pair.go b/internal/service/lightsail/key_pair.go index d4eee187b62..bf0f6ce1566 100644 --- a/internal/service/lightsail/key_pair.go +++ b/internal/service/lightsail/key_pair.go @@ -7,8 +7,8 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" @@ -102,13 +102,13 @@ func resourceKeyPairCreate(d *schema.ResourceData, meta interface{}) error { KeyPairName: aws.String(kName), }) if err != nil { - return err + return fmt.Errorf("creating Lightsail Key Pair (%s): %w", kName, err) } if resp.Operation == nil { - return fmt.Errorf("No operation found for CreateKeyPair response") + return fmt.Errorf("creating Lightsail Key Pair (%s): no operation returned", kName) } if resp.KeyPair == nil { - return fmt.Errorf("No KeyPair information found for CreateKeyPair response") + return fmt.Errorf("creating Lightsail Key Pair (%s): no key information returned", kName) } d.SetId(kName) @@ -120,12 +120,12 @@ func resourceKeyPairCreate(d *schema.ResourceData, meta interface{}) error { // encrypt private key if pgp_key is given pgpKey, err := retrieveGPGKey(d.Get("pgp_key").(string)) if err != nil { - return err + return fmt.Errorf("creating Lightsail Key Pair (%s): %w", kName, err) } if pgpKey != "" { - fingerprint, encrypted, err := encryptValue(pgpKey, *resp.PrivateKeyBase64, "Lightsail Private Key") + fingerprint, encrypted, err := encryptValue(pgpKey, aws.StringValue(resp.PrivateKeyBase64), "Lightsail Private Key") if err != nil { - return err + return fmt.Errorf("creating Lightsail Key Pair (%s): %w", kName, err) } d.Set("encrypted_fingerprint", fingerprint) @@ -143,8 +143,7 @@ func resourceKeyPairCreate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - log.Printf("[ERR] Error importing key: %s", err) - return err + return fmt.Errorf("creating Lightsail Key Pair (%s): %w", kName, err) } d.SetId(kName) @@ -169,16 +168,12 @@ func resourceKeyPairRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - log.Printf("[WARN] Error getting KeyPair (%s): %s", d.Id(), err) - // check for known not found error - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "NotFoundException" { - log.Printf("[WARN] Lightsail KeyPair (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + log.Printf("[WARN] Lightsail KeyPair (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - return err + return fmt.Errorf("reading Lightsail Key Pair (%s): %w", d.Id(), err) } d.Set("arn", resp.KeyPair.Arn) @@ -195,7 +190,7 @@ func resourceKeyPairDelete(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("deleting Lightsail Key Pair (%s): %w", d.Id(), err) } op := resp.Operation @@ -203,9 +198,7 @@ func resourceKeyPairDelete(d *schema.ResourceData, meta interface{}) error { err = waitOperation(conn, op.Id) if err != nil { - return fmt.Errorf( - "Error waiting for KeyPair (%s) to become destroyed: %s", - d.Id(), err) + return fmt.Errorf("deleting Lightsail Key Pair (%s): waiting for completion: %w", d.Id(), err) } return nil @@ -221,7 +214,7 @@ func retrieveGPGKey(pgpKey string) (string, error) { if strings.HasPrefix(pgpKey, keybasePrefix) { publicKeys, err := pgpkeys.FetchKeybasePubkeys([]string{pgpKey}) if err != nil { - return "", fmt.Errorf("Error retrieving Public Key for %s: %w", pgpKey, err) + return "", fmt.Errorf("retrieving Public Key (%s): %w", pgpKey, err) } encryptionKey = publicKeys[pgpKey] } @@ -235,7 +228,7 @@ func encryptValue(encryptionKey, value, description string) (string, string, err fingerprints, encryptedValue, err := pgpkeys.EncryptShares([][]byte{[]byte(value)}, []string{encryptionKey}) if err != nil { - return "", "", fmt.Errorf("Error encrypting %s: %w", description, err) + return "", "", fmt.Errorf("encrypting %s: %w", description, err) } return fingerprints[0], base64.StdEncoding.EncodeToString(encryptedValue[0]), nil diff --git a/internal/service/lightsail/static_ip.go b/internal/service/lightsail/static_ip.go index 207317165ae..a2015a7d2a3 100644 --- a/internal/service/lightsail/static_ip.go +++ b/internal/service/lightsail/static_ip.go @@ -1,11 +1,12 @@ package lightsail import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -43,13 +44,12 @@ func resourceStaticIPCreate(d *schema.ResourceData, meta interface{}) error { name := d.Get("name").(string) log.Printf("[INFO] Allocating Lightsail Static IP: %q", name) - out, err := conn.AllocateStaticIp(&lightsail.AllocateStaticIpInput{ + _, err := conn.AllocateStaticIp(&lightsail.AllocateStaticIpInput{ StaticIpName: aws.String(name), }) if err != nil { - return err + return fmt.Errorf("creating Lightsail Static IP: %w", err) } - log.Printf("[INFO] Lightsail Static IP allocated: %s", *out) d.SetId(name) @@ -65,16 +65,13 @@ func resourceStaticIPRead(d *schema.ResourceData, meta interface{}) error { StaticIpName: aws.String(name), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "NotFoundException" { - log.Printf("[WARN] Lightsail Static IP (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + log.Printf("[WARN] Lightsail Static IP (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - return err + return fmt.Errorf("reading Lightsail Static IP (%s):%w", d.Id(), err) } - log.Printf("[INFO] Received Lightsail Static IP: %s", *out) d.Set("arn", out.StaticIp.Arn) d.Set("ip_address", out.StaticIp.IpAddress) @@ -88,12 +85,11 @@ func resourceStaticIPDelete(d *schema.ResourceData, meta interface{}) error { name := d.Get("name").(string) log.Printf("[INFO] Deleting Lightsail Static IP: %q", name) - out, err := conn.ReleaseStaticIp(&lightsail.ReleaseStaticIpInput{ + _, err := conn.ReleaseStaticIp(&lightsail.ReleaseStaticIpInput{ StaticIpName: aws.String(name), }) if err != nil { - return err + return fmt.Errorf("deleting Lightsail Static IP (%s):%w", d.Id(), err) } - log.Printf("[INFO] Deleted Lightsail Static IP: %s", *out) return nil } diff --git a/internal/service/lightsail/static_ip_attachment.go b/internal/service/lightsail/static_ip_attachment.go index 38a77f2a2d0..72a3d5211c6 100644 --- a/internal/service/lightsail/static_ip_attachment.go +++ b/internal/service/lightsail/static_ip_attachment.go @@ -1,11 +1,12 @@ package lightsail import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lightsail" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -39,15 +40,14 @@ func resourceStaticIPAttachmentCreate(d *schema.ResourceData, meta interface{}) conn := meta.(*conns.AWSClient).LightsailConn() staticIpName := d.Get("static_ip_name").(string) - log.Printf("[INFO] Attaching Lightsail Static IP: %q", staticIpName) - out, err := conn.AttachStaticIp(&lightsail.AttachStaticIpInput{ + log.Printf("[INFO] Creating Lightsail Static IP Attachment: %q", staticIpName) + _, err := conn.AttachStaticIp(&lightsail.AttachStaticIpInput{ StaticIpName: aws.String(staticIpName), InstanceName: aws.String(d.Get("instance_name").(string)), }) if err != nil { - return err + return fmt.Errorf("creating Lightsail Static IP Attachment: %w", err) } - log.Printf("[INFO] Lightsail Static IP attached: %s", *out) d.SetId(staticIpName) @@ -58,28 +58,24 @@ func resourceStaticIPAttachmentRead(d *schema.ResourceData, meta interface{}) er conn := meta.(*conns.AWSClient).LightsailConn() staticIpName := d.Get("static_ip_name").(string) - log.Printf("[INFO] Reading Lightsail Static IP: %q", staticIpName) + log.Printf("[INFO] Reading Lightsail Static IP Attachment: %q", staticIpName) out, err := conn.GetStaticIp(&lightsail.GetStaticIpInput{ StaticIpName: aws.String(staticIpName), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "NotFoundException" { - log.Printf("[WARN] Lightsail Static IP (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } + if tfawserr.ErrCodeEquals(err, lightsail.ErrCodeNotFoundException) { + log.Printf("[WARN] Lightsail Static IP Attachment (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - return err + return fmt.Errorf("reading Lightsail Static IP Attachment (%s):%w", d.Id(), err) } if !*out.StaticIp.IsAttached { - log.Printf("[WARN] Lightsail Static IP (%s) is not attached, removing from state", d.Id()) + log.Printf("[WARN] Lightsail Static IP Attachment (%s) is not attached, removing from state", d.Id()) d.SetId("") return nil } - log.Printf("[INFO] Received Lightsail Static IP: %s", *out) - d.Set("instance_name", out.StaticIp.AttachedTo) d.Set("ip_address", out.StaticIp.IpAddress) @@ -90,13 +86,11 @@ func resourceStaticIPAttachmentDelete(d *schema.ResourceData, meta interface{}) conn := meta.(*conns.AWSClient).LightsailConn() name := d.Get("static_ip_name").(string) - log.Printf("[INFO] Detaching Lightsail Static IP: %q", name) - out, err := conn.DetachStaticIp(&lightsail.DetachStaticIpInput{ + _, err := conn.DetachStaticIp(&lightsail.DetachStaticIpInput{ StaticIpName: aws.String(name), }) if err != nil { - return err + return fmt.Errorf("deleting Lightsail Static IP Attachment (%s):%w", d.Id(), err) } - log.Printf("[INFO] Detached Lightsail Static IP: %s", *out) return nil } From 01d8a16ca42de25e18bb2bd4303de6523ef63135 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:49:43 -0800 Subject: [PATCH 037/106] Fixes bare errors in `lexmodels` --- internal/service/lexmodels/bot_alias.go | 20 ++++++++++---------- internal/service/lexmodels/intent.go | 8 +++++--- internal/service/lexmodels/slot_type.go | 8 +++++--- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/internal/service/lexmodels/bot_alias.go b/internal/service/lexmodels/bot_alias.go index cfda1ef97c1..f746a47f2e3 100644 --- a/internal/service/lexmodels/bot_alias.go +++ b/internal/service/lexmodels/bot_alias.go @@ -132,7 +132,7 @@ func resourceBotAliasCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("conversation_logs"); ok { conversationLogs, err := expandConversationLogs(v) if err != nil { - return err + return fmt.Errorf("creating Lex Model Bot Alias (%s): %w", id, err) } input.ConversationLogs = conversationLogs } @@ -154,13 +154,12 @@ func resourceBotAliasCreate(d *schema.ResourceData, meta interface{}) error { return nil }) - if tfresource.TimedOut(err) { // nosemgrep:ci.helper-schema-TimeoutError-check-doesnt-return-output _, err = conn.PutBotAlias(input) } if err != nil { - return fmt.Errorf("error creating bot alias '%s': %w", id, err) + return fmt.Errorf("creating Lex Model Bot Alias (%s): %w", id, err) } d.SetId(id) @@ -225,7 +224,7 @@ func resourceBotAliasUpdate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("conversation_logs"); ok { conversationLogs, err := expandConversationLogs(v) if err != nil { - return err + return fmt.Errorf("updating Lex Model Bot Alias (%s): %w", d.Id(), err) } input.ConversationLogs = conversationLogs } @@ -252,7 +251,7 @@ func resourceBotAliasUpdate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error updating bot alias '%s': %w", d.Id(), err) + return fmt.Errorf("updating Lex Model Bot Alias (%s): %w", d.Id(), err) } return resourceBotAliasRead(d, meta) @@ -273,7 +272,7 @@ func resourceBotAliasDelete(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeleteBotAlias(input) if tfawserr.ErrCodeEquals(err, lexmodelbuildingservice.ErrCodeConflictException) { - return resource.RetryableError(fmt.Errorf("'%q': bot alias still deleting", d.Id())) + return resource.RetryableError(fmt.Errorf("%q: bot alias still deleting", d.Id())) } if err != nil { return resource.NonRetryableError(err) @@ -285,14 +284,15 @@ func resourceBotAliasDelete(d *schema.ResourceData, meta interface{}) error { if tfresource.TimedOut(err) { _, err = conn.DeleteBotAlias(input) } - if err != nil { - return fmt.Errorf("error deleting bot alias '%s': %w", d.Id(), err) + return fmt.Errorf("deleting Lex Model Bot Alias (%s): %w", d.Id(), err) } - _, err = waitBotAliasDeleted(conn, botAliasName, botName) + if _, err := waitBotAliasDeleted(conn, botAliasName, botName); err != nil { + return fmt.Errorf("deleting Lex Model Bot Alias (%s): waiting for completion: %w", d.Id(), err) + } - return err + return nil } func resourceBotAliasImport(d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) { diff --git a/internal/service/lexmodels/intent.go b/internal/service/lexmodels/intent.go index a6d1bf8cc85..00126a7b43b 100644 --- a/internal/service/lexmodels/intent.go +++ b/internal/service/lexmodels/intent.go @@ -527,12 +527,14 @@ func resourceIntentDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting intent %s: %w", d.Id(), err) + return fmt.Errorf("deleting Lex Model Intent (%s): %w", d.Id(), err) } - _, err = waitIntentDeleted(conn, d.Id()) + if _, err := waitIntentDeleted(conn, d.Id()); err != nil { + return fmt.Errorf("deleting Lex Model Intent (%s): waiting for completion: %w", d.Id(), err) + } - return err + return nil } var codeHookResource = &schema.Resource{ diff --git a/internal/service/lexmodels/slot_type.go b/internal/service/lexmodels/slot_type.go index 513a03e23df..38736c63e90 100644 --- a/internal/service/lexmodels/slot_type.go +++ b/internal/service/lexmodels/slot_type.go @@ -249,12 +249,14 @@ func resourceSlotTypeDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting Lex Slot Type (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Lex Model Slot Type (%s): %w", d.Id(), err) } - _, err = waitSlotTypeDeleted(conn, d.Id()) + if _, err := waitSlotTypeDeleted(conn, d.Id()); err != nil { + return fmt.Errorf("deleting Lex Model Slot Type (%s): waiting for completion: %w", d.Id(), err) + } - return err + return nil } func flattenEnumerationValues(values []*lexmodelbuildingservice.EnumerationValue) (flattened []map[string]interface{}) { From 2d9758b4a9addad4d1fc91edd11ade6e233f2f11 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:50:04 -0800 Subject: [PATCH 038/106] Fixes bare errors in `lambda` --- internal/service/lambda/alias.go | 12 +++++------- internal/service/lambda/function.go | 4 ++-- .../service/lambda/function_event_invoke_config.go | 14 +++++++------- internal/service/lambda/invocation_data_source.go | 8 +++----- .../service/lambda/layer_version_permission.go | 8 ++++---- internal/service/lambda/permission.go | 2 +- .../lambda/provisioned_concurrency_config.go | 14 +++++++------- 7 files changed, 29 insertions(+), 33 deletions(-) diff --git a/internal/service/lambda/alias.go b/internal/service/lambda/alias.go index 436309bc8fd..ce1efab3427 100644 --- a/internal/service/lambda/alias.go +++ b/internal/service/lambda/alias.go @@ -6,8 +6,8 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lambda" + "github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" ) @@ -116,13 +116,11 @@ func resourceAliasRead(d *schema.ResourceData, meta interface{}) error { aliasConfiguration, err := conn.GetAlias(params) if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "ResourceNotFoundException" && strings.Contains(awsErr.Message(), "Cannot find alias arn") { - d.SetId("") - return nil - } + if tfawserr.ErrCodeEquals(err, lambda.ErrCodeResourceNotFoundException) { + d.SetId("") + return nil } - return err + return fmt.Errorf("reading Lambda Alias (%s): %w", d.Id(), err) } d.Set("description", aliasConfiguration.Description) diff --git a/internal/service/lambda/function.go b/internal/service/lambda/function.go index 06c4211f848..7c728deb6b3 100644 --- a/internal/service/lambda/function.go +++ b/internal/service/lambda/function.go @@ -719,7 +719,7 @@ func resourceFunctionRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading Lambda Function (%s): %w", d.Id(), err) } if getFunctionOutput.Concurrency != nil { @@ -907,7 +907,7 @@ func resourceFunctionRead(d *schema.ResourceData, meta interface{}) error { return true }) if err != nil { - return err + return fmt.Errorf("reading Lambda Function (%s): %w", d.Id(), err) } d.Set("version", lastVersion) diff --git a/internal/service/lambda/function_event_invoke_config.go b/internal/service/lambda/function_event_invoke_config.go index a1a771b4a5f..f92443e4eae 100644 --- a/internal/service/lambda/function_event_invoke_config.go +++ b/internal/service/lambda/function_event_invoke_config.go @@ -144,7 +144,7 @@ func resourceFunctionEventInvokeConfigCreate(d *schema.ResourceData, meta interf } if err != nil { - return fmt.Errorf("error putting Lambda Function Event Invoke Config (%s): %s", id, err) + return fmt.Errorf("creating Lambda Function Event Invoke Config (%s): %s", id, err) } d.SetId(id) @@ -158,7 +158,7 @@ func resourceFunctionEventInvokeConfigRead(d *schema.ResourceData, meta interfac functionName, qualifier, err := FunctionEventInvokeConfigParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Lambda Function Event Invoke Config (%s): %w", d.Id(), err) } input := &lambda.GetFunctionEventInvokeConfigInput{ @@ -178,7 +178,7 @@ func resourceFunctionEventInvokeConfigRead(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error getting Lambda Function Event Invoke Config (%s): %s", d.Id(), err) + return fmt.Errorf("reading Lambda Function Event Invoke Config (%s): %w", d.Id(), err) } if err := d.Set("destination_config", flattenFunctionEventInvokeConfigDestinationConfig(output.DestinationConfig)); err != nil { @@ -199,7 +199,7 @@ func resourceFunctionEventInvokeConfigUpdate(d *schema.ResourceData, meta interf functionName, qualifier, err := FunctionEventInvokeConfigParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Lambda Function Event Invoke Config (%s): %w", d.Id(), err) } input := &lambda.PutFunctionEventInvokeConfigInput{ @@ -242,7 +242,7 @@ func resourceFunctionEventInvokeConfigUpdate(d *schema.ResourceData, meta interf } if err != nil { - return fmt.Errorf("error putting Lambda Function Event Invoke Config (%s): %s", d.Id(), err) + return fmt.Errorf("updating Lambda Function Event Invoke Config (%s): %s", d.Id(), err) } return resourceFunctionEventInvokeConfigRead(d, meta) @@ -254,7 +254,7 @@ func resourceFunctionEventInvokeConfigDelete(d *schema.ResourceData, meta interf functionName, qualifier, err := FunctionEventInvokeConfigParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Lambda Function Event Invoke Config (%s): %w", d.Id(), err) } input := &lambda.DeleteFunctionEventInvokeConfigInput{ @@ -272,7 +272,7 @@ func resourceFunctionEventInvokeConfigDelete(d *schema.ResourceData, meta interf } if err != nil { - return fmt.Errorf("error putting Lambda Function Event Invoke Config (%s): %s", d.Id(), err) + return fmt.Errorf("deleting Lambda Function Event Invoke Config (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/lambda/invocation_data_source.go b/internal/service/lambda/invocation_data_source.go index 533981d2627..b1c0285a0c2 100644 --- a/internal/service/lambda/invocation_data_source.go +++ b/internal/service/lambda/invocation_data_source.go @@ -56,16 +56,14 @@ func dataSourceInvocationRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("invoking Lambda Function (%s): %w", functionName, err) } if res.FunctionError != nil { - return fmt.Errorf("Lambda function (%s) returned error: (%s)", functionName, string(res.Payload)) + return fmt.Errorf(`invoking Lambda Function (%s): returned error: "%s"`, functionName, string(res.Payload)) } - if err = d.Set("result", string(res.Payload)); err != nil { - return err - } + d.Set("result", string(res.Payload)) d.SetId(fmt.Sprintf("%s_%s_%x", functionName, qualifier, md5.Sum(input))) diff --git a/internal/service/lambda/layer_version_permission.go b/internal/service/lambda/layer_version_permission.go index 67f9fe7fd97..00fd987db7b 100644 --- a/internal/service/lambda/layer_version_permission.go +++ b/internal/service/lambda/layer_version_permission.go @@ -109,7 +109,7 @@ func resourceLayerVersionPermissionRead(d *schema.ResourceData, meta interface{} layerName, versionNumber, err := ResourceLayerVersionPermissionParseId(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Lambda Layer Version Permission (%s): %w", d.Id(), err) } input := &lambda.GetLayerVersionPolicyInput{ @@ -126,13 +126,13 @@ func resourceLayerVersionPermissionRead(d *schema.ResourceData, meta interface{} } if err != nil { - return fmt.Errorf("error reading Lambda Layer Version Permission (%s): %w", d.Id(), err) + return fmt.Errorf("reading Lambda Layer Version Permission (%s): %w", d.Id(), err) } policyDoc := &IAMPolicyDoc{} if err := json.Unmarshal([]byte(aws.StringValue(layerVersionPolicyOutput.Policy)), policyDoc); err != nil { - return err + return fmt.Errorf("reading Lambda Layer Version Permission (%s): %w", d.Id(), err) } d.Set("layer_name", layerName) @@ -194,7 +194,7 @@ func resourceLayerVersionPermissionDelete(d *schema.ResourceData, meta interface layerName, versionNumber, err := ResourceLayerVersionPermissionParseId(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Lambda Layer Version Permission (%s): %w", d.Id(), err) } input := &lambda.RemoveLayerVersionPermissionInput{ diff --git a/internal/service/lambda/permission.go b/internal/service/lambda/permission.go index 9b2870735f5..a9c64740e34 100644 --- a/internal/service/lambda/permission.go +++ b/internal/service/lambda/permission.go @@ -197,7 +197,7 @@ func resourcePermissionRead(d *schema.ResourceData, meta interface{}) error { functionName, err := GetFunctionNameFromARN(statement.Resource) if err != nil { - return err + return fmt.Errorf("reading Lambda Permission (%s/%s): %w", functionName, d.Id(), err) } d.Set("function_name", functionName) diff --git a/internal/service/lambda/provisioned_concurrency_config.go b/internal/service/lambda/provisioned_concurrency_config.go index a5acae0c8ae..91bdadc7f01 100644 --- a/internal/service/lambda/provisioned_concurrency_config.go +++ b/internal/service/lambda/provisioned_concurrency_config.go @@ -83,7 +83,7 @@ func resourceProvisionedConcurrencyConfigRead(d *schema.ResourceData, meta inter functionName, qualifier, err := ProvisionedConcurrencyConfigParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) } input := &lambda.GetProvisionedConcurrencyConfigInput{ @@ -100,7 +100,7 @@ func resourceProvisionedConcurrencyConfigRead(d *schema.ResourceData, meta inter } if err != nil { - return fmt.Errorf("error getting Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) + return fmt.Errorf("reading Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) } d.Set("function_name", functionName) @@ -116,7 +116,7 @@ func resourceProvisionedConcurrencyConfigUpdate(d *schema.ResourceData, meta int functionName, qualifier, err := ProvisionedConcurrencyConfigParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) } input := &lambda.PutProvisionedConcurrencyConfigInput{ @@ -128,11 +128,11 @@ func resourceProvisionedConcurrencyConfigUpdate(d *schema.ResourceData, meta int _, err = conn.PutProvisionedConcurrencyConfig(input) if err != nil { - return fmt.Errorf("error putting Lambda Provisioned Concurrency Config (%s:%s): %s", functionName, qualifier, err) + return fmt.Errorf("updating Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) } if err := waitForProvisionedConcurrencyConfigStatusReady(conn, functionName, qualifier, d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for Lambda Provisioned Concurrency Config (%s) to be ready: %s", d.Id(), err) + return fmt.Errorf("updating Lambda Provisioned Concurrency Config (%s): waiting for completion: %s", d.Id(), err) } return resourceProvisionedConcurrencyConfigRead(d, meta) @@ -144,7 +144,7 @@ func resourceProvisionedConcurrencyConfigDelete(d *schema.ResourceData, meta int functionName, qualifier, err := ProvisionedConcurrencyConfigParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) } input := &lambda.DeleteProvisionedConcurrencyConfigInput{ @@ -159,7 +159,7 @@ func resourceProvisionedConcurrencyConfigDelete(d *schema.ResourceData, meta int } if err != nil { - return fmt.Errorf("error putting Lambda Provisioned Concurrency Config (%s:%s): %s", functionName, qualifier, err) + return fmt.Errorf("deleting Lambda Provisioned Concurrency Config (%s): %s", d.Id(), err) } return nil From 2ae8d9a4f82282142b3effed5fe38e15e2a91a27 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:50:19 -0800 Subject: [PATCH 039/106] Fixes bare errors in `lakeformation` --- internal/service/lakeformation/lf_tag.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/service/lakeformation/lf_tag.go b/internal/service/lakeformation/lf_tag.go index 069c988c81a..8e5b767c20b 100644 --- a/internal/service/lakeformation/lf_tag.go +++ b/internal/service/lakeformation/lf_tag.go @@ -74,7 +74,7 @@ func resourceLFTagCreate(d *schema.ResourceData, meta interface{}) error { _, err := conn.CreateLFTag(input) if err != nil { - return fmt.Errorf("error creating Lake Formation LF-Tag: %w", err) + return fmt.Errorf("creating Lake Formation LF-Tag: %w", err) } d.SetId(fmt.Sprintf("%s:%s", catalogID, tagKey)) @@ -87,7 +87,7 @@ func resourceLFTagRead(d *schema.ResourceData, meta interface{}) error { catalogID, tagKey, err := ReadLFTagID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Lake Formation LF-Tag (%s): %s", d.Id(), err) } input := &lakeformation.GetLFTagInput{ @@ -105,7 +105,7 @@ func resourceLFTagRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Lake Formation LF-Tag: %s", err.Error()) + return fmt.Errorf("reading Lake Formation LF-Tag (%s): %s", d.Id(), err) } d.Set("key", output.TagKey) @@ -120,7 +120,7 @@ func resourceLFTagUpdate(d *schema.ResourceData, meta interface{}) error { catalogID, tagKey, err := ReadLFTagID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Lake Formation LF-Tag (%s): %w", d.Id(), err) } o, n := d.GetChange("values") @@ -144,7 +144,7 @@ func resourceLFTagUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateLFTag(input) if err != nil { - return fmt.Errorf("error updating Lake Formation LF-Tag (%s): %w", d.Id(), err) + return fmt.Errorf("updating Lake Formation LF-Tag (%s): %w", d.Id(), err) } return resourceLFTagRead(d, meta) @@ -155,7 +155,7 @@ func resourceLFTagDelete(d *schema.ResourceData, meta interface{}) error { catalogID, tagKey, err := ReadLFTagID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Lake Formation LF-Tag (%s): %w", d.Id(), err) } input := &lakeformation.DeleteLFTagInput{ @@ -165,7 +165,7 @@ func resourceLFTagDelete(d *schema.ResourceData, meta interface{}) error { _, err = conn.DeleteLFTag(input) if err != nil { - return fmt.Errorf("error deleting Lake Formation LF-Tag (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Lake Formation LF-Tag (%s): %w", d.Id(), err) } return nil From f3b3dfa53cf5d68f10338f9303a5080a32b34b42 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:50:39 -0800 Subject: [PATCH 040/106] Fixes bare errors in `kinesisanalyticsv2` --- .../service/kinesisanalyticsv2/application.go | 30 +++++++++---------- .../application_snapshot.go | 10 +++---- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/internal/service/kinesisanalyticsv2/application.go b/internal/service/kinesisanalyticsv2/application.go index 74f0217a728..8a901cfc466 100644 --- a/internal/service/kinesisanalyticsv2/application.go +++ b/internal/service/kinesisanalyticsv2/application.go @@ -953,7 +953,7 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("error creating Kinesis Analytics v2 Application (%s): %w", applicationName, err) + return fmt.Errorf("creating Kinesis Analytics v2 Application (%s): %w", applicationName, err) } output := outputRaw.(*kinesisanalyticsv2.CreateApplicationOutput) @@ -964,7 +964,7 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { if _, ok := d.GetOk("start_application"); ok { if err := startApplication(conn, expandStartApplicationInput(d), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("creating Kinesis Analytics v2 Application (%s): %w", applicationName, err) } } @@ -1514,11 +1514,11 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("start_application") { if _, ok := d.GetOk("start_application"); ok { if err := startApplication(conn, expandStartApplicationInput(d), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating Kinesis Analytics v2 Application (%s): %w", d.Id(), err) } } else { if err := stopApplication(conn, expandStopApplicationInput(d), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating Kinesis Analytics v2 Application (%s): %w", d.Id(), err) } } } @@ -1531,7 +1531,7 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { createTimestamp, err := time.Parse(time.RFC3339, d.Get("create_timestamp").(string)) if err != nil { - return fmt.Errorf("error parsing create_timestamp: %w", err) + return fmt.Errorf("deleting Kinesis Analytics v2 Application (%s): parsing create_timestamp: %w", d.Id(), err) } applicationName := d.Get("name").(string) @@ -1547,13 +1547,13 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting Kinesis Analytics v2 Application (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Kinesis Analytics v2 Application (%s): %w", d.Id(), err) } _, err = waitApplicationDeleted(conn, applicationName, d.Timeout(schema.TimeoutDelete)) if err != nil { - return fmt.Errorf("error waiting for Kinesis Analytics v2 Application (%s) deletion: %w", d.Id(), err) + return fmt.Errorf("deleting Kinesis Analytics v2 Application (%s): waiting for completion: %w", d.Id(), err) } return nil @@ -1562,13 +1562,13 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { func resourceApplicationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { arn, err := arn.Parse(d.Id()) if err != nil { - return []*schema.ResourceData{}, fmt.Errorf("Error parsing ARN %q: %w", d.Id(), err) + return []*schema.ResourceData{}, fmt.Errorf("parsing ARN %q: %w", d.Id(), err) } // application/ parts := strings.Split(arn.Resource, "/") if len(parts) != 2 { - return []*schema.ResourceData{}, fmt.Errorf("Unexpected ARN format: %q", d.Id()) + return []*schema.ResourceData{}, fmt.Errorf("unexpected ARN format: %q", d.Id()) } d.Set("name", parts[1]) @@ -1582,7 +1582,7 @@ func startApplication(conn *kinesisanalyticsv2.KinesisAnalyticsV2, input *kinesi application, err := FindApplicationDetailByName(conn, applicationName) if err != nil { - return fmt.Errorf("error reading Kinesis Analytics v2 Application (%s): %w", applicationName, err) + return fmt.Errorf("starting application: %w", err) } applicationARN := aws.StringValue(application.ApplicationARN) @@ -1605,11 +1605,11 @@ func startApplication(conn *kinesisanalyticsv2.KinesisAnalyticsV2, input *kinesi log.Printf("[DEBUG] Starting Kinesis Analytics v2 Application (%s): %s", applicationARN, input) if _, err := conn.StartApplication(input); err != nil { - return fmt.Errorf("error starting Kinesis Analytics v2 Application (%s): %w", applicationARN, err) + return fmt.Errorf("starting application: %w", err) } if _, err := waitApplicationStarted(conn, applicationName, timeout); err != nil { - return fmt.Errorf("error waiting for Kinesis Analytics v2 Application (%s) to start: %w", applicationARN, err) + return fmt.Errorf("starting application: waiting for completion: %w", err) } return nil @@ -1621,7 +1621,7 @@ func stopApplication(conn *kinesisanalyticsv2.KinesisAnalyticsV2, input *kinesis application, err := FindApplicationDetailByName(conn, applicationName) if err != nil { - return fmt.Errorf("error reading Kinesis Analytics v2 Application (%s): %w", applicationName, err) + return fmt.Errorf("stopping application: %w", err) } applicationARN := aws.StringValue(application.ApplicationARN) @@ -1634,11 +1634,11 @@ func stopApplication(conn *kinesisanalyticsv2.KinesisAnalyticsV2, input *kinesis log.Printf("[DEBUG] Stopping Kinesis Analytics v2 Application (%s): %s", applicationARN, input) if _, err := conn.StopApplication(input); err != nil { - return fmt.Errorf("error stopping Kinesis Analytics v2 Application (%s): %w", applicationARN, err) + return fmt.Errorf("stopping application: %w", err) } if _, err := waitApplicationStopped(conn, applicationName, timeout); err != nil { - return fmt.Errorf("error waiting for Kinesis Analytics v2 Application (%s) to stop: %w", applicationARN, err) + return fmt.Errorf("stopping application: waiting for completion: %w", err) } return nil diff --git a/internal/service/kinesisanalyticsv2/application_snapshot.go b/internal/service/kinesisanalyticsv2/application_snapshot.go index 35af961dd6e..cd372bb5ee1 100644 --- a/internal/service/kinesisanalyticsv2/application_snapshot.go +++ b/internal/service/kinesisanalyticsv2/application_snapshot.go @@ -99,7 +99,7 @@ func resourceApplicationSnapshotRead(d *schema.ResourceData, meta interface{}) e applicationName, snapshotName, err := applicationSnapshotParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Kinesis Analytics v2 Application Snapshot (%s): %w", d.Id(), err) } snapshot, err := FindSnapshotDetailsByApplicationAndSnapshotNames(conn, applicationName, snapshotName) @@ -111,7 +111,7 @@ func resourceApplicationSnapshotRead(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("error reading Kinesis Analytics v2 Application Snapshot (%s): %w", d.Id(), err) + return fmt.Errorf("reading Kinesis Analytics v2 Application Snapshot (%s): %w", d.Id(), err) } d.Set("application_name", applicationName) @@ -128,7 +128,7 @@ func resourceApplicationSnapshotDelete(d *schema.ResourceData, meta interface{}) applicationName, snapshotName, err := applicationSnapshotParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Kinesis Analytics v2 Application Snapshot (%s): %w", d.Id(), err) } snapshotCreationTimestamp, err := time.Parse(time.RFC3339, d.Get("snapshot_creation_timestamp").(string)) @@ -152,13 +152,13 @@ func resourceApplicationSnapshotDelete(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error deleting Kinesis Analytics v2 Application Snapshot (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Kinesis Analytics v2 Application Snapshot (%s): %w", d.Id(), err) } _, err = waitSnapshotDeleted(conn, applicationName, snapshotName, d.Timeout(schema.TimeoutDelete)) if err != nil { - return fmt.Errorf("error waiting for Kinesis Analytics v2 Application Snapshot (%s) deletion: %w", d.Id(), err) + return fmt.Errorf("deleting Kinesis Analytics v2 Application Snapshot (%s): waiting for completion: %w", d.Id(), err) } return nil From 5a75123bb8de3571ef8c353c1de697fa0759eee3 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:50:50 -0800 Subject: [PATCH 041/106] Fixes bare errors in `kinesisanalytics` --- internal/service/kinesisanalytics/application.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/kinesisanalytics/application.go b/internal/service/kinesisanalytics/application.go index fa1b2885f22..f6e0ce50599 100644 --- a/internal/service/kinesisanalytics/application.go +++ b/internal/service/kinesisanalytics/application.go @@ -641,7 +641,7 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("error creating Kinesis Analytics Application (%s): %w", applicationName, err) + return fmt.Errorf("creating Kinesis Analytics Application (%s): %w", applicationName, err) } applicationSummary := outputRaw.(*kinesisanalytics.CreateApplicationOutput).ApplicationSummary @@ -690,7 +690,7 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { err = startApplication(conn, application, inputStartingPosition) if err != nil { - return err + return fmt.Errorf("creating Kinesis Analytics Application (%s): %w", applicationName, err) } } else { log.Printf("[DEBUG] Kinesis Analytics Application (%s) has no inputs", d.Id()) @@ -1141,7 +1141,7 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { err = startApplication(conn, application, inputStartingPosition) if err != nil { - return err + return fmt.Errorf("updating Kinesis Analytics Application (%s): %w", d.Id(), err) } } else { log.Printf("[DEBUG] Kinesis Analytics Application (%s) has no inputs", d.Id()) @@ -1150,7 +1150,7 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { err = stopApplication(conn, application) if err != nil { - return err + return fmt.Errorf("updating Kinesis Analytics Application (%s): %w", d.Id(), err) } } } @@ -1237,11 +1237,11 @@ func startApplication(conn *kinesisanalytics.KinesisAnalytics, application *kine log.Printf("[DEBUG] Starting Kinesis Analytics Application (%s): %s", applicationARN, input) if _, err := conn.StartApplication(input); err != nil { - return fmt.Errorf("error starting Kinesis Analytics Application (%s): %w", applicationARN, err) + return fmt.Errorf("starting application: %w", err) } if _, err := waitApplicationStarted(conn, applicationName); err != nil { - return fmt.Errorf("error waiting for Kinesis Analytics Application (%s) to start: %w", applicationARN, err) + return fmt.Errorf("starting application: waiting for completion: %w", err) } return nil @@ -1263,11 +1263,11 @@ func stopApplication(conn *kinesisanalytics.KinesisAnalytics, application *kines log.Printf("[DEBUG] Stopping Kinesis Analytics Application (%s): %s", applicationARN, input) if _, err := conn.StopApplication(input); err != nil { - return fmt.Errorf("error stopping Kinesis Analytics Application (%s): %w", applicationARN, err) + return fmt.Errorf("stopping application: %w", err) } if _, err := waitApplicationStopped(conn, applicationName); err != nil { - return fmt.Errorf("error waiting for Kinesis Analytics Application (%s) to stop: %w", applicationARN, err) + return fmt.Errorf("stopping application: waiting for completion: %w", err) } return nil From 4e1647a5ef900b158e4014000b6d9ca9997cb354 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Tue, 10 Jan 2023 16:51:10 -0800 Subject: [PATCH 042/106] Fixes bare errors in `iot` --- internal/service/iot/policy.go | 4 ++-- internal/service/iot/thing_group_membership.go | 8 ++++---- internal/service/iot/thing_type.go | 16 +++++++--------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/internal/service/iot/policy.go b/internal/service/iot/policy.go index 6e4b474d998..d6b7f7b591a 100644 --- a/internal/service/iot/policy.go +++ b/internal/service/iot/policy.go @@ -89,7 +89,7 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading IoT Policy (%s): %s", d.Id(), err) + return fmt.Errorf("reading IoT Policy (%s): %s", d.Id(), err) } d.Set("arn", out.PolicyArn) @@ -98,7 +98,7 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(out.PolicyDocument)) if err != nil { - return err + return fmt.Errorf("reading IoT Policy (%s): %s", d.Id(), err) } d.Set("policy", policyToSet) diff --git a/internal/service/iot/thing_group_membership.go b/internal/service/iot/thing_group_membership.go index a851996985e..21b67701f3f 100644 --- a/internal/service/iot/thing_group_membership.go +++ b/internal/service/iot/thing_group_membership.go @@ -75,7 +75,7 @@ func resourceThingGroupMembershipRead(d *schema.ResourceData, meta interface{}) thingGroupName, thingName, err := ThingGroupMembershipParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IoT Thing Group Membership (%s): %w", d.Id(), err) } err = FindThingGroupMembership(conn, thingGroupName, thingName) @@ -87,7 +87,7 @@ func resourceThingGroupMembershipRead(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error reading IoT Thing Group Membership (%s): %w", d.Id(), err) + return fmt.Errorf("reading IoT Thing Group Membership (%s): %w", d.Id(), err) } d.Set("thing_group_name", thingGroupName) @@ -102,7 +102,7 @@ func resourceThingGroupMembershipDelete(d *schema.ResourceData, meta interface{} thingGroupName, thingName, err := ThingGroupMembershipParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IoT Thing Group Membership (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting IoT Thing Group Membership: %s", d.Id()) @@ -116,7 +116,7 @@ func resourceThingGroupMembershipDelete(d *schema.ResourceData, meta interface{} } if err != nil { - return fmt.Errorf("error removing IoT Thing (%s) from IoT Thing Group (%s): %w", thingName, thingGroupName, err) + return fmt.Errorf("deleting IoT Thing Group Membership (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/iot/thing_type.go b/internal/service/iot/thing_type.go index edac2afb0f3..d3876a58c05 100644 --- a/internal/service/iot/thing_type.go +++ b/internal/service/iot/thing_type.go @@ -106,7 +106,7 @@ func resourceThingTypeCreate(d *schema.ResourceData, meta interface{}) error { out, err := conn.CreateThingType(params) if err != nil { - return err + return fmt.Errorf("creating IoT Thing Type (%s): %w", d.Get("name").(string), err) } d.SetId(aws.StringValue(out.ThingTypeName)) @@ -117,11 +117,10 @@ func resourceThingTypeCreate(d *schema.ResourceData, meta interface{}) error { UndoDeprecate: aws.Bool(false), } - log.Printf("[DEBUG] Deprecating IoT Thing Type: %s", params) _, err := conn.DeprecateThingType(params) if err != nil { - return err + return fmt.Errorf("creating IoT Thing Type (%s): deprecating Thing Type: %w", d.Get("name").(string), err) } } @@ -142,10 +141,10 @@ func resourceThingTypeRead(d *schema.ResourceData, meta interface{}) error { if err != nil { if tfawserr.ErrCodeEquals(err, iot.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] IoT Thing Type %q not found, removing from state", d.Id()) + log.Printf("[WARN] IoT Thing Type (%s) not found, removing from state", d.Id()) d.SetId("") } - return err + return fmt.Errorf("reading IoT Thing Type (%s): %w", d.Id(), err) } if out.ThingTypeMetadata != nil { @@ -190,7 +189,7 @@ func resourceThingTypeUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeprecateThingType(params) if err != nil { - return err + return fmt.Errorf("updating IoT Thing Type (%s): deprecating Thing Type: %w", d.Id(), err) } } @@ -217,13 +216,12 @@ func resourceThingTypeDelete(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeprecateThingType(deprecateParams) if err != nil { - return err + return fmt.Errorf("deleting IoT Thing Type (%s): deprecating Thing Type: %s", d.Id(), err) } deleteParams := &iot.DeleteThingTypeInput{ ThingTypeName: aws.String(d.Id()), } - log.Printf("[DEBUG] Deleting IoT Thing Type: %s", deleteParams) err = resource.Retry(6*time.Minute, func() *resource.RetryError { _, err := conn.DeleteThingType(deleteParams) @@ -251,7 +249,7 @@ func resourceThingTypeDelete(d *schema.ResourceData, meta interface{}) error { } } if err != nil { - return fmt.Errorf("Error deleting IOT thing type: %s", err) + return fmt.Errorf("deleting IoT Thing Type (%s): %s", d.Id(), err) } return nil } From 1271cd2293d2a94a384cb721bdeb0066c6bf2bc0 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 11:41:23 -0800 Subject: [PATCH 043/106] Fixes bare errors in `iam` --- internal/service/iam/access_key.go | 36 ++++------- .../service/iam/account_alias_data_source.go | 6 +- internal/service/iam/encryption.go | 4 +- internal/service/iam/group.go | 20 ++---- internal/service/iam/group_membership.go | 51 ++++++--------- internal/service/iam/group_policy.go | 14 ++-- internal/service/iam/instance_profile.go | 34 ++++------ internal/service/iam/policy.go | 19 +++--- internal/service/iam/policy_attachment.go | 4 +- .../iam/policy_document_data_source.go | 16 ++--- internal/service/iam/role.go | 40 ++++++------ internal/service/iam/role_policy.go | 22 +++---- internal/service/iam/server_certificate.go | 2 +- .../iam/server_certificate_data_source.go | 4 +- internal/service/iam/service_linked_role.go | 21 +++--- .../iam/service_specific_credential.go | 4 +- internal/service/iam/signing_certificate.go | 12 ++-- internal/service/iam/sweep.go | 2 +- internal/service/iam/user.go | 2 +- internal/service/iam/user_group_membership.go | 64 +++++++++++-------- internal/service/iam/user_login_profile.go | 8 +-- internal/service/iam/user_policy.go | 28 ++++---- 22 files changed, 194 insertions(+), 219 deletions(-) diff --git a/internal/service/iam/access_key.go b/internal/service/iam/access_key.go index 34c1a9a16ac..fe1df04be91 100644 --- a/internal/service/iam/access_key.go +++ b/internal/service/iam/access_key.go @@ -101,17 +101,15 @@ func ResourceAccessKey() *schema.Resource { func resourceAccessKeyCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).IAMConn() + username := d.Get("user").(string) + request := &iam.CreateAccessKeyInput{ - UserName: aws.String(d.Get("user").(string)), + UserName: aws.String(username), } createResp, err := conn.CreateAccessKey(request) if err != nil { - return fmt.Errorf( - "Error creating access key for user %s: %s", - *request.UserName, - err, - ) + return fmt.Errorf("creating IAM Access Key (%s): %s", username, err) } d.SetId(aws.StringValue(createResp.AccessKey.AccessKeyId)) @@ -129,11 +127,11 @@ func resourceAccessKeyCreate(d *schema.ResourceData, meta interface{}) error { pgpKey := v.(string) encryptionKey, err := retrieveGPGKey(pgpKey) if err != nil { - return err + return fmt.Errorf("creating IAM Access Key (%s): %s", username, err) } fingerprint, encrypted, err := encryptValue(encryptionKey, *createResp.AccessKey.SecretAccessKey, "IAM Access Key Secret") if err != nil { - return err + return fmt.Errorf("creating IAM Access Key (%s): %s", username, err) } d.Set("key_fingerprint", fingerprint) @@ -141,18 +139,14 @@ func resourceAccessKeyCreate(d *schema.ResourceData, meta interface{}) error { _, encrypted, err = encryptValue(encryptionKey, sesSMTPPasswordV4, "SES SMTP password") if err != nil { - return err + return fmt.Errorf("creating IAM Access Key (%s): %s", username, err) } d.Set("encrypted_ses_smtp_password_v4", encrypted) } else { - if err := d.Set("secret", createResp.AccessKey.SecretAccessKey); err != nil { - return err - } + d.Set("secret", createResp.AccessKey.SecretAccessKey) - if err := d.Set("ses_smtp_password_v4", sesSMTPPasswordV4); err != nil { - return err - } + d.Set("ses_smtp_password_v4", sesSMTPPasswordV4) } if v, ok := d.GetOk("status"); ok && v.(string) == iam.StatusTypeInactive { @@ -191,7 +185,7 @@ func resourceAccessKeyRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error reading IAM access key: %w", err) + return fmt.Errorf("error reading IAM Access Key (%s): %s", d.Id(), err) } d.SetId(aws.StringValue(key.AccessKeyId)) @@ -228,7 +222,7 @@ func resourceAccessKeyUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("status") { if err := resourceAccessKeyStatusUpdate(conn, d); err != nil { - return err + return fmt.Errorf("updating IAM Access Key (%s): %s", d.Id(), err) } } @@ -244,7 +238,7 @@ func resourceAccessKeyDelete(d *schema.ResourceData, meta interface{}) error { } if _, err := conn.DeleteAccessKey(request); err != nil { - return fmt.Errorf("Error deleting access key %s: %s", d.Id(), err) + return fmt.Errorf("deleting IAM Access Key (%s): %s", d.Id(), err) } return nil } @@ -256,10 +250,8 @@ func resourceAccessKeyStatusUpdate(conn *iam.IAM, d *schema.ResourceData) error UserName: aws.String(d.Get("user").(string)), } - if _, err := conn.UpdateAccessKey(request); err != nil { - return fmt.Errorf("Error updating access key %s: %s", d.Id(), err) - } - return nil + _, err := conn.UpdateAccessKey(request) + return err } func hmacSignature(key []byte, value []byte) ([]byte, error) { diff --git a/internal/service/iam/account_alias_data_source.go b/internal/service/iam/account_alias_data_source.go index 40f2b092b37..d37e3c7c619 100644 --- a/internal/service/iam/account_alias_data_source.go +++ b/internal/service/iam/account_alias_data_source.go @@ -1,6 +1,7 @@ package iam import ( + "errors" "fmt" "log" @@ -31,17 +32,16 @@ func dataSourceAccountAliasRead(d *schema.ResourceData, meta interface{}) error req := &iam.ListAccountAliasesInput{} resp, err := conn.ListAccountAliases(req) if err != nil { - return err + return fmt.Errorf("reading IAM Account Alias: %w", err) } // 'AccountAliases': [] if there is no alias. if resp == nil || len(resp.AccountAliases) == 0 { - return fmt.Errorf("no IAM account alias found") + return errors.New("reading IAM Account Alias: empty result") } alias := aws.StringValue(resp.AccountAliases[0]) d.SetId(alias) - log.Printf("[DEBUG] Setting AWS IAM Account Alias to %s.", alias) d.Set("account_alias", alias) return nil diff --git a/internal/service/iam/encryption.go b/internal/service/iam/encryption.go index 521fa53355f..0dc89cd2194 100644 --- a/internal/service/iam/encryption.go +++ b/internal/service/iam/encryption.go @@ -18,7 +18,7 @@ func retrieveGPGKey(pgpKey string) (string, error) { if strings.HasPrefix(pgpKey, keybasePrefix) { publicKeys, err := pgpkeys.FetchKeybasePubkeys([]string{pgpKey}) if err != nil { - return "", fmt.Errorf("Error retrieving Public Key for %s: %w", pgpKey, err) + return "", fmt.Errorf("retrieving Public Key (%s): %w", pgpKey, err) } encryptionKey = publicKeys[pgpKey] } @@ -32,7 +32,7 @@ func encryptValue(encryptionKey, value, description string) (string, string, err fingerprints, encryptedValue, err := pgpkeys.EncryptShares([][]byte{[]byte(value)}, []string{encryptionKey}) if err != nil { - return "", "", fmt.Errorf("Error encrypting %s: %w", description, err) + return "", "", fmt.Errorf("encrypting %s: %w", description, err) } return fingerprints[0], base64.StdEncoding.EncodeToString(encryptedValue[0]), nil diff --git a/internal/service/iam/group.go b/internal/service/iam/group.go index 70336581371..ff8bd816fd2 100644 --- a/internal/service/iam/group.go +++ b/internal/service/iam/group.go @@ -106,27 +106,19 @@ func resourceGroupRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading IAM Group (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Group (%s): %w", d.Id(), err) } if getResp == nil || getResp.Group == nil { - return fmt.Errorf("error reading IAM Group (%s): empty response", d.Id()) + return fmt.Errorf("reading IAM Group (%s): empty response", d.Id()) } group := getResp.Group - if err := d.Set("name", group.GroupName); err != nil { - return err - } - if err := d.Set("arn", group.Arn); err != nil { - return err - } - if err := d.Set("path", group.Path); err != nil { - return err - } - if err := d.Set("unique_id", group.GroupId); err != nil { - return err - } + d.Set("name", group.GroupName) + d.Set("arn", group.Arn) + d.Set("path", group.Path) + d.Set("unique_id", group.GroupId) return nil } diff --git a/internal/service/iam/group_membership.go b/internal/service/iam/group_membership.go index 60b7c5d5390..7a25201f30d 100644 --- a/internal/service/iam/group_membership.go +++ b/internal/service/iam/group_membership.go @@ -48,13 +48,14 @@ func resourceGroupMembershipCreate(d *schema.ResourceData, meta interface{}) err conn := meta.(*conns.AWSClient).IAMConn() group := d.Get("group").(string) - userList := flex.ExpandStringSet(d.Get("users").(*schema.Set)) + userList := flex.ExpandStringValueSet(d.Get("users").(*schema.Set)) if err := addUsersToGroup(conn, userList, group); err != nil { - return err + return fmt.Errorf("creating IAM Group Membership (%s): %w", d.Get("name").(string), err) } d.SetId(d.Get("name").(string)) + return resourceGroupMembershipRead(d, meta) } @@ -113,11 +114,11 @@ func resourceGroupMembershipRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading IAM Group Membership (%s): %w", group, err) + return fmt.Errorf("reading IAM Group Membership (%s): %w", group, err) } if err := d.Set("users", ul); err != nil { - return fmt.Errorf("Error setting user list from IAM Group Membership (%s), error: %s", group, err) + return fmt.Errorf("setting user list from IAM Group Membership (%s): %s", group, err) } return nil @@ -139,15 +140,15 @@ func resourceGroupMembershipUpdate(d *schema.ResourceData, meta interface{}) err os := o.(*schema.Set) ns := n.(*schema.Set) - remove := flex.ExpandStringSet(os.Difference(ns)) - add := flex.ExpandStringSet(ns.Difference(os)) + remove := flex.ExpandStringValueSet(os.Difference(ns)) + add := flex.ExpandStringValueSet(ns.Difference(os)) if err := removeUsersFromGroup(conn, remove, group); err != nil { - return err + return fmt.Errorf("updating IAM Group Membership (%s): %w", d.Get("name").(string), err) } if err := addUsersToGroup(conn, add, group); err != nil { - return err + return fmt.Errorf("updating IAM Group Membership (%s): %w", d.Get("name").(string), err) } } @@ -156,39 +157,27 @@ func resourceGroupMembershipUpdate(d *schema.ResourceData, meta interface{}) err func resourceGroupMembershipDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).IAMConn() - userList := flex.ExpandStringSet(d.Get("users").(*schema.Set)) + userList := flex.ExpandStringValueSet(d.Get("users").(*schema.Set)) group := d.Get("group").(string) - err := removeUsersFromGroup(conn, userList, group) - return err + if err := removeUsersFromGroup(conn, userList, group); err != nil { + return fmt.Errorf("deleting IAM Group Membership (%s): %w", d.Get("name").(string), err) + } + return nil } -func removeUsersFromGroup(conn *iam.IAM, users []*string, group string) error { - for _, u := range users { - _, err := conn.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{ - UserName: u, - GroupName: aws.String(group), - }) - - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { - return nil - } - - if err != nil { +func removeUsersFromGroup(conn *iam.IAM, users []string, group string) error { + for _, user := range users { + if err := removeUserFromGroup(conn, user, group); err != nil { return err } } return nil } -func addUsersToGroup(conn *iam.IAM, users []*string, group string) error { - for _, u := range users { - _, err := conn.AddUserToGroup(&iam.AddUserToGroupInput{ - UserName: u, - GroupName: aws.String(group), - }) - - if err != nil { +func addUsersToGroup(conn *iam.IAM, users []string, group string) error { + for _, user := range users { + if err := addUserToGroup(conn, user, group); err != nil { return err } } diff --git a/internal/service/iam/group_policy.go b/internal/service/iam/group_policy.go index bd1490a4ff0..c748bc662fb 100644 --- a/internal/service/iam/group_policy.go +++ b/internal/service/iam/group_policy.go @@ -99,7 +99,7 @@ func resourceGroupPolicyRead(d *schema.ResourceData, meta interface{}) error { group, name, err := GroupPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IAM Group Policy (%s): %w", d.Id(), err) } request := &iam.GetGroupPolicyInput{ @@ -136,21 +136,21 @@ func resourceGroupPolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading IAM Group Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Group Policy (%s): %w", d.Id(), err) } if getResp == nil || getResp.PolicyDocument == nil { - return fmt.Errorf("error reading IAM Group Policy (%s): empty response", d.Id()) + return fmt.Errorf("reading IAM Group Policy (%s): empty response", d.Id()) } policy, err := url.QueryUnescape(*getResp.PolicyDocument) if err != nil { - return err + return fmt.Errorf("reading IAM Group Policy (%s): %w", d.Id(), err) } policyToSet, err := verify.LegacyPolicyToSet(d.Get("policy").(string), policy) if err != nil { - return fmt.Errorf("while setting policy (%s), encountered: %w", policyToSet, err) + return fmt.Errorf("reading IAM Group Policy (%s): setting policy: %w", d.Id(), err) } d.Set("policy", policyToSet) @@ -171,7 +171,7 @@ func resourceGroupPolicyDelete(d *schema.ResourceData, meta interface{}) error { group, name, err := GroupPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IAM Group Policy (%s): %w", d.Id(), err) } request := &iam.DeleteGroupPolicyInput{ @@ -183,7 +183,7 @@ func resourceGroupPolicyDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { return nil } - return fmt.Errorf("Error deleting IAM group policy %s: %s", d.Id(), err) + return fmt.Errorf("deleting IAM Group Policy (%s): %w", d.Id(), err) } return nil } diff --git a/internal/service/iam/instance_profile.go b/internal/service/iam/instance_profile.go index 95737f93e8c..aa05685fe72 100644 --- a/internal/service/iam/instance_profile.go +++ b/internal/service/iam/instance_profile.go @@ -116,7 +116,7 @@ func resourceInstanceProfileCreate(d *schema.ResourceData, meta interface{}) err } if err != nil { - return fmt.Errorf("creating IAM instance profile %s: %w", name, err) + return fmt.Errorf("creating IAM Instance Profile (%s): %w", name, err) } waiterRequest := &iam.GetInstanceProfileInput{ @@ -194,7 +194,7 @@ func instanceProfileRemoveAllRoles(d *schema.ResourceData, conn *iam.IAM) error if role, ok := d.GetOk("role"); ok { err := instanceProfileRemoveRole(conn, d.Id(), role.(string)) if err != nil { - return fmt.Errorf("removing role %s from IAM instance profile %s: %w", role, d.Id(), err) + return fmt.Errorf("removing role (%s): %w", role, err) } } @@ -210,14 +210,14 @@ func resourceInstanceProfileUpdate(d *schema.ResourceData, meta interface{}) err if oldRole.(string) != "" { err := instanceProfileRemoveRole(conn, d.Id(), oldRole.(string)) if err != nil { - return fmt.Errorf("removing role %s to IAM instance profile %s: %w", oldRole.(string), d.Id(), err) + return fmt.Errorf("removing role %s to IAM Instance Profile (%s): %w", oldRole.(string), d.Id(), err) } } if newRole.(string) != "" { err := instanceProfileAddRole(conn, d.Id(), newRole.(string)) if err != nil { - return fmt.Errorf("adding role %s to IAM instance profile %s: %w", newRole.(string), d.Id(), err) + return fmt.Errorf("adding role %s to IAM Instance Profile (%s): %w", newRole.(string), d.Id(), err) } } } @@ -255,7 +255,7 @@ func resourceInstanceProfileRead(d *schema.ResourceData, meta interface{}) error return nil } if err != nil { - return fmt.Errorf("reading IAM instance profile %s: %w", d.Id(), err) + return fmt.Errorf("reading IAM Instance Profile (%s): %w", d.Id(), err) } instanceProfile := result.InstanceProfile @@ -270,10 +270,10 @@ func resourceInstanceProfileRead(d *schema.ResourceData, meta interface{}) error if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { err := instanceProfileRemoveRole(conn, d.Id(), roleName) if err != nil { - return fmt.Errorf("removing role %s to IAM instance profile %s: %w", roleName, d.Id(), err) + return fmt.Errorf("removing role %s to IAM Instance Profile (%s): %w", roleName, d.Id(), err) } } - return fmt.Errorf("reading IAM Role %s attached to IAM Instance Profile %s: %w", roleName, d.Id(), err) + return fmt.Errorf("reading IAM Role %s attached to IAM Instance Profile (%s): %w", roleName, d.Id(), err) } } @@ -284,7 +284,7 @@ func resourceInstanceProfileDelete(d *schema.ResourceData, meta interface{}) err conn := meta.(*conns.AWSClient).IAMConn() if err := instanceProfileRemoveAllRoles(d, conn); err != nil { - return err + return fmt.Errorf("deleting IAM Instance Profile (%s): %w", d.Id(), err) } request := &iam.DeleteInstanceProfileInput{ @@ -295,7 +295,7 @@ func resourceInstanceProfileDelete(d *schema.ResourceData, meta interface{}) err if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { return nil } - return fmt.Errorf("deleting IAM instance profile %s: %w", d.Id(), err) + return fmt.Errorf("deleting IAM Instance Profile (%s): %w", d.Id(), err) } return nil @@ -306,18 +306,10 @@ func instanceProfileReadResult(d *schema.ResourceData, result *iam.InstanceProfi ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig d.SetId(aws.StringValue(result.InstanceProfileName)) - if err := d.Set("name", result.InstanceProfileName); err != nil { - return err - } - if err := d.Set("arn", result.Arn); err != nil { - return err - } - if err := d.Set("create_date", result.CreateDate.Format(time.RFC3339)); err != nil { - return err - } - if err := d.Set("path", result.Path); err != nil { - return err - } + d.Set("name", result.InstanceProfileName) + d.Set("arn", result.Arn) + d.Set("create_date", result.CreateDate.Format(time.RFC3339)) + d.Set("path", result.Path) d.Set("unique_id", result.InstanceProfileId) if result.Roles != nil && len(result.Roles) > 0 { diff --git a/internal/service/iam/policy.go b/internal/service/iam/policy.go index 4f760783eb2..c23714ca1d4 100644 --- a/internal/service/iam/policy.go +++ b/internal/service/iam/policy.go @@ -277,7 +277,7 @@ func resourcePolicyUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChangesExcept("tags", "tags_all") { if err := policyPruneVersions(d.Id(), conn); err != nil { - return err + return fmt.Errorf("updating IAM policy %s: pruning versions: %w", d.Id(), err) } policy, err := structure.NormalizeJsonString(d.Get("policy").(string)) @@ -292,7 +292,7 @@ func resourcePolicyUpdate(d *schema.ResourceData, meta interface{}) error { } if _, err := conn.CreatePolicyVersion(request); err != nil { - return fmt.Errorf("error updating IAM policy %s: %w", d.Id(), err) + return fmt.Errorf("updating IAM policy %s: %w", d.Id(), err) } } @@ -318,8 +318,8 @@ func resourcePolicyUpdate(d *schema.ResourceData, meta interface{}) error { func resourcePolicyDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).IAMConn() - if err := PolicyDeleteNondefaultVersions(d.Id(), conn); err != nil { - return err + if err := policyDeleteNonDefaultVersions(d.Id(), conn); err != nil { + return fmt.Errorf("deleting IAM policy (%s): deleting non-default versions: %w", d.Id(), err) } request := &iam.DeletePolicyInput{ @@ -333,7 +333,7 @@ func resourcePolicyDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting IAM policy %s: %w", d.Id(), err) + return fmt.Errorf("deleting IAM policy (%s): %w", d.Id(), err) } return nil @@ -367,18 +367,17 @@ func policyPruneVersions(arn string, conn *iam.IAM) error { } } - err1 := policyDeleteVersion(arn, aws.StringValue(oldestVersion.VersionId), conn) - return err1 + return policyDeleteVersion(arn, aws.StringValue(oldestVersion.VersionId), conn) } -func PolicyDeleteNondefaultVersions(arn string, conn *iam.IAM) error { +func policyDeleteNonDefaultVersions(arn string, conn *iam.IAM) error { versions, err := policyListVersions(arn, conn) if err != nil { return err } for _, version := range versions { - if *version.IsDefaultVersion { + if aws.BoolValue(version.IsDefaultVersion) { continue } if err := policyDeleteVersion(arn, aws.StringValue(version.VersionId), conn); err != nil { @@ -397,7 +396,7 @@ func policyDeleteVersion(arn, versionID string, conn *iam.IAM) error { _, err := conn.DeletePolicyVersion(request) if err != nil { - return fmt.Errorf("Error deleting version %s from IAM policy %s: %w", versionID, arn, err) + return fmt.Errorf("deleting policy version (%s): %w", versionID, err) } return nil } diff --git a/internal/service/iam/policy_attachment.go b/internal/service/iam/policy_attachment.go index 2e2bacf6bae..150beaaa7c8 100644 --- a/internal/service/iam/policy_attachment.go +++ b/internal/service/iam/policy_attachment.go @@ -99,7 +99,7 @@ func resourcePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) erro d.SetId("") return nil } - return fmt.Errorf("error reading IAM Policy Attachment (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Policy Attachment (%s): %w", d.Id(), err) } ul := make([]string, 0) @@ -124,7 +124,7 @@ func resourcePolicyAttachmentRead(d *schema.ResourceData, meta interface{}) erro return true }) if err != nil { - return err + return fmt.Errorf("reading IAM Policy Attachment (%s): %w", d.Id(), err) } userErr := d.Set("users", ul) diff --git a/internal/service/iam/policy_document_data_source.go b/internal/service/iam/policy_document_data_source.go index f920a7f126d..3e808f85294 100644 --- a/internal/service/iam/policy_document_data_source.go +++ b/internal/service/iam/policy_document_data_source.go @@ -129,7 +129,7 @@ func dataSourcePolicyDocumentRead(d *schema.ResourceData, meta interface{}) erro if v, ok := d.GetOk("source_json"); ok { if err := json.Unmarshal([]byte(v.(string)), mergedDoc); err != nil { - return err + return fmt.Errorf("writing IAM Policy Document: %w", err) } } @@ -150,14 +150,14 @@ func dataSourcePolicyDocumentRead(d *schema.ResourceData, meta interface{}) erro sourceDoc := &IAMPolicyDoc{} if err := json.Unmarshal([]byte(sourceJSON.(string)), sourceDoc); err != nil { - return err + return fmt.Errorf("writing IAM Policy Document: merging source document %d: %w", sourceJSONIndex, err) } // assure all statements in sourceDoc are unique before merging for stmtIndex, stmt := range sourceDoc.Statements { if stmt.Sid != "" { if _, sidExists := sidMap[stmt.Sid]; sidExists { - return fmt.Errorf("duplicate Sid (%s) in source_policy_documents (item %d; statement %d). Remove the Sid or ensure Sids are unique.", stmt.Sid, sourceJSONIndex, stmtIndex) + return fmt.Errorf("writing IAM Policy Document: merging source document %d: duplicate Sid (%s) in source_policy_documents (statement %d). Remove the Sid or ensure Sids are unique.", sourceJSONIndex, stmt.Sid, stmtIndex) } sidMap[stmt.Sid] = struct{}{} } @@ -189,7 +189,7 @@ func dataSourcePolicyDocumentRead(d *schema.ResourceData, meta interface{}) erro if sid, ok := cfgStmt["sid"]; ok { if _, ok := sidMap[sid.(string)]; ok { - return fmt.Errorf("duplicate Sid (%s). Remove the Sid or ensure the Sid is unique.", sid.(string)) + return fmt.Errorf("writing IAM Policy Document: duplicate Sid (%s). Remove the Sid or ensure the Sid is unique.", sid.(string)) } stmt.Sid = sid.(string) if len(stmt.Sid) > 0 { @@ -258,13 +258,13 @@ func dataSourcePolicyDocumentRead(d *schema.ResourceData, meta interface{}) erro // merge override_policy_documents policies into mergedDoc in order specified if v, ok := d.GetOk("override_policy_documents"); ok && len(v.([]interface{})) > 0 { - for _, overrideJSON := range v.([]interface{}) { + for overrideJSONIndex, overrideJSON := range v.([]interface{}) { if overrideJSON == nil { continue } overrideDoc := &IAMPolicyDoc{} if err := json.Unmarshal([]byte(overrideJSON.(string)), overrideDoc); err != nil { - return err + return fmt.Errorf("writing IAM Policy Document: merging override document %d: %w", overrideJSONIndex, err) } mergedDoc.Merge(overrideDoc) @@ -275,7 +275,7 @@ func dataSourcePolicyDocumentRead(d *schema.ResourceData, meta interface{}) erro if v, ok := d.GetOk("override_json"); ok { overrideDoc := &IAMPolicyDoc{} if err := json.Unmarshal([]byte(v.(string)), overrideDoc); err != nil { - return err + return fmt.Errorf("writing IAM Policy Document: merging override JSON: %w", err) } mergedDoc.Merge(overrideDoc) @@ -284,7 +284,7 @@ func dataSourcePolicyDocumentRead(d *schema.ResourceData, meta interface{}) erro jsonDoc, err := json.MarshalIndent(mergedDoc, "", " ") if err != nil { // should never happen if the above code is correct - return err + return fmt.Errorf("writing IAM Policy Document: formatting JSON: %w", err) } jsonString := string(jsonDoc) diff --git a/internal/service/iam/role.go b/internal/service/iam/role.go index 1a6794beb5c..ee7b1412fc8 100644 --- a/internal/service/iam/role.go +++ b/internal/service/iam/role.go @@ -214,7 +214,7 @@ func resourceRoleCreate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("failed creating IAM Role (%s): %w", name, err) + return fmt.Errorf("creating IAM Role (%s): %w", name, err) } roleName := aws.StringValue(output.Role.RoleName) @@ -222,14 +222,14 @@ func resourceRoleCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("inline_policy"); ok && v.(*schema.Set).Len() > 0 { policies := expandRoleInlinePolicies(roleName, v.(*schema.Set).List()) if err := addRoleInlinePolicies(policies, meta); err != nil { - return err + return fmt.Errorf("creating IAM Role (%s): %w", name, err) } } if v, ok := d.GetOk("managed_policy_arns"); ok && v.(*schema.Set).Len() > 0 { managedPolicies := flex.ExpandStringSet(v.(*schema.Set)) if err := addRoleManagedPolicies(roleName, managedPolicies, meta); err != nil { - return err + return fmt.Errorf("creating IAM Role (%s): %w", name, err) } } @@ -269,14 +269,14 @@ func resourceRoleRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading IAM Role (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Role (%s): %w", d.Id(), err) } role := outputRaw.(*iam.Role) // occasionally, immediately after a role is created, AWS will give an ARN like AROAQ7SSZBKHRKPWRZUN6 (unique ID) if role, err = waitRoleARNIsNotUniqueID(conn, d.Id(), role); err != nil { - return fmt.Errorf("error waiting for IAM role (%s) read: %w", d.Id(), err) + return fmt.Errorf("reading IAM Role (%s): waiting for valid ARN: %w", d.Id(), err) } d.Set("arn", role.Arn) @@ -293,12 +293,12 @@ func resourceRoleRead(d *schema.ResourceData, meta interface{}) error { assumeRolePolicy, err := url.QueryUnescape(aws.StringValue(role.AssumeRolePolicyDocument)) if err != nil { - return err + return fmt.Errorf("reading IAM Role (%s): %w", d.Id(), err) } policyToSet, err := verify.PolicyToSet(d.Get("assume_role_policy").(string), assumeRolePolicy) if err != nil { - return err + return fmt.Errorf("reading IAM Role (%s): %w", d.Id(), err) } d.Set("assume_role_policy", policyToSet) @@ -455,13 +455,13 @@ func resourceRoleUpdate(d *schema.ResourceData, meta interface{}) error { policyNames = append(policyNames, aws.String(tfMap["name"].(string))) } } - if err := deleteRolePolicies(conn, roleName, policyNames); err != nil { - return fmt.Errorf("unable to delete inline policies: %w", err) + if err := deleteRoleInlinePolicies(conn, roleName, policyNames); err != nil { + return fmt.Errorf("updating IAM Role (%s): %w", d.Id(), err) } policies := expandRoleInlinePolicies(roleName, add) if err := addRoleInlinePolicies(policies, meta); err != nil { - return err + return fmt.Errorf("updating IAM Role (%s): %w", d.Id(), err) } } @@ -482,11 +482,11 @@ func resourceRoleUpdate(d *schema.ResourceData, meta interface{}) error { add := flex.ExpandStringSet(ns.Difference(os)) if err := deleteRolePolicyAttachments(conn, roleName, remove); err != nil { - return fmt.Errorf("unable to detach policies: %w", err) + return fmt.Errorf("updating IAM Role (%s): %w", d.Id(), err) } if err := addRoleManagedPolicies(roleName, add, meta); err != nil { - return err + return fmt.Errorf("updating IAM Role (%s): %w", d.Id(), err) } } @@ -557,7 +557,7 @@ func DeleteRole(conn *iam.IAM, roleName string, forceDetach, hasInline, hasManag return err } - if err := deleteRolePolicies(conn, roleName, inlinePolicies); err != nil { + if err := deleteRoleInlinePolicies(conn, roleName, inlinePolicies); err != nil { return fmt.Errorf("unable to delete inline policies: %w", err) } } @@ -660,9 +660,9 @@ func readRolePolicyAttachments(conn *iam.IAM, roleName string) ([]*string, error } func deleteRolePolicyAttachments(conn *iam.IAM, roleName string, managedPolicies []*string) error { - for _, parn := range managedPolicies { + for _, arn := range managedPolicies { input := &iam.DetachRolePolicyInput{ - PolicyArn: parn, + PolicyArn: arn, RoleName: aws.String(roleName), } @@ -671,7 +671,7 @@ func deleteRolePolicyAttachments(conn *iam.IAM, roleName string, managedPolicies continue } if err != nil { - return err + return fmt.Errorf("detaching managed policy (%s): %w", aws.StringValue(arn), err) } } @@ -696,7 +696,7 @@ func readRolePolicyNames(conn *iam.IAM, roleName string) ([]*string, error) { return inlinePolicies, nil } -func deleteRolePolicies(conn *iam.IAM, roleName string, policyNames []*string) error { +func deleteRoleInlinePolicies(conn *iam.IAM, roleName string, policyNames []*string) error { for _, name := range policyNames { if len(aws.StringValue(name)) == 0 { continue @@ -712,7 +712,7 @@ func deleteRolePolicies(conn *iam.IAM, roleName string, policyNames []*string) e return nil } if err != nil { - return err + return fmt.Errorf("removing inline policy (%s): %w", aws.StringValue(name), err) } } @@ -812,8 +812,7 @@ func addRoleInlinePolicies(policies []*iam.PutRolePolicyInput, meta interface{}) } if _, err := conn.PutRolePolicy(policy); err != nil { - newErr := fmt.Errorf("creating inline policy (%s): %w", aws.StringValue(policy.PolicyName), err) - log.Printf("[ERROR] %s", newErr) + newErr := fmt.Errorf("adding inline policy (%s): %w", aws.StringValue(policy.PolicyName), err) errs = multierror.Append(errs, newErr) } } @@ -828,7 +827,6 @@ func addRoleManagedPolicies(roleName string, policies []*string, meta interface{ for _, arn := range policies { if err := attachPolicyToRole(conn, roleName, aws.StringValue(arn)); err != nil { newErr := fmt.Errorf("attaching managed policy (%s): %w", aws.StringValue(arn), err) - log.Printf("[ERROR] %s", newErr) errs = multierror.Append(errs, newErr) } } diff --git a/internal/service/iam/role_policy.go b/internal/service/iam/role_policy.go index 33ca348f606..4d58651364c 100644 --- a/internal/service/iam/role_policy.go +++ b/internal/service/iam/role_policy.go @@ -106,7 +106,7 @@ func resourceRolePolicyRead(d *schema.ResourceData, meta interface{}) error { role, name, err := RolePolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IAM Role Policy (%s): %w", d.Id(), err) } request := &iam.GetRolePolicyInput{ @@ -143,29 +143,29 @@ func resourceRolePolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading IAM Role Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Role Policy (%s): %w", d.Id(), err) } if getResp == nil || getResp.PolicyDocument == nil { - return fmt.Errorf("error reading IAM Role Policy (%s): empty response", d.Id()) + return fmt.Errorf("reading IAM Role Policy (%s): empty response", d.Id()) } policy, err := url.QueryUnescape(*getResp.PolicyDocument) if err != nil { - return err + return fmt.Errorf("reading IAM Role Policy (%s): %w", d.Id(), err) } policyToSet, err := verify.LegacyPolicyToSet(d.Get("policy").(string), policy) if err != nil { - return fmt.Errorf("while setting policy (%s), encountered: %w", policyToSet, err) + return fmt.Errorf("reading IAM Role Policy (%s): setting policy: %w", d.Id(), err) } d.Set("policy", policyToSet) - if err := d.Set("name", name); err != nil { - return err - } - return d.Set("role", role) + d.Set("name", name) + d.Set("role", role) + + return nil } func resourceRolePolicyDelete(d *schema.ResourceData, meta interface{}) error { @@ -173,7 +173,7 @@ func resourceRolePolicyDelete(d *schema.ResourceData, meta interface{}) error { role, name, err := RolePolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IAM role policy (%s): %s", d.Id(), err) } request := &iam.DeleteRolePolicyInput{ @@ -185,7 +185,7 @@ func resourceRolePolicyDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { return nil } - return fmt.Errorf("Error deleting IAM role policy %s: %s", d.Id(), err) + return fmt.Errorf("deleting IAM role policy (%s): %s", d.Id(), err) } return nil } diff --git a/internal/service/iam/server_certificate.go b/internal/service/iam/server_certificate.go index 32264ef1220..d465c119ab2 100644 --- a/internal/service/iam/server_certificate.go +++ b/internal/service/iam/server_certificate.go @@ -276,7 +276,7 @@ func resourceServerCertificateDelete(d *schema.ResourceData, meta interface{}) e }) } - return err + return fmt.Errorf("deleting IAM Server Certificate (%s): %w", d.Id(), err) } func resourceServerCertificateImport( diff --git a/internal/service/iam/server_certificate_data_source.go b/internal/service/iam/server_certificate_data_source.go index ce485b43829..3814bec90fa 100644 --- a/internal/service/iam/server_certificate_data_source.go +++ b/internal/service/iam/server_certificate_data_source.go @@ -120,7 +120,7 @@ func dataSourceServerCertificateRead(d *schema.ResourceData, meta interface{}) e return true }) if err != nil { - return fmt.Errorf("Error describing certificates: %w", err) + return fmt.Errorf("reading IAM Server Certificate: listing certificates: %w", err) } if len(metadatas) == 0 { @@ -148,7 +148,7 @@ func dataSourceServerCertificateRead(d *schema.ResourceData, meta interface{}) e ServerCertificateName: metadata.ServerCertificateName, }) if err != nil { - return err + return fmt.Errorf("reading IAM Server Certificate: getting certificate details: %w", err) } d.Set("upload_date", serverCertificateResp.ServerCertificate.ServerCertificateMetadata.UploadDate.Format(time.RFC3339)) d.Set("certificate_body", serverCertificateResp.ServerCertificate.CertificateBody) diff --git a/internal/service/iam/service_linked_role.go b/internal/service/iam/service_linked_role.go index e4ae8ce6477..e8843c1ed63 100644 --- a/internal/service/iam/service_linked_role.go +++ b/internal/service/iam/service_linked_role.go @@ -96,11 +96,10 @@ func resourceServiceLinkedRoleCreate(d *schema.ResourceData, meta interface{}) e input.Description = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating IAM Service Linked Role: %s", input) output, err := conn.CreateServiceLinkedRole(input) if err != nil { - return fmt.Errorf("error creating IAM Service Linked Role (%s): %w", serviceName, err) + return fmt.Errorf("creating IAM Service Linked Role (%s): %w", serviceName, err) } d.SetId(aws.StringValue(output.Role.Arn)) @@ -109,7 +108,7 @@ func resourceServiceLinkedRoleCreate(d *schema.ResourceData, meta interface{}) e _, roleName, _, err := DecodeServiceLinkedRoleID(d.Id()) if err != nil { - return err + return fmt.Errorf("creating IAM Service Linked Role (%s): %w", serviceName, err) } err = roleUpdateTags(conn, roleName, nil, tags) @@ -121,7 +120,7 @@ func resourceServiceLinkedRoleCreate(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("failed adding tags after create for IAM Service Linked Role (%s): %w", d.Id(), err) + return fmt.Errorf("creating IAM Service Linked Role (%s): adding tags: %w", serviceName, err) } } @@ -136,7 +135,7 @@ func resourceServiceLinkedRoleRead(d *schema.ResourceData, meta interface{}) err serviceName, roleName, customSuffix, err := DecodeServiceLinkedRoleID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IAM Service Linked Role (%s): %w", d.Id(), err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(propagationTimeout, func() (interface{}, error) { @@ -150,7 +149,7 @@ func resourceServiceLinkedRoleRead(d *schema.ResourceData, meta interface{}) err } if err != nil { - return fmt.Errorf("error reading IAM Service Linked Role (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Service Linked Role (%s): %w", d.Id(), err) } role := outputRaw.(*iam.Role) @@ -184,7 +183,7 @@ func resourceServiceLinkedRoleUpdate(d *schema.ResourceData, meta interface{}) e _, roleName, _, err := DecodeServiceLinkedRoleID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating IAM Service Linked Role (%s): %w", d.Id(), err) } if d.HasChangesExcept("tags_all", "tags") { @@ -197,7 +196,7 @@ func resourceServiceLinkedRoleUpdate(d *schema.ResourceData, meta interface{}) e _, err = conn.UpdateRole(input) if err != nil { - return fmt.Errorf("error updating IAM Service Linked Role (%s): %w", d.Id(), err) + return fmt.Errorf("updating IAM Service Linked Role (%s): %w", d.Id(), err) } } @@ -213,7 +212,7 @@ func resourceServiceLinkedRoleUpdate(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("failed updating tags for IAM Service Linked Role (%s): %w", d.Id(), err) + return fmt.Errorf("updating IAM Service Linked Role (%s): updating tags: %w", d.Id(), err) } } @@ -226,7 +225,7 @@ func resourceServiceLinkedRoleDelete(d *schema.ResourceData, meta interface{}) e _, roleName, _, err := DecodeServiceLinkedRoleID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IAM Service Linked Role (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting IAM Service Linked Role: (%s)", d.Id()) @@ -239,7 +238,7 @@ func resourceServiceLinkedRoleDelete(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("error deleting IAM Service Linked Role (%s): %w", d.Id(), err) + return fmt.Errorf("deleting IAM Service Linked Role (%s): %w", d.Id(), err) } deletionTaskID := aws.StringValue(output.DeletionTaskId) diff --git a/internal/service/iam/service_specific_credential.go b/internal/service/iam/service_specific_credential.go index e447947aef7..b3eb6d19244 100644 --- a/internal/service/iam/service_specific_credential.go +++ b/internal/service/iam/service_specific_credential.go @@ -98,7 +98,7 @@ func resourceServiceSpecificCredentialRead(d *schema.ResourceData, meta interfac serviceName, userName, credID, err := DecodeServiceSpecificCredentialId(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IAM Service Specific Credential (%s): %w", d.Id(), err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(propagationTimeout, func() (interface{}, error) { @@ -112,7 +112,7 @@ func resourceServiceSpecificCredentialRead(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error reading IAM Service Specific Credential (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Service Specific Credential (%s): %w", d.Id(), err) } cred := outputRaw.(*iam.ServiceSpecificCredentialMetadata) diff --git a/internal/service/iam/signing_certificate.go b/internal/service/iam/signing_certificate.go index 7c41bb408f7..00da5229cca 100644 --- a/internal/service/iam/signing_certificate.go +++ b/internal/service/iam/signing_certificate.go @@ -90,7 +90,7 @@ func resourceSigningCertificateRead(d *schema.ResourceData, meta interface{}) er certId, userName, err := DecodeSigningCertificateId(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IAM Signing Certificate (%s): %w", d.Id(), err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(propagationTimeout, func() (interface{}, error) { @@ -104,7 +104,7 @@ func resourceSigningCertificateRead(d *schema.ResourceData, meta interface{}) er } if err != nil { - return fmt.Errorf("error reading IAM Signing Certificate (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM Signing Certificate (%s): %w", d.Id(), err) } resp := outputRaw.(*iam.SigningCertificate) @@ -122,7 +122,7 @@ func resourceSigningCertificateUpdate(d *schema.ResourceData, meta interface{}) certId, userName, err := DecodeSigningCertificateId(d.Id()) if err != nil { - return err + return fmt.Errorf("updating IAM Signing Certificate (%s): %w", d.Id(), err) } updateInput := &iam.UpdateSigningCertificateInput{ @@ -133,7 +133,7 @@ func resourceSigningCertificateUpdate(d *schema.ResourceData, meta interface{}) _, err = conn.UpdateSigningCertificate(updateInput) if err != nil { - return fmt.Errorf("error updating IAM Signing Certificate: %w", err) + return fmt.Errorf("updating IAM Signing Certificate (%s): %w", d.Id(), err) } return resourceSigningCertificateRead(d, meta) @@ -145,7 +145,7 @@ func resourceSigningCertificateDelete(d *schema.ResourceData, meta interface{}) certId, userName, err := DecodeSigningCertificateId(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IAM Signing Certificate (%s): %s", d.Id(), err) } input := &iam.DeleteSigningCertificateInput{ @@ -157,7 +157,7 @@ func resourceSigningCertificateDelete(d *schema.ResourceData, meta interface{}) if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { return nil } - return fmt.Errorf("Error deleting IAM Signing Certificate %s: %s", d.Id(), err) + return fmt.Errorf("deleting IAM Signing Certificate (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/iam/sweep.go b/internal/service/iam/sweep.go index f0909190e00..607a9528983 100644 --- a/internal/service/iam/sweep.go +++ b/internal/service/iam/sweep.go @@ -421,7 +421,7 @@ func sweepPolicies(region string) error { } log.Printf("[INFO] Deleting IAM Policy: %s", arn) - if err := PolicyDeleteNondefaultVersions(arn, conn); err != nil { + if err := policyDeleteNonDefaultVersions(arn, conn); err != nil { sweeperErr := fmt.Errorf("error deleting IAM Policy (%s) non-default versions: %w", arn, err) log.Printf("[ERROR] %s", sweeperErr) sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) diff --git a/internal/service/iam/user.go b/internal/service/iam/user.go index b18fed16d75..a237fa636fe 100644 --- a/internal/service/iam/user.go +++ b/internal/service/iam/user.go @@ -339,7 +339,7 @@ func DeleteUserGroupMemberships(conn *iam.IAM, username string) error { for _, g := range groups { // use iam group membership func to remove user from all groups log.Printf("[DEBUG] Removing IAM User %s from IAM Group %s", username, g) - if err := removeUsersFromGroup(conn, []*string{aws.String(username)}, g); err != nil { + if err := removeUsersFromGroup(conn, []string{username}, g); err != nil { return err } } diff --git a/internal/service/iam/user_group_membership.go b/internal/service/iam/user_group_membership.go index f2c64e096c6..1223227bfb2 100644 --- a/internal/service/iam/user_group_membership.go +++ b/internal/service/iam/user_group_membership.go @@ -45,10 +45,10 @@ func resourceUserGroupMembershipCreate(d *schema.ResourceData, meta interface{}) conn := meta.(*conns.AWSClient).IAMConn() user := d.Get("user").(string) - groupList := flex.ExpandStringSet(d.Get("groups").(*schema.Set)) + groupList := flex.ExpandStringValueSet(d.Get("groups").(*schema.Set)) if err := addUserToGroups(conn, user, groupList); err != nil { - return err + return fmt.Errorf("assigning IAM User Group Membership (%s): %w", user, err) } //lintignore:R015 // Allow legacy unstable ID usage in managed resource @@ -144,15 +144,15 @@ func resourceUserGroupMembershipUpdate(d *schema.ResourceData, meta interface{}) os := o.(*schema.Set) ns := n.(*schema.Set) - remove := flex.ExpandStringSet(os.Difference(ns)) - add := flex.ExpandStringSet(ns.Difference(os)) + remove := flex.ExpandStringValueSet(os.Difference(ns)) + add := flex.ExpandStringValueSet(ns.Difference(os)) if err := removeUserFromGroups(conn, user, remove); err != nil { - return err + return fmt.Errorf("updating IAM User Group Membership (%s): %w", user, err) } if err := addUserToGroups(conn, user, add); err != nil { - return err + return fmt.Errorf("updating IAM User Group Membership (%s): %w", user, err) } } @@ -162,40 +162,54 @@ func resourceUserGroupMembershipUpdate(d *schema.ResourceData, meta interface{}) func resourceUserGroupMembershipDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).IAMConn() user := d.Get("user").(string) - groups := flex.ExpandStringSet(d.Get("groups").(*schema.Set)) + groups := flex.ExpandStringValueSet(d.Get("groups").(*schema.Set)) - err := removeUserFromGroups(conn, user, groups) - return err + if err := removeUserFromGroups(conn, user, groups); err != nil { + return fmt.Errorf("deleting IAM User Group Membership (%s): %w", user, err) + } + return nil } -func removeUserFromGroups(conn *iam.IAM, user string, groups []*string) error { +func removeUserFromGroups(conn *iam.IAM, user string, groups []string) error { for _, group := range groups { - _, err := conn.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{ - UserName: &user, - GroupName: group, - }) - if err != nil { - if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { - continue - } + if err := removeUserFromGroup(conn, user, group); err != nil { return err } } - return nil } -func addUserToGroups(conn *iam.IAM, user string, groups []*string) error { +func addUserToGroups(conn *iam.IAM, user string, groups []string) error { for _, group := range groups { - _, err := conn.AddUserToGroup(&iam.AddUserToGroupInput{ - UserName: &user, - GroupName: group, - }) - if err != nil { + if err := addUserToGroup(conn, user, group); err != nil { return err } } + return nil +} +func addUserToGroup(conn *iam.IAM, user, group string) error { + _, err := conn.AddUserToGroup(&iam.AddUserToGroupInput{ + UserName: aws.String(user), + GroupName: aws.String(group), + }) + if err != nil { + return fmt.Errorf("adding User (%s) to Group (%s): %w", user, group, err) + } + return nil +} + +func removeUserFromGroup(conn *iam.IAM, user, group string) error { + _, err := conn.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{ + UserName: aws.String(user), + GroupName: aws.String(group), + }) + if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { + return nil + } + if err != nil { + return fmt.Errorf("removing User (%s) from Group (%s): %w", user, group, err) + } return nil } diff --git a/internal/service/iam/user_login_profile.go b/internal/service/iam/user_login_profile.go index aa6b0f139af..d312e36ef98 100644 --- a/internal/service/iam/user_login_profile.go +++ b/internal/service/iam/user_login_profile.go @@ -133,7 +133,7 @@ func resourceUserLoginProfileCreate(d *schema.ResourceData, meta interface{}) er passwordLength := d.Get("password_length").(int) initialPassword, err := GeneratePassword(passwordLength) if err != nil { - return err + return fmt.Errorf("creating IAM User Login Profile for %q: %w", username, err) } request := &iam.CreateLoginProfileInput{ @@ -144,7 +144,7 @@ func resourceUserLoginProfileCreate(d *schema.ResourceData, meta interface{}) er createResp, err := conn.CreateLoginProfile(request) if err != nil { - return fmt.Errorf("Error creating IAM User Login Profile for %q: %w", username, err) + return fmt.Errorf("creating IAM User Login Profile for %q: %w", username, err) } d.SetId(aws.StringValue(createResp.LoginProfile.UserName)) @@ -152,12 +152,12 @@ func resourceUserLoginProfileCreate(d *schema.ResourceData, meta interface{}) er if v, ok := d.GetOk("pgp_key"); ok { encryptionKey, err := retrieveGPGKey(v.(string)) if err != nil { - return fmt.Errorf("error retrieving GPG Key during IAM User Login Profile (%s) creation: %w", username, err) + return fmt.Errorf("creating IAM User Login Profile for %q: %w", username, err) } fingerprint, encrypted, err := encryptValue(encryptionKey, initialPassword, "Password") if err != nil { - return fmt.Errorf("error encrypting password during IAM User Login Profile (%s) creation: %w", username, err) + return fmt.Errorf("creating IAM User Login Profile for %q: %w", username, err) } d.Set("key_fingerprint", fingerprint) diff --git a/internal/service/iam/user_policy.go b/internal/service/iam/user_policy.go index b1114f201e8..44425f9824b 100644 --- a/internal/service/iam/user_policy.go +++ b/internal/service/iam/user_policy.go @@ -79,7 +79,7 @@ func resourceUserPolicyPut(d *schema.ResourceData, meta interface{}) error { if !d.IsNewResource() { _, policyName, err = UserPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("putting IAM User Policy %s: %s", d.Id(), err) } } else if v, ok := d.GetOk("name"); ok { policyName = v.(string) @@ -91,10 +91,10 @@ func resourceUserPolicyPut(d *schema.ResourceData, meta interface{}) error { request.PolicyName = aws.String(policyName) if _, err := conn.PutUserPolicy(request); err != nil { - return fmt.Errorf("Error putting IAM user policy %s: %s", *request.PolicyName, err) + return fmt.Errorf("putting IAM User Policy %s: %s", aws.StringValue(request.PolicyName), err) } - d.SetId(fmt.Sprintf("%s:%s", *request.UserName, *request.PolicyName)) + d.SetId(fmt.Sprintf("%s:%s", aws.StringValue(request.UserName), aws.StringValue(request.PolicyName))) return nil } @@ -103,7 +103,7 @@ func resourceUserPolicyRead(d *schema.ResourceData, meta interface{}) error { user, name, err := UserPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IAM User Policy (%s): %w", d.Id(), err) } request := &iam.GetUserPolicyInput{ @@ -140,29 +140,29 @@ func resourceUserPolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading IAM User Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading IAM User Policy (%s): %w", d.Id(), err) } if getResp == nil || getResp.PolicyDocument == nil { - return fmt.Errorf("error reading IAM User Policy (%s): empty response", d.Id()) + return fmt.Errorf("reading IAM User Policy (%s): empty response", d.Id()) } policy, err := url.QueryUnescape(*getResp.PolicyDocument) if err != nil { - return err + return fmt.Errorf("reading IAM User Policy (%s): %w", d.Id(), err) } policyToSet, err := verify.LegacyPolicyToSet(d.Get("policy").(string), policy) if err != nil { - return fmt.Errorf("while setting policy (%s), encountered: %w", policyToSet, err) + return fmt.Errorf("reading IAM User Policy (%s): setting policy: %w", d.Id(), err) } d.Set("policy", policyToSet) - if err := d.Set("name", name); err != nil { - return err - } - return d.Set("user", user) + d.Set("name", name) + d.Set("user", user) + + return nil } func resourceUserPolicyDelete(d *schema.ResourceData, meta interface{}) error { @@ -170,7 +170,7 @@ func resourceUserPolicyDelete(d *schema.ResourceData, meta interface{}) error { user, name, err := UserPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IAM User Policy %s: %s", d.Id(), err) } request := &iam.DeleteUserPolicyInput{ @@ -182,7 +182,7 @@ func resourceUserPolicyDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, iam.ErrCodeNoSuchEntityException) { return nil } - return fmt.Errorf("Error deleting IAM user policy %s: %s", d.Id(), err) + return fmt.Errorf("deleting IAM User Policy %s: %s", d.Id(), err) } return nil } From fa5f09ddefa4c758bb77c6ff1794978bcbffb224 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 11:41:39 -0800 Subject: [PATCH 044/106] Fixes bare errors in `guardduty` --- .../service/guardduty/detector_data_source.go | 4 +- internal/service/guardduty/filter.go | 30 +++++---- internal/service/guardduty/guardduty_test.go | 4 +- internal/service/guardduty/ipset.go | 23 +++---- internal/service/guardduty/member.go | 12 ++-- .../guardduty/publishing_destination.go | 38 ++++++------ internal/service/guardduty/threatintelset.go | 61 +++++++++---------- .../service/guardduty/threatintelset_test.go | 42 ++++++------- 8 files changed, 104 insertions(+), 110 deletions(-) diff --git a/internal/service/guardduty/detector_data_source.go b/internal/service/guardduty/detector_data_source.go index 4c3cb8fc2f9..b0a80bd9a94 100644 --- a/internal/service/guardduty/detector_data_source.go +++ b/internal/service/guardduty/detector_data_source.go @@ -64,11 +64,11 @@ func dataSourceDetectorRead(d *schema.ResourceData, meta interface{}) error { getResp, err := conn.GetDetector(getInput) if err != nil { - return err + return fmt.Errorf("reading GuardDuty Detector (%s): %w", detectorId, err) } if getResp == nil { - return fmt.Errorf("cannot receive GuardDuty Detector details") + return fmt.Errorf("reading GuardDuty Detector (%s): empty result", detectorId) } d.SetId(detectorId) diff --git a/internal/service/guardduty/filter.go b/internal/service/guardduty/filter.go index aa01a62c974..ecb79bbe322 100644 --- a/internal/service/guardduty/filter.go +++ b/internal/service/guardduty/filter.go @@ -139,7 +139,7 @@ func resourceFilterCreate(d *schema.ResourceData, meta interface{}) error { var err error input.FindingCriteria, err = expandFindingCriteria(d.Get("finding_criteria").([]interface{})) if err != nil { - return err + return fmt.Errorf("creating GuardDuty Filter: %w", err) } if len(tags) > 0 { @@ -149,7 +149,7 @@ func resourceFilterCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Creating GuardDuty Filter: %s", input) output, err := conn.CreateFilter(&input) if err != nil { - return fmt.Errorf("error creating GuardDuty Filter: %w", err) + return fmt.Errorf("creating GuardDuty Filter: %w", err) } d.SetId(filterCreateID(d.Get("detector_id").(string), aws.StringValue(output.Name))) @@ -169,7 +169,7 @@ func resourceFilterRead(d *schema.ResourceData, meta interface{}) error { // If there is no "detector_id" passed, then it's an import. detectorID, name, err = FilterParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading GuardDuty Filter (%s): %w", name, err) } } else { detectorID = d.Get("detector_id").(string) @@ -190,7 +190,7 @@ func resourceFilterRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("error reading GuardDuty Filter '%s': %w", name, err) + return fmt.Errorf("reading GuardDuty Filter (%s): %w", name, err) } arn := arn.ARN{ @@ -217,11 +217,11 @@ func resourceFilterRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } d.SetId(filterCreateID(detectorID, name)) @@ -243,14 +243,12 @@ func resourceFilterUpdate(d *schema.ResourceData, meta interface{}) error { var err error input.FindingCriteria, err = expandFindingCriteria(d.Get("finding_criteria").([]interface{})) if err != nil { - return err + return fmt.Errorf("updating GuardDuty Filter %s: %w", d.Id(), err) } - log.Printf("[DEBUG] Updating GuardDuty Filter: %s", input) - _, err = conn.UpdateFilter(&input) if err != nil { - return fmt.Errorf("error updating GuardDuty Filter %s: %w", d.Id(), err) + return fmt.Errorf("updating GuardDuty Filter %s: %w", d.Id(), err) } } @@ -258,7 +256,7 @@ func resourceFilterUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating GuardDuty Filter (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating GuardDuty Filter (%s) tags: %s", d.Get("arn").(string), err) } } @@ -283,7 +281,7 @@ func resourceFilterDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error deleting GuardDuty Filter %s: %w", d.Id(), err) + return fmt.Errorf("deleting GuardDuty Filter %s: %w", d.Id(), err) } return nil } @@ -336,7 +334,7 @@ func expandFindingCriteria(raw []interface{}) (*guardduty.FindingCriteria, error if v, ok := x.(string); ok && v != "" { i, err := expandConditionIntField(field, v) if err != nil { - return nil, fmt.Errorf("error parsing condition %q for field %q: %w", "greater_than", field, err) + return nil, fmt.Errorf("parsing condition %q for field %q: %w", "greater_than", field, err) } condition.GreaterThan = aws.Int64(i) } @@ -345,7 +343,7 @@ func expandFindingCriteria(raw []interface{}) (*guardduty.FindingCriteria, error if v, ok := x.(string); ok && v != "" { i, err := expandConditionIntField(field, v) if err != nil { - return nil, fmt.Errorf("error parsing condition %q for field %q: %w", "greater_than_or_equal", field, err) + return nil, fmt.Errorf("parsing condition %q for field %q: %w", "greater_than_or_equal", field, err) } condition.GreaterThanOrEqual = aws.Int64(i) } @@ -354,7 +352,7 @@ func expandFindingCriteria(raw []interface{}) (*guardduty.FindingCriteria, error if v, ok := x.(string); ok && v != "" { i, err := expandConditionIntField(field, v) if err != nil { - return nil, fmt.Errorf("error parsing condition %q for field %q: %w", "less_than", field, err) + return nil, fmt.Errorf("parsing condition %q for field %q: %w", "less_than", field, err) } condition.LessThan = aws.Int64(i) } @@ -363,7 +361,7 @@ func expandFindingCriteria(raw []interface{}) (*guardduty.FindingCriteria, error if v, ok := x.(string); ok && v != "" { i, err := expandConditionIntField(field, v) if err != nil { - return nil, fmt.Errorf("error parsing condition %q for field %q: %w", "less_than_or_equal", field, err) + return nil, fmt.Errorf("parsing condition %q for field %q: %w", "less_than_or_equal", field, err) } condition.LessThanOrEqual = aws.Int64(i) } diff --git a/internal/service/guardduty/guardduty_test.go b/internal/service/guardduty/guardduty_test.go index 361e273e465..5a1f8910617 100644 --- a/internal/service/guardduty/guardduty_test.go +++ b/internal/service/guardduty/guardduty_test.go @@ -44,8 +44,8 @@ func TestAccGuardDuty_serial(t *testing.T) { "malwareProtection": testAccOrganizationConfiguration_malwareprotection, }, "ThreatIntelSet": { - "basic": testAccThreatintelset_basic, - "tags": testAccThreatintelset_tags, + "basic": testAccThreatIntelSet_basic, + "tags": testAccThreatIntelSet_tags, }, "Member": { "basic": testAccMember_basic, diff --git a/internal/service/guardduty/ipset.go b/internal/service/guardduty/ipset.go index 8f06a104a63..5178dee7756 100644 --- a/internal/service/guardduty/ipset.go +++ b/internal/service/guardduty/ipset.go @@ -93,7 +93,7 @@ func resourceIPSetCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateIPSet(input) if err != nil { - return err + return fmt.Errorf("creating GuardDuty IPSet (%s): %w", d.Get("name").(string), err) } stateConf := &resource.StateChangeConf{ @@ -106,10 +106,11 @@ func resourceIPSetCreate(d *schema.ResourceData, meta interface{}) error { _, err = stateConf.WaitForState() if err != nil { - return fmt.Errorf("Error waiting for GuardDuty IpSet status to be \"%s\" or \"%s\": %s", guardduty.IpSetStatusActive, guardduty.IpSetStatusInactive, err) + return fmt.Errorf("creating GuardDuty IPSet (%s): waiting for completion: %w", d.Get("name").(string), err) } d.SetId(fmt.Sprintf("%s:%s", detectorID, *resp.IpSetId)) + return resourceIPSetRead(d, meta) } @@ -120,7 +121,7 @@ func resourceIPSetRead(d *schema.ResourceData, meta interface{}) error { ipSetId, detectorId, err := DecodeIPSetID(d.Id()) if err != nil { - return err + return fmt.Errorf("creating GuardDuty IPSet (%s): %w", d.Id(), err) } input := &guardduty.GetIPSetInput{ DetectorId: aws.String(detectorId), @@ -130,11 +131,11 @@ func resourceIPSetRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetIPSet(input) if err != nil { if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") { - log.Printf("[WARN] GuardDuty IpSet %q not found, removing from state", ipSetId) + log.Printf("[WARN] GuardDuty IPSet (%s) not found, removing from state", ipSetId) d.SetId("") return nil } - return err + return fmt.Errorf("reading GuardDuty IPSet (%s): %w", d.Id(), err) } arn := arn.ARN{ @@ -171,7 +172,7 @@ func resourceIPSetUpdate(d *schema.ResourceData, meta interface{}) error { ipSetId, detectorId, err := DecodeIPSetID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating GuardDuty IPSet (%s): %s", d.Id(), err) } if d.HasChanges("activate", "location", "name") { @@ -192,7 +193,7 @@ func resourceIPSetUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateIPSet(input) if err != nil { - return err + return fmt.Errorf("updating GuardDuty IPSet (%s): %s", d.Id(), err) } } @@ -200,7 +201,7 @@ func resourceIPSetUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating GuardDuty IP Set (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating GuardDuty IPSet (%s): setting tags: %s", d.Id(), err) } } @@ -212,7 +213,7 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { ipSetId, detectorId, err := DecodeIPSetID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting GuardDuty IPSet (%s): %s", d.Id(), err) } input := &guardduty.DeleteIPSetInput{ DetectorId: aws.String(detectorId), @@ -221,7 +222,7 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { _, err = conn.DeleteIPSet(input) if err != nil { - return err + return fmt.Errorf("deleting GuardDuty IPSet (%s): %s", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -240,7 +241,7 @@ func resourceIPSetDelete(d *schema.ResourceData, meta interface{}) error { _, err = stateConf.WaitForState() if err != nil { - return fmt.Errorf("Error waiting for GuardDuty IpSet status to be \"%s\": %s", guardduty.IpSetStatusDeleted, err) + return fmt.Errorf("deleting GuardDuty IPSet (%s): waiting for completion: %s", d.Id(), err) } return nil diff --git a/internal/service/guardduty/member.go b/internal/service/guardduty/member.go index aa985ff9970..b4c3763d135 100644 --- a/internal/service/guardduty/member.go +++ b/internal/service/guardduty/member.go @@ -86,7 +86,7 @@ func resourceMemberCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Creating GuardDuty Member: %s", input) _, err := conn.CreateMembers(&input) if err != nil { - return fmt.Errorf("Creating GuardDuty Member failed: %s", err.Error()) + return fmt.Errorf("Creating GuardDuty Member failed: %s", err) } d.SetId(fmt.Sprintf("%s:%s", detectorID, accountID)) @@ -121,7 +121,7 @@ func resourceMemberRead(d *schema.ResourceData, meta interface{}) error { accountID, detectorID, err := DecodeMemberID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading GuardDuty Member (%s): %s", d.Id(), err) } input := guardduty.GetMembersInput{ @@ -137,7 +137,7 @@ func resourceMemberRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("Reading GuardDuty Member '%s' failed: %s", d.Id(), err.Error()) + return fmt.Errorf("reading GuardDuty Member (%s): %s", d.Id(), err) } if gmo.Members == nil || (len(gmo.Members) < 1) { @@ -168,7 +168,7 @@ func resourceMemberUpdate(d *schema.ResourceData, meta interface{}) error { accountID, detectorID, err := DecodeMemberID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating GuardDuty Member (%s): %s", d.Id(), err) } if d.HasChange("invite") { @@ -216,7 +216,7 @@ func resourceMemberDelete(d *schema.ResourceData, meta interface{}) error { accountID, detectorID, err := DecodeMemberID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting GuardDuty Member (%s): %s", d.Id(), err) } input := guardduty.DeleteMembersInput{ @@ -227,7 +227,7 @@ func resourceMemberDelete(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Delete GuardDuty Member: %s", input) _, err = conn.DeleteMembers(&input) if err != nil { - return fmt.Errorf("Deleting GuardDuty Member '%s' failed: %s", d.Id(), err.Error()) + return fmt.Errorf("deleting GuardDuty Member (%s): %s", d.Id(), err) } return nil } diff --git a/internal/service/guardduty/publishing_destination.go b/internal/service/guardduty/publishing_destination.go index a674275495f..bbc98b47f20 100644 --- a/internal/service/guardduty/publishing_destination.go +++ b/internal/service/guardduty/publishing_destination.go @@ -64,10 +64,9 @@ func resourcePublishingDestinationCreate(d *schema.ResourceData, meta interface{ DestinationType: aws.String(d.Get("destination_type").(string)), } - log.Printf("[DEBUG] Creating GuardDuty publishing destination: %s", input) output, err := conn.CreatePublishingDestination(&input) if err != nil { - return fmt.Errorf("Creating GuardDuty publishing destination failed: %w", err) + return fmt.Errorf("creating GuardDuty Publishing Destination: %w", err) } d.SetId(fmt.Sprintf("%s:%s", d.Get("detector_id"), aws.StringValue(output.DestinationId))) @@ -85,10 +84,10 @@ func resourcePublishingDestinationCreate(d *schema.ResourceData, meta interface{ func resourcePublishingDestinationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() - destinationId, detectorId, errStateRead := DecodePublishDestinationID(d.Id()) + destinationId, detectorId, err := DecodePublishDestinationID(d.Id()) - if errStateRead != nil { - return errStateRead + if err != nil { + return fmt.Errorf("reading GuardDuty Publishing Destination (%s): %w", d.Id(), err) } input := &guardduty.DescribePublishingDestinationInput{ @@ -96,15 +95,14 @@ func resourcePublishingDestinationRead(d *schema.ResourceData, meta interface{}) DestinationId: aws.String(destinationId), } - log.Printf("[DEBUG] Reading GuardDuty publishing destination: %s", input) gdo, err := conn.DescribePublishingDestination(input) if err != nil { if tfawserr.ErrMessageContains(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the one or more input parameters have invalid values.") { - log.Printf("[WARN] GuardDuty publishing destination: %q not found, removing from state", d.Id()) + log.Printf("[WARN] GuardDuty Publishing Destination: %q not found, removing from state", d.Id()) d.SetId("") return nil } - return fmt.Errorf("Reading GuardDuty publishing destination: '%s' failed: %w", d.Id(), err) + return fmt.Errorf("reading GuardDuty Publishing Destination (%s): %w", d.Id(), err) } d.Set("detector_id", detectorId) @@ -117,10 +115,10 @@ func resourcePublishingDestinationRead(d *schema.ResourceData, meta interface{}) func resourcePublishingDestinationUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() - destinationId, detectorId, errStateRead := DecodePublishDestinationID(d.Id()) + destinationId, detectorId, err := DecodePublishDestinationID(d.Id()) - if errStateRead != nil { - return errStateRead + if err != nil { + return fmt.Errorf("updating GuardDuty Publishing Destination (%s): %w", d.Id(), err) } input := guardduty.UpdatePublishingDestinationInput{ @@ -132,10 +130,8 @@ func resourcePublishingDestinationUpdate(d *schema.ResourceData, meta interface{ }, } - log.Printf("[DEBUG] Update GuardDuty publishing destination: %s", input) - _, err := conn.UpdatePublishingDestination(&input) - if err != nil { - return fmt.Errorf("Updating GuardDuty publishing destination '%s' failed: %w", d.Id(), err) + if _, err = conn.UpdatePublishingDestination(&input); err != nil { + return fmt.Errorf("updating GuardDuty Publishing Destination (%s): %w", d.Id(), err) } return resourcePublishingDestinationRead(d, meta) @@ -144,10 +140,10 @@ func resourcePublishingDestinationUpdate(d *schema.ResourceData, meta interface{ func resourcePublishingDestinationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() - destinationId, detectorId, errStateRead := DecodePublishDestinationID(d.Id()) + destinationId, detectorId, err := DecodePublishDestinationID(d.Id()) - if errStateRead != nil { - return errStateRead + if err != nil { + return fmt.Errorf("deleting GuardDuty Publishing Destination (%s): %w", d.Id(), err) } input := guardduty.DeletePublishingDestinationInput{ @@ -155,15 +151,15 @@ func resourcePublishingDestinationDelete(d *schema.ResourceData, meta interface{ DetectorId: aws.String(detectorId), } - log.Printf("[DEBUG] Delete GuardDuty publishing destination: %s", input) - _, err := conn.DeletePublishingDestination(&input) + log.Printf("[DEBUG] Delete GuardDuty Publishing Destination: %s", input) + _, err = conn.DeletePublishingDestination(&input) if tfawserr.ErrCodeEquals(err, guardduty.ErrCodeBadRequestException) { return nil } if err != nil { - return fmt.Errorf("Deleting GuardDuty publishing destination '%s' failed: %w", d.Id(), err) + return fmt.Errorf("deleting GuardDuty Publishing Destination (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/guardduty/threatintelset.go b/internal/service/guardduty/threatintelset.go index c873c73568b..d8e239e591f 100644 --- a/internal/service/guardduty/threatintelset.go +++ b/internal/service/guardduty/threatintelset.go @@ -18,12 +18,12 @@ import ( "github.com/hashicorp/terraform-provider-aws/internal/verify" ) -func ResourceThreatintelset() *schema.Resource { +func ResourceThreatIntelSet() *schema.Resource { return &schema.Resource{ - Create: resourceThreatintelsetCreate, - Read: resourceThreatintelsetRead, - Update: resourceThreatintelsetUpdate, - Delete: resourceThreatintelsetDelete, + Create: resourceThreatIntelSetCreate, + Read: resourceThreatIntelSetRead, + Update: resourceThreatIntelSetUpdate, + Delete: resourceThreatIntelSetDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, @@ -73,15 +73,16 @@ func ResourceThreatintelset() *schema.Resource { } } -func resourceThreatintelsetCreate(d *schema.ResourceData, meta interface{}) error { +func resourceThreatIntelSetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) detectorID := d.Get("detector_id").(string) + name := d.Get("name").(string) input := &guardduty.CreateThreatIntelSetInput{ DetectorId: aws.String(detectorID), - Name: aws.String(d.Get("name").(string)), + Name: aws.String(name), Format: aws.String(d.Get("format").(string)), Location: aws.String(d.Get("location").(string)), Activate: aws.Bool(d.Get("activate").(bool)), @@ -93,7 +94,7 @@ func resourceThreatintelsetCreate(d *schema.ResourceData, meta interface{}) erro resp, err := conn.CreateThreatIntelSet(input) if err != nil { - return err + return fmt.Errorf("creating GuardDuty Threat Intel Set (%s): %w", name, err) } stateConf := &resource.StateChangeConf{ @@ -104,24 +105,23 @@ func resourceThreatintelsetCreate(d *schema.ResourceData, meta interface{}) erro MinTimeout: 3 * time.Second, } - _, err = stateConf.WaitForState() - if err != nil { - return fmt.Errorf("Error waiting for GuardDuty ThreatIntelSet status to be \"%s\" or \"%s\": %s", - guardduty.ThreatIntelSetStatusActive, guardduty.ThreatIntelSetStatusInactive, err) + if _, err = stateConf.WaitForState(); err != nil { + return fmt.Errorf("creating GuardDuty Threat Intel Set (%s): waiting for completion: %w", name, err) } - d.SetId(fmt.Sprintf("%s:%s", detectorID, *resp.ThreatIntelSetId)) - return resourceThreatintelsetRead(d, meta) + d.SetId(fmt.Sprintf("%s:%s", detectorID, aws.StringValue(resp.ThreatIntelSetId))) + + return resourceThreatIntelSetRead(d, meta) } -func resourceThreatintelsetRead(d *schema.ResourceData, meta interface{}) error { +func resourceThreatIntelSetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig - threatIntelSetId, detectorId, err := DecodeThreatintelsetID(d.Id()) + threatIntelSetId, detectorId, err := DecodeThreatIntelSetID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading GuardDuty Threat Intel Set (%s): %w", d.Id(), err) } input := &guardduty.GetThreatIntelSetInput{ DetectorId: aws.String(detectorId), @@ -135,7 +135,7 @@ func resourceThreatintelsetRead(d *schema.ResourceData, meta interface{}) error d.SetId("") return nil } - return err + return fmt.Errorf("reading GuardDuty Threat Intel Set (%s): %w", d.Id(), err) } arn := arn.ARN{ @@ -167,12 +167,12 @@ func resourceThreatintelsetRead(d *schema.ResourceData, meta interface{}) error return nil } -func resourceThreatintelsetUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceThreatIntelSetUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() - threatIntelSetID, detectorId, err := DecodeThreatintelsetID(d.Id()) + threatIntelSetID, detectorId, err := DecodeThreatIntelSetID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating GuardDuty Threat Intel Set (%s): %w", d.Id(), err) } if d.HasChanges("activate", "location", "name") { @@ -191,9 +191,8 @@ func resourceThreatintelsetUpdate(d *schema.ResourceData, meta interface{}) erro input.Activate = aws.Bool(d.Get("activate").(bool)) } - _, err = conn.UpdateThreatIntelSet(input) - if err != nil { - return err + if _, err = conn.UpdateThreatIntelSet(input); err != nil { + return fmt.Errorf("updating GuardDuty Threat Intel Set (%s): %w", d.Id(), err) } } @@ -201,19 +200,19 @@ func resourceThreatintelsetUpdate(d *schema.ResourceData, meta interface{}) erro o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating GuardDuty Threat Intel Set (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating GuardDuty Threat Intel Set (%s): setting tags: %w", d.Id(), err) } } - return resourceThreatintelsetRead(d, meta) + return resourceThreatIntelSetRead(d, meta) } -func resourceThreatintelsetDelete(d *schema.ResourceData, meta interface{}) error { +func resourceThreatIntelSetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GuardDutyConn() - threatIntelSetID, detectorId, err := DecodeThreatintelsetID(d.Id()) + threatIntelSetID, detectorId, err := DecodeThreatIntelSetID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting GuardDuty Threat Intel Set (%s): %w", d.Id(), err) } input := &guardduty.DeleteThreatIntelSetInput{ DetectorId: aws.String(detectorId), @@ -222,7 +221,7 @@ func resourceThreatintelsetDelete(d *schema.ResourceData, meta interface{}) erro _, err = conn.DeleteThreatIntelSet(input) if err != nil { - return err + return fmt.Errorf("deleting GuardDuty Threat Intel Set (%s): %w", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -261,7 +260,7 @@ func threatintelsetRefreshStatusFunc(conn *guardduty.GuardDuty, threatIntelSetID } } -func DecodeThreatintelsetID(id string) (threatIntelSetID, detectorID string, err error) { +func DecodeThreatIntelSetID(id string) (threatIntelSetID, detectorID string, err error) { parts := strings.Split(id, ":") if len(parts) != 2 { err = fmt.Errorf("GuardDuty ThreatIntelSet ID must be of the form :, was provided: %s", id) diff --git a/internal/service/guardduty/threatintelset_test.go b/internal/service/guardduty/threatintelset_test.go index cdb4edb1593..2c67ddc85d7 100644 --- a/internal/service/guardduty/threatintelset_test.go +++ b/internal/service/guardduty/threatintelset_test.go @@ -16,7 +16,7 @@ import ( tfguardduty "github.com/hashicorp/terraform-provider-aws/internal/service/guardduty" ) -func testAccThreatintelset_basic(t *testing.T) { +func testAccThreatIntelSet_basic(t *testing.T) { bucketName := fmt.Sprintf("tf-test-%s", sdkacctest.RandString(5)) keyName1 := fmt.Sprintf("tf-%s", sdkacctest.RandString(5)) keyName2 := fmt.Sprintf("tf-%s", sdkacctest.RandString(5)) @@ -28,12 +28,12 @@ func testAccThreatintelset_basic(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, guardduty.EndpointsID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckThreatintelsetDestroy, + CheckDestroy: testAccCheckThreatIntelSetDestroy, Steps: []resource.TestStep{ { - Config: testAccThreatintelsetConfig_basic(bucketName, keyName1, threatintelsetName1, true), + Config: testAccThreatIntelSetConfig_basic(bucketName, keyName1, threatintelsetName1, true), Check: resource.ComposeTestCheckFunc( - testAccCheckThreatintelsetExists(resourceName), + testAccCheckThreatIntelSetExists(resourceName), acctest.MatchResourceAttrRegionalARN(resourceName, "arn", "guardduty", regexp.MustCompile("detector/.+/threatintelset/.+$")), resource.TestCheckResourceAttr(resourceName, "name", threatintelsetName1), resource.TestCheckResourceAttr(resourceName, "activate", "true"), @@ -47,9 +47,9 @@ func testAccThreatintelset_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccThreatintelsetConfig_basic(bucketName, keyName2, threatintelsetName2, false), + Config: testAccThreatIntelSetConfig_basic(bucketName, keyName2, threatintelsetName2, false), Check: resource.ComposeTestCheckFunc( - testAccCheckThreatintelsetExists(resourceName), + testAccCheckThreatIntelSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", threatintelsetName2), resource.TestCheckResourceAttr(resourceName, "activate", "false"), resource.TestMatchResourceAttr(resourceName, "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName2))), @@ -59,7 +59,7 @@ func testAccThreatintelset_basic(t *testing.T) { }) } -func testAccThreatintelset_tags(t *testing.T) { +func testAccThreatIntelSet_tags(t *testing.T) { rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix) resourceName := "aws_guardduty_threatintelset.test" @@ -67,12 +67,12 @@ func testAccThreatintelset_tags(t *testing.T) { PreCheck: func() { acctest.PreCheck(t) }, ErrorCheck: acctest.ErrorCheck(t, guardduty.EndpointsID), ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories, - CheckDestroy: testAccCheckThreatintelsetDestroy, + CheckDestroy: testAccCheckThreatIntelSetDestroy, Steps: []resource.TestStep{ { - Config: testAccThreatintelsetConfig_tags1(rName, "key1", "value1"), + Config: testAccThreatIntelSetConfig_tags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckThreatintelsetExists(resourceName), + testAccCheckThreatIntelSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), @@ -83,18 +83,18 @@ func testAccThreatintelset_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccThreatintelsetConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), + Config: testAccThreatIntelSetConfig_tags2(rName, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckThreatintelsetExists(resourceName), + testAccCheckThreatIntelSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { - Config: testAccThreatintelsetConfig_tags1(rName, "key2", "value2"), + Config: testAccThreatIntelSetConfig_tags1(rName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckThreatintelsetExists(resourceName), + testAccCheckThreatIntelSetExists(resourceName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), @@ -103,7 +103,7 @@ func testAccThreatintelset_tags(t *testing.T) { }) } -func testAccCheckThreatintelsetDestroy(s *terraform.State) error { +func testAccCheckThreatIntelSetDestroy(s *terraform.State) error { conn := acctest.Provider.Meta().(*conns.AWSClient).GuardDutyConn() for _, rs := range s.RootModule().Resources { @@ -111,7 +111,7 @@ func testAccCheckThreatintelsetDestroy(s *terraform.State) error { continue } - threatIntelSetId, detectorId, err := tfguardduty.DecodeThreatintelsetID(rs.Primary.ID) + threatIntelSetId, detectorId, err := tfguardduty.DecodeThreatIntelSetID(rs.Primary.ID) if err != nil { return err } @@ -138,14 +138,14 @@ func testAccCheckThreatintelsetDestroy(s *terraform.State) error { return nil } -func testAccCheckThreatintelsetExists(name string) resource.TestCheckFunc { +func testAccCheckThreatIntelSetExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) } - threatIntelSetId, detectorId, err := tfguardduty.DecodeThreatintelsetID(rs.Primary.ID) + threatIntelSetId, detectorId, err := tfguardduty.DecodeThreatIntelSetID(rs.Primary.ID) if err != nil { return err } @@ -161,7 +161,7 @@ func testAccCheckThreatintelsetExists(name string) resource.TestCheckFunc { } } -func testAccThreatintelsetConfig_basic(bucketName, keyName, threatintelsetName string, activate bool) string { +func testAccThreatIntelSetConfig_basic(bucketName, keyName, threatintelsetName string, activate bool) string { return fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} @@ -192,7 +192,7 @@ resource "aws_guardduty_threatintelset" "test" { `, bucketName, keyName, threatintelsetName, activate) } -func testAccThreatintelsetConfig_tags1(rName, tagKey1, tagValue1 string) string { +func testAccThreatIntelSetConfig_tags1(rName, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} @@ -227,7 +227,7 @@ resource "aws_guardduty_threatintelset" "test" { `, rName, tagKey1, tagValue1) } -func testAccThreatintelsetConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { +func testAccThreatIntelSetConfig_tags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` resource "aws_guardduty_detector" "test" {} From d922c86cdd9b32d528a39949a869cb1f0b1f6cfd Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 11:42:18 -0800 Subject: [PATCH 045/106] Fixes bare errors in `grafana` --- internal/service/grafana/workspace_api_key.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/grafana/workspace_api_key.go b/internal/service/grafana/workspace_api_key.go index 749508de4b0..b838c5c0252 100644 --- a/internal/service/grafana/workspace_api_key.go +++ b/internal/service/grafana/workspace_api_key.go @@ -83,7 +83,7 @@ func resourceWorkspaceAPIKeyDelete(d *schema.ResourceData, meta interface{}) err workspaceID, keyName, err := WorkspaceAPIKeyParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Grafana Workspace API Key (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting Grafana Workspace API Key: %s", d.Id()) From 5a07c169fe23d98582b86c5644be122646ab59c6 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 11:42:32 -0800 Subject: [PATCH 046/106] Fixes bare errors in `glue` --- internal/service/glue/catalog_database.go | 12 +++++------ internal/service/glue/catalog_table.go | 21 +++++++++---------- internal/service/glue/connection.go | 12 +++++------ internal/service/glue/crawler.go | 12 +++++------ internal/service/glue/partition.go | 5 ++--- internal/service/glue/resource_policy.go | 4 ++-- .../service/glue/user_defined_function.go | 14 ++++++------- 7 files changed, 39 insertions(+), 41 deletions(-) diff --git a/internal/service/glue/catalog_database.go b/internal/service/glue/catalog_database.go index be449edba9f..db80f73da8e 100644 --- a/internal/service/glue/catalog_database.go +++ b/internal/service/glue/catalog_database.go @@ -150,7 +150,7 @@ func resourceCatalogDatabaseCreate(d *schema.ResourceData, meta interface{}) err _, err := conn.CreateDatabase(input) if err != nil { - return fmt.Errorf("Error creating Catalog Database: %w", err) + return fmt.Errorf("creating Glue Catalog Database (%s): %w", name, err) } d.SetId(fmt.Sprintf("%s:%s", catalogID, name)) @@ -163,7 +163,7 @@ func resourceCatalogDatabaseUpdate(d *schema.ResourceData, meta interface{}) err catalogID, name, err := ReadCatalogID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Glue Catalog Database (%s): %w", d.Id(), err) } dbUpdateInput := &glue.UpdateDatabaseInput{ @@ -194,7 +194,7 @@ func resourceCatalogDatabaseUpdate(d *schema.ResourceData, meta interface{}) err dbUpdateInput.DatabaseInput = dbInput if _, err := conn.UpdateDatabase(dbUpdateInput); err != nil { - return err + return fmt.Errorf("updating Glue Catalog Database (%s): %w", d.Id(), err) } return resourceCatalogDatabaseRead(d, meta) @@ -205,7 +205,7 @@ func resourceCatalogDatabaseRead(d *schema.ResourceData, meta interface{}) error catalogID, name, err := ReadCatalogID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Glue Catalog Database (%s): %w", d.Id(), err) } input := &glue.GetDatabaseInput{ @@ -221,7 +221,7 @@ func resourceCatalogDatabaseRead(d *schema.ResourceData, meta interface{}) error return nil } - return fmt.Errorf("Error reading Glue Catalog Database: %s", err.Error()) + return fmt.Errorf("reading Glue Catalog Database (%s): %w", d.Id(), err) } database := out.Database @@ -263,7 +263,7 @@ func resourceCatalogDatabaseDelete(d *schema.ResourceData, meta interface{}) err CatalogId: aws.String(d.Get("catalog_id").(string)), }) if err != nil { - return fmt.Errorf("Error deleting Glue Catalog Database: %w", err) + return fmt.Errorf("deleting Glue Catalog Database (%s): %w", d.Id(), err) } return nil } diff --git a/internal/service/glue/catalog_table.go b/internal/service/glue/catalog_table.go index b5bb584c4bb..fe50efa70b4 100644 --- a/internal/service/glue/catalog_table.go +++ b/internal/service/glue/catalog_table.go @@ -369,10 +369,9 @@ func resourceCatalogTableCreate(d *schema.ResourceData, meta interface{}) error PartitionIndexes: expandTablePartitionIndexes(d.Get("partition_index").([]interface{})), } - log.Printf("[DEBUG] Glue catalog table input: %#v", input) _, err := conn.CreateTable(input) if err != nil { - return fmt.Errorf("Error creating Glue Catalog Table: %w", err) + return fmt.Errorf("creating Glue Catalog Table (%s): %w", name, err) } d.SetId(fmt.Sprintf("%s:%s:%s", catalogID, dbName, name)) @@ -385,7 +384,7 @@ func resourceCatalogTableRead(d *schema.ResourceData, meta interface{}) error { catalogID, dbName, name, err := ReadTableID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Glue Catalog Table (%s): %w", d.Id(), err) } out, err := FindTableByName(conn, catalogID, dbName, name) @@ -396,7 +395,7 @@ func resourceCatalogTableRead(d *schema.ResourceData, meta interface{}) error { return nil } - return fmt.Errorf("Error reading Glue Catalog Table: %w", err) + return fmt.Errorf("reading Glue Catalog Table (%s): %w", d.Id(), err) } table := out.Table @@ -464,7 +463,7 @@ func resourceCatalogTableUpdate(d *schema.ResourceData, meta interface{}) error catalogID, dbName, _, err := ReadTableID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Glue Catalog Table (%s): %w", d.Id(), err) } updateTableInput := &glue.UpdateTableInput{ @@ -474,7 +473,7 @@ func resourceCatalogTableUpdate(d *schema.ResourceData, meta interface{}) error } if _, err := conn.UpdateTable(updateTableInput); err != nil { - return fmt.Errorf("Error updating Glue Catalog Table: %w", err) + return fmt.Errorf("updating Glue Catalog Table (%s): %w", d.Id(), err) } return resourceCatalogTableRead(d, meta) @@ -483,13 +482,13 @@ func resourceCatalogTableUpdate(d *schema.ResourceData, meta interface{}) error func resourceCatalogTableDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GlueConn() - catalogID, dbName, name, tableIdErr := ReadTableID(d.Id()) - if tableIdErr != nil { - return tableIdErr + catalogID, dbName, name, err := ReadTableID(d.Id()) + if err != nil { + return fmt.Errorf("deleting Glue Catalog Table (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Glue Catalog Table: %s:%s:%s", catalogID, dbName, name) - _, err := conn.DeleteTable(&glue.DeleteTableInput{ + _, err = conn.DeleteTable(&glue.DeleteTableInput{ CatalogId: aws.String(catalogID), Name: aws.String(name), DatabaseName: aws.String(dbName), @@ -498,7 +497,7 @@ func resourceCatalogTableDelete(d *schema.ResourceData, meta interface{}) error if tfawserr.ErrCodeEquals(err, glue.ErrCodeEntityNotFoundException) { return nil } - return fmt.Errorf("Error deleting Glue Catalog Table: %w", err) + return fmt.Errorf("deleting Glue Catalog Table (%s): %w", d.Id(), err) } return nil } diff --git a/internal/service/glue/connection.go b/internal/service/glue/connection.go index d12d96f27d9..d5f4486669c 100644 --- a/internal/service/glue/connection.go +++ b/internal/service/glue/connection.go @@ -139,7 +139,7 @@ func resourceConnectionRead(d *schema.ResourceData, meta interface{}) error { catalogID, connectionName, err := DecodeConnectionID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Glue Connection (%s): %w", d.Id(), err) } connection, err := FindConnectionByName(conn, connectionName, catalogID) @@ -150,7 +150,7 @@ func resourceConnectionRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Glue Connection (%s): %w", d.Id(), err) + return fmt.Errorf("reading Glue Connection (%s): %w", d.Id(), err) } connectionArn := arn.ARN{ @@ -202,7 +202,7 @@ func resourceConnectionUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChangesExcept("tags", "tags_all") { catalogID, connectionName, err := DecodeConnectionID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Glue Connection (%s): %w", d.Id(), err) } input := &glue.UpdateConnectionInput{ @@ -214,7 +214,7 @@ func resourceConnectionUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Updating Glue Connection: %s", input) _, err = conn.UpdateConnection(input) if err != nil { - return fmt.Errorf("error updating Glue Connection (%s): %w", d.Id(), err) + return fmt.Errorf("updating Glue Connection (%s): %w", d.Id(), err) } } @@ -233,13 +233,13 @@ func resourceConnectionDelete(d *schema.ResourceData, meta interface{}) error { catalogID, connectionName, err := DecodeConnectionID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Glue Connection (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting Glue Connection: %s", d.Id()) err = DeleteConnection(conn, catalogID, connectionName) if err != nil { - return fmt.Errorf("error deleting Glue Connection (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Glue Connection (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/glue/crawler.go b/internal/service/glue/crawler.go index 89efb3d557b..7a51e34f14a 100644 --- a/internal/service/glue/crawler.go +++ b/internal/service/glue/crawler.go @@ -361,7 +361,7 @@ func resourceCrawlerCreate(d *schema.ResourceData, meta interface{}) error { crawlerInput, err := createCrawlerInput(d, name, meta.(*conns.AWSClient).DefaultTagsConfig) if err != nil { - return err + return fmt.Errorf("creating Glue Crawler (%s): %w", name, err) } // Retry for IAM eventual consistency @@ -395,7 +395,7 @@ func resourceCrawlerCreate(d *schema.ResourceData, meta interface{}) error { _, err = glueConn.CreateCrawler(crawlerInput) } if err != nil { - return fmt.Errorf("error creating Glue crawler: %w", err) + return fmt.Errorf("creating Glue Crawler (%s): %w", name, err) } d.SetId(name) @@ -750,7 +750,7 @@ func resourceCrawlerUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChangesExcept("tags", "tags_all") { updateCrawlerInput, err := updateCrawlerInput(d, name) if err != nil { - return err + return fmt.Errorf("updating Glue Crawler (%s): %w", d.Id(), err) } // Retry for IAM eventual consistency @@ -786,7 +786,7 @@ func resourceCrawlerUpdate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error updating Glue crawler: %w", err) + return fmt.Errorf("updating Glue Crawler (%s): %w", d.Id(), err) } } @@ -1000,7 +1000,7 @@ func flattenDeltaTargets(deltaTargets []*glue.DeltaTarget) []map[string]interfac func resourceCrawlerDelete(d *schema.ResourceData, meta interface{}) error { glueConn := meta.(*conns.AWSClient).GlueConn() - log.Printf("[DEBUG] deleting Glue crawler: %s", d.Id()) + log.Printf("[DEBUG] deleting Glue Crawler: %s", d.Id()) _, err := glueConn.DeleteCrawler(&glue.DeleteCrawlerInput{ Name: aws.String(d.Id()), }) @@ -1008,7 +1008,7 @@ func resourceCrawlerDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, glue.ErrCodeEntityNotFoundException) { return nil } - return fmt.Errorf("error deleting Glue crawler: %w", err) + return fmt.Errorf("error deleting Glue Crawler: %w", err) } return nil } diff --git a/internal/service/glue/partition.go b/internal/service/glue/partition.go index ae60fd87004..325f7164a19 100644 --- a/internal/service/glue/partition.go +++ b/internal/service/glue/partition.go @@ -270,7 +270,7 @@ func resourcePartitionUpdate(d *schema.ResourceData, meta interface{}) error { catalogID, dbName, tableName, values, err := readPartitionID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Glue Partition (%s): %w", d.Id(), err) } input := &glue.UpdatePartitionInput{ @@ -281,9 +281,8 @@ func resourcePartitionUpdate(d *schema.ResourceData, meta interface{}) error { PartitionValueList: aws.StringSlice(values), } - log.Printf("[DEBUG] Updating Glue Partition: %#v", input) if _, err := conn.UpdatePartition(input); err != nil { - return fmt.Errorf("error updating Glue Partition: %w", err) + return fmt.Errorf("updating Glue Partition (%s): %w", d.Id(), err) } return resourcePartitionRead(d, meta) diff --git a/internal/service/glue/resource_policy.go b/internal/service/glue/resource_policy.go index 8953d642dc4..6ad44f72608 100644 --- a/internal/service/glue/resource_policy.go +++ b/internal/service/glue/resource_policy.go @@ -83,7 +83,7 @@ func resourceResourcePolicyRead(d *schema.ResourceData, meta interface{}) error return nil } if err != nil { - return fmt.Errorf("error reading policy request: %w", err) + return fmt.Errorf("reading Glue Resource Policy (%s): %w", d.Id(), err) } if aws.StringValue(resourcePolicy.PolicyInJson) == "" { @@ -93,7 +93,7 @@ func resourceResourcePolicyRead(d *schema.ResourceData, meta interface{}) error policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(resourcePolicy.PolicyInJson)) if err != nil { - return err + return fmt.Errorf("reading Glue Resource Policy (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) diff --git a/internal/service/glue/user_defined_function.go b/internal/service/glue/user_defined_function.go index acb3753df94..34fe94bd2d7 100644 --- a/internal/service/glue/user_defined_function.go +++ b/internal/service/glue/user_defined_function.go @@ -115,7 +115,7 @@ func resourceUserDefinedFunctionUpdate(d *schema.ResourceData, meta interface{}) catalogID, dbName, funcName, err := ReadUDFID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Glue User Defined Function (%s): %w", d.Id(), err) } input := &glue.UpdateUserDefinedFunctionInput{ @@ -126,7 +126,7 @@ func resourceUserDefinedFunctionUpdate(d *schema.ResourceData, meta interface{}) } if _, err := conn.UpdateUserDefinedFunction(input); err != nil { - return fmt.Errorf("error updating Glue User Defined Function (%s): %w", d.Id(), err) + return fmt.Errorf("updating Glue User Defined Function (%s): %w", d.Id(), err) } return resourceUserDefinedFunctionRead(d, meta) @@ -137,7 +137,7 @@ func resourceUserDefinedFunctionRead(d *schema.ResourceData, meta interface{}) e catalogID, dbName, funcName, err := ReadUDFID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Glue User Defined Function (%s): %w", d.Id(), err) } input := &glue.GetUserDefinedFunctionInput{ @@ -154,7 +154,7 @@ func resourceUserDefinedFunctionRead(d *schema.ResourceData, meta interface{}) e return nil } - return fmt.Errorf("error reading Glue User Defined Function: %w", err) + return fmt.Errorf("reading Glue User Defined Function (%s): %w", d.Id(), err) } udf := out.UserDefinedFunction @@ -178,7 +178,7 @@ func resourceUserDefinedFunctionRead(d *schema.ResourceData, meta interface{}) e d.Set("create_time", udf.CreateTime.Format(time.RFC3339)) } if err := d.Set("resource_uris", flattenUserDefinedFunctionResourceURI(udf.ResourceUris)); err != nil { - return err + return fmt.Errorf("reading Glue User Defined Function (%s): setting resource_uris: %w", d.Id(), err) } return nil @@ -188,7 +188,7 @@ func resourceUserDefinedFunctionDelete(d *schema.ResourceData, meta interface{}) conn := meta.(*conns.AWSClient).GlueConn() catalogID, dbName, funcName, err := ReadUDFID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Glue User Defined Function (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Glue User Defined Function: %s", d.Id()) @@ -198,7 +198,7 @@ func resourceUserDefinedFunctionDelete(d *schema.ResourceData, meta interface{}) FunctionName: aws.String(funcName), }) if err != nil { - return fmt.Errorf("error deleting Glue User Defined Function: %w", err) + return fmt.Errorf("deleting Glue User Defined Function (%s): %w", d.Id(), err) } return nil } From 0f4a5ac5ee14402e7efaf3c0606daa73e670226e Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 11:42:49 -0800 Subject: [PATCH 047/106] Fixes bare errors in `glacier` --- internal/service/glacier/vault.go | 8 ++++---- internal/service/glacier/vault_lock.go | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/service/glacier/vault.go b/internal/service/glacier/vault.go index 7f5c43fa02e..663a6b85a21 100644 --- a/internal/service/glacier/vault.go +++ b/internal/service/glacier/vault.go @@ -177,7 +177,7 @@ func resourceVaultRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("Error reading Glacier Vault: %w", err) + return fmt.Errorf("reading Glacier Vault (%s): %w", d.Id(), err) } awsClient := meta.(*conns.AWSClient) @@ -186,7 +186,7 @@ func resourceVaultRead(d *schema.ResourceData, meta interface{}) error { location, err := buildVaultLocation(awsClient.AccountID, d.Id()) if err != nil { - return err + return fmt.Errorf("reading Glacier Vault (%s): %w", d.Id(), err) } d.Set("location", location) @@ -215,12 +215,12 @@ func resourceVaultRead(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, glacier.ErrCodeResourceNotFoundException) { d.Set("access_policy", "") } else if err != nil { - return fmt.Errorf("error getting access policy for Glacier Vault (%s): %w", d.Id(), err) + return fmt.Errorf("reading Glacier Vault (%s): reading policy: %w", d.Id(), err) } else if pol != nil && pol.Policy != nil { policy, err := verify.PolicyToSet(d.Get("access_policy").(string), aws.StringValue(pol.Policy.Policy)) if err != nil { - return err + return fmt.Errorf("reading Glacier Vault (%s): setting policy: %w", d.Id(), err) } d.Set("access_policy", policy) diff --git a/internal/service/glacier/vault_lock.go b/internal/service/glacier/vault_lock.go index b567b10c468..9965cb36bbe 100644 --- a/internal/service/glacier/vault_lock.go +++ b/internal/service/glacier/vault_lock.go @@ -125,7 +125,7 @@ func resourceVaultLockRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Glacier Vault Lock (%s): %s", d.Id(), err) + return fmt.Errorf("reading Glacier Vault Lock (%s): %s", d.Id(), err) } if output == nil { @@ -140,7 +140,7 @@ func resourceVaultLockRead(d *schema.ResourceData, meta interface{}) error { policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(output.Policy)) if err != nil { - return err + return fmt.Errorf("reading Glacier Vault Lock (%s): setting policy: %s", d.Id(), err) } d.Set("policy", policyToSet) From e01d2db9e331280fedffb582986da1709149680e Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 11:50:21 -0800 Subject: [PATCH 048/106] Fixes bare errors in `gamelift` --- internal/service/gamelift/alias.go | 19 ++++++++++--------- internal/service/gamelift/build.go | 5 ++++- .../service/gamelift/game_server_group.go | 4 ++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/internal/service/gamelift/alias.go b/internal/service/gamelift/alias.go index cf531df5410..d41b8ef7bb4 100644 --- a/internal/service/gamelift/alias.go +++ b/internal/service/gamelift/alias.go @@ -88,10 +88,9 @@ func resourceAliasCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("description"); ok { input.Description = aws.String(v.(string)) } - log.Printf("[INFO] Creating GameLift Alias: %s", input) out, err := conn.CreateAlias(&input) if err != nil { - return err + return fmt.Errorf("creating GameLift Alias (%s): %w", d.Get("name").(string), err) } d.SetId(aws.StringValue(out.Alias.AliasId)) @@ -114,7 +113,7 @@ func resourceAliasRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[WARN] GameLift Alias (%s) not found, removing from state", d.Id()) return nil } - return err + return fmt.Errorf("reading GameLift Alias (%s): %w", d.Id(), err) } a := out.Alias @@ -126,7 +125,7 @@ func resourceAliasRead(d *schema.ResourceData, meta interface{}) error { tags, err := ListTags(conn, arn) if err != nil { - return fmt.Errorf("error listing tags for Game Lift Alias (%s): %s", arn, err) + return fmt.Errorf("reading GameLift Alias (%s): listing tags: %w", d.Id(), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -154,7 +153,7 @@ func resourceAliasUpdate(d *schema.ResourceData, meta interface{}) error { RoutingStrategy: expandRoutingStrategy(d.Get("routing_strategy").([]interface{})), }) if err != nil { - return err + return fmt.Errorf("updating GameLift Alias (%s): %w", d.Id(), err) } arn := d.Get("arn").(string) @@ -162,7 +161,7 @@ func resourceAliasUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating Game Lift Alias (%s) tags: %s", arn, err) + return fmt.Errorf("reading GameLift Alias (%s): updating tags: %w", d.Id(), err) } } @@ -173,10 +172,12 @@ func resourceAliasDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).GameLiftConn() log.Printf("[INFO] Deleting GameLift Alias: %s", d.Id()) - _, err := conn.DeleteAlias(&gamelift.DeleteAliasInput{ + if _, err := conn.DeleteAlias(&gamelift.DeleteAliasInput{ AliasId: aws.String(d.Id()), - }) - return err + }); err != nil { + return fmt.Errorf("deleting GameLift Alias (%s): %w", d.Id(), err) + } + return nil } func expandRoutingStrategy(cfg []interface{}) *gamelift.RoutingStrategy { diff --git a/internal/service/gamelift/build.go b/internal/service/gamelift/build.go index 630f2d1f76f..630e867262b 100644 --- a/internal/service/gamelift/build.go +++ b/internal/service/gamelift/build.go @@ -213,7 +213,10 @@ func resourceBuildDelete(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeleteBuild(&gamelift.DeleteBuildInput{ BuildId: aws.String(d.Id()), }) - return err + if err != nil { + return fmt.Errorf("deleting GameLift Build Client (%s): %w", d.Id(), err) + } + return nil } func expandStorageLocation(cfg []interface{}) *gamelift.S3Location { diff --git a/internal/service/gamelift/game_server_group.go b/internal/service/gamelift/game_server_group.go index 32b391b77f7..9f2401160ca 100644 --- a/internal/service/gamelift/game_server_group.go +++ b/internal/service/gamelift/game_server_group.go @@ -265,7 +265,7 @@ func resourceGameServerGroupRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading GameLift Game Server Group (%s): %w", gameServerGroupName, err) + return fmt.Errorf("reading GameLift Game Server Group (%s): %w", gameServerGroupName, err) } autoScalingGroupName := strings.Split(aws.StringValue(gameServerGroup.AutoScalingGroupArn), "/")[1] @@ -273,7 +273,7 @@ func resourceGameServerGroupRead(d *schema.ResourceData, meta interface{}) error AutoScalingGroupNames: []*string{aws.String(autoScalingGroupName)}, }) if err != nil { - return err + return fmt.Errorf("reading GameLift Game Server Group (%s): reading AutoScaling Group: %w", gameServerGroupName, err) } if autoScalingGroupOutput == nil || len(autoScalingGroupOutput.AutoScalingGroups) == 0 { return fmt.Errorf("error describing Auto Scaling Group (%s): not found", autoScalingGroupName) From db9809aaa6af732ef869640865aa747c7f0ba082 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 12:22:14 -0800 Subject: [PATCH 049/106] Fixes bare errors in `fms` --- internal/service/fms/policy.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/fms/policy.go b/internal/service/fms/policy.go index b0b4b65972a..7f542e4b43c 100644 --- a/internal/service/fms/policy.go +++ b/internal/service/fms/policy.go @@ -187,17 +187,17 @@ func resourcePolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading FMS Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading FMS Policy (%s): %w", d.Id(), err) } if err := resourcePolicyFlattenPolicy(d, output); err != nil { - return err + return fmt.Errorf("reading FMS Policy (%s): %w", d.Id(), err) } tags, err := ListTags(conn, d.Get("arn").(string)) if err != nil { - return fmt.Errorf("error listing tags for FMS Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading FMS Policy (%s): listing tags: %w", d.Id(), err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -290,20 +290,20 @@ func resourcePolicyFlattenPolicy(d *schema.ResourceData, resp *fms.GetPolicyOutp d.Set("name", resp.Policy.PolicyName) d.Set("exclude_resource_tags", resp.Policy.ExcludeResourceTags) if err := d.Set("exclude_map", flattenPolicyMap(resp.Policy.ExcludeMap)); err != nil { - return err + return fmt.Errorf("setting exclude_map: %w", err) } if err := d.Set("include_map", flattenPolicyMap(resp.Policy.IncludeMap)); err != nil { - return err + return fmt.Errorf("setting include_map: %w", err) } d.Set("remediation_enabled", resp.Policy.RemediationEnabled) if err := d.Set("resource_type_list", resp.Policy.ResourceTypeList); err != nil { - return err + return fmt.Errorf("setting resource_type_list: %w", err) } d.Set("delete_unused_fm_managed_resources", resp.Policy.DeleteUnusedFMManagedResources) d.Set("resource_type", resp.Policy.ResourceType) d.Set("policy_update_token", resp.Policy.PolicyUpdateToken) if err := d.Set("resource_tags", flattenResourceTags(resp.Policy.ResourceTags)); err != nil { - return err + return fmt.Errorf("setting resource_tags: %w", err) } securityServicePolicy := []map[string]string{{ @@ -311,7 +311,7 @@ func resourcePolicyFlattenPolicy(d *schema.ResourceData, resp *fms.GetPolicyOutp "managed_service_data": *resp.Policy.SecurityServicePolicyData.ManagedServiceData, }} if err := d.Set("security_service_policy_data", securityServicePolicy); err != nil { - return err + return fmt.Errorf("setting security_service_policy_data: %w", err) } return nil From ddf1e1e9ec6b7a412cf272fa6e234cf2d8319e80 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 12:22:31 -0800 Subject: [PATCH 050/106] Fixes bare errors in `firehose` --- internal/service/firehose/delivery_stream.go | 81 ++++++++++---------- 1 file changed, 40 insertions(+), 41 deletions(-) diff --git a/internal/service/firehose/delivery_stream.go b/internal/service/firehose/delivery_stream.go index 72b2e1a3ba5..48d7b793265 100644 --- a/internal/service/firehose/delivery_stream.go +++ b/internal/service/firehose/delivery_stream.go @@ -747,12 +747,12 @@ func flattenDeliveryStream(d *schema.ResourceData, s *firehose.DeliveryStreamDes } if err := d.Set("server_side_encryption", []map[string]interface{}{sseOptions}); err != nil { - return fmt.Errorf("error setting server_side_encryption: %s", err) + return fmt.Errorf("setting server_side_encryption: %s", err) } if s.Source != nil { if err := d.Set("kinesis_source_configuration", flattenSourceConfiguration(s.Source.KinesisStreamSourceDescription)); err != nil { - return fmt.Errorf("error setting kinesis_source_configuration: %s", err) + return fmt.Errorf("setting kinesis_source_configuration: %s", err) } } @@ -762,45 +762,45 @@ func flattenDeliveryStream(d *schema.ResourceData, s *firehose.DeliveryStreamDes d.Set("destination", destinationTypeRedshift) configuredPassword := d.Get("redshift_configuration.0.password").(string) if err := d.Set("redshift_configuration", flattenRedshiftConfiguration(destination.RedshiftDestinationDescription, configuredPassword)); err != nil { - return fmt.Errorf("error setting redshift_configuration: %s", err) + return fmt.Errorf("setting redshift_configuration: %s", err) } if err := d.Set("s3_configuration", flattenS3Configuration(destination.RedshiftDestinationDescription.S3DestinationDescription)); err != nil { - return fmt.Errorf("error setting s3_configuration: %s", err) + return fmt.Errorf("setting s3_configuration: %s", err) } } else if destination.ElasticsearchDestinationDescription != nil { d.Set("destination", destinationTypeElasticsearch) if err := d.Set("elasticsearch_configuration", flattenElasticsearchConfiguration(destination.ElasticsearchDestinationDescription)); err != nil { - return fmt.Errorf("error setting elasticsearch_configuration: %s", err) + return fmt.Errorf("setting elasticsearch_configuration: %s", err) } if err := d.Set("s3_configuration", flattenS3Configuration(destination.ElasticsearchDestinationDescription.S3DestinationDescription)); err != nil { - return fmt.Errorf("error setting s3_configuration: %s", err) + return fmt.Errorf("setting s3_configuration: %s", err) } } else if destination.SplunkDestinationDescription != nil { d.Set("destination", destinationTypeSplunk) if err := d.Set("splunk_configuration", flattenSplunkConfiguration(destination.SplunkDestinationDescription)); err != nil { - return fmt.Errorf("error setting splunk_configuration: %s", err) + return fmt.Errorf("setting splunk_configuration: %s", err) } if err := d.Set("s3_configuration", flattenS3Configuration(destination.SplunkDestinationDescription.S3DestinationDescription)); err != nil { - return fmt.Errorf("error setting s3_configuration: %s", err) + return fmt.Errorf("setting s3_configuration: %s", err) } } else if destination.HttpEndpointDestinationDescription != nil { d.Set("destination", destinationTypeHTTPEndpoint) configuredAccessKey := d.Get("http_endpoint_configuration.0.access_key").(string) if err := d.Set("http_endpoint_configuration", flattenHTTPEndpointConfiguration(destination.HttpEndpointDestinationDescription, configuredAccessKey)); err != nil { - return fmt.Errorf("error setting http_endpoint_configuration: %s", err) + return fmt.Errorf("setting http_endpoint_configuration: %s", err) } if err := d.Set("s3_configuration", flattenS3Configuration(destination.HttpEndpointDestinationDescription.S3DestinationDescription)); err != nil { - return fmt.Errorf("error setting s3_configuration: %s", err) + return fmt.Errorf("setting s3_configuration: %s", err) } } else if d.Get("destination").(string) == destinationTypeS3 { d.Set("destination", destinationTypeS3) if err := d.Set("s3_configuration", flattenS3Configuration(destination.S3DestinationDescription)); err != nil { - return fmt.Errorf("error setting s3_configuration: %s", err) + return fmt.Errorf("setting s3_configuration: %s", err) } } else { d.Set("destination", destinationTypeExtendedS3) if err := d.Set("extended_s3_configuration", flattenExtendedS3Configuration(destination.ExtendedS3DestinationDescription)); err != nil { - return fmt.Errorf("error setting extended_s3_configuration: %s", err) + return fmt.Errorf("setting extended_s3_configuration: %s", err) } } d.Set("destination_id", destination.DestinationId) @@ -2116,7 +2116,7 @@ func extractPrefixConfiguration(s3 map[string]interface{}) *string { func createRedshiftConfig(d *schema.ResourceData, s3Config *firehose.S3DestinationConfiguration) (*firehose.RedshiftDestinationConfiguration, error) { redshiftRaw, ok := d.GetOk("redshift_configuration") if !ok { - return nil, fmt.Errorf("Error loading Redshift Configuration for Kinesis Firehose: redshift_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("redshift_configuration", destinationTypeRedshift) } rl := redshiftRaw.([]interface{}) @@ -2149,7 +2149,7 @@ func createRedshiftConfig(d *schema.ResourceData, s3Config *firehose.S3Destinati func updateRedshiftConfig(d *schema.ResourceData, s3Update *firehose.S3DestinationUpdate) (*firehose.RedshiftDestinationUpdate, error) { redshiftRaw, ok := d.GetOk("redshift_configuration") if !ok { - return nil, fmt.Errorf("Error loading Redshift Configuration for Kinesis Firehose: redshift_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("redshift_configuration", destinationTypeRedshift) } rl := redshiftRaw.([]interface{}) @@ -2185,10 +2185,14 @@ func updateRedshiftConfig(d *schema.ResourceData, s3Update *firehose.S3Destinati return configuration, nil } +func elasticsearchDestinationRequiredParamErr(param, destination string) error { + return fmt.Errorf(`%q is required when "destination" is %q`, param, destination) +} + func createElasticsearchConfig(d *schema.ResourceData, s3Config *firehose.S3DestinationConfiguration) (*firehose.ElasticsearchDestinationConfiguration, error) { esConfig, ok := d.GetOk("elasticsearch_configuration") if !ok { - return nil, fmt.Errorf("Error loading Elasticsearch Configuration for Kinesis Firehose: elasticsearch_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("elasticsearch_configuration", destinationTypeElasticsearch) } esList := esConfig.([]interface{}) @@ -2236,7 +2240,7 @@ func createElasticsearchConfig(d *schema.ResourceData, s3Config *firehose.S3Dest func updateElasticsearchConfig(d *schema.ResourceData, s3Update *firehose.S3DestinationUpdate) (*firehose.ElasticsearchDestinationUpdate, error) { esConfig, ok := d.GetOk("elasticsearch_configuration") if !ok { - return nil, fmt.Errorf("Error loading Elasticsearch Configuration for Kinesis Firehose: elasticsearch_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("elasticsearch_configuration", destinationTypeElasticsearch) } esList := esConfig.([]interface{}) @@ -2277,7 +2281,7 @@ func updateElasticsearchConfig(d *schema.ResourceData, s3Update *firehose.S3Dest func createSplunkConfig(d *schema.ResourceData, s3Config *firehose.S3DestinationConfiguration) (*firehose.SplunkDestinationConfiguration, error) { splunkRaw, ok := d.GetOk("splunk_configuration") if !ok { - return nil, fmt.Errorf("Error loading Splunk Configuration for Kinesis Firehose: splunk_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("splunk_configuration", destinationTypeSplunk) } sl := splunkRaw.([]interface{}) @@ -2309,7 +2313,7 @@ func createSplunkConfig(d *schema.ResourceData, s3Config *firehose.S3Destination func updateSplunkConfig(d *schema.ResourceData, s3Update *firehose.S3DestinationUpdate) (*firehose.SplunkDestinationUpdate, error) { splunkRaw, ok := d.GetOk("splunk_configuration") if !ok { - return nil, fmt.Errorf("Error loading Splunk Configuration for Kinesis Firehose: splunk_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("splunk_configuration", destinationTypeSplunk) } sl := splunkRaw.([]interface{}) @@ -2341,7 +2345,7 @@ func updateSplunkConfig(d *schema.ResourceData, s3Update *firehose.S3Destination func createHTTPEndpointConfig(d *schema.ResourceData, s3Config *firehose.S3DestinationConfiguration) (*firehose.HttpEndpointDestinationConfiguration, error) { HttpEndpointRaw, ok := d.GetOk("http_endpoint_configuration") if !ok { - return nil, fmt.Errorf("Error loading HTTP Endpoint Configuration for Kinesis Firehose: http_endpoint_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("http_endpoint_configuration", destinationTypeHTTPEndpoint) } sl := HttpEndpointRaw.([]interface{}) @@ -2386,7 +2390,7 @@ func createHTTPEndpointConfig(d *schema.ResourceData, s3Config *firehose.S3Desti func updateHTTPEndpointConfig(d *schema.ResourceData, s3Update *firehose.S3DestinationUpdate) (*firehose.HttpEndpointDestinationUpdate, error) { HttpEndpointRaw, ok := d.GetOk("http_endpoint_configuration") if !ok { - return nil, fmt.Errorf("Error loading HTTP Endpoint Configuration for Kinesis Firehose: http_endpoint_configuration not found") + return nil, elasticsearchDestinationRequiredParamErr("http_endpoint_configuration", destinationTypeHTTPEndpoint) } sl := HttpEndpointRaw.([]interface{}) @@ -2584,25 +2588,25 @@ func resourceDeliveryStreamCreate(d *schema.ResourceData, meta interface{}) erro } else if d.Get("destination").(string) == destinationTypeElasticsearch { esConfig, err := createElasticsearchConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("creating Kinesis Firehose Delivery Stream: %s", err) } createInput.ElasticsearchDestinationConfiguration = esConfig } else if d.Get("destination").(string) == destinationTypeRedshift { rc, err := createRedshiftConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("creating Kinesis Firehose Delivery Stream: %s", err) } createInput.RedshiftDestinationConfiguration = rc } else if d.Get("destination").(string) == destinationTypeSplunk { rc, err := createSplunkConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("creating Kinesis Firehose Delivery Stream: %s", err) } createInput.SplunkDestinationConfiguration = rc } else if d.Get("destination").(string) == destinationTypeHTTPEndpoint { rc, err := createHTTPEndpointConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("creating Kinesis Firehose Delivery Stream: %s", err) } createInput.HttpEndpointDestinationConfiguration = rc } @@ -2646,13 +2650,13 @@ func resourceDeliveryStreamCreate(d *schema.ResourceData, meta interface{}) erro _, err = conn.CreateDeliveryStream(createInput) } if err != nil { - return fmt.Errorf("error creating Kinesis Firehose Delivery Stream: %s", err) + return fmt.Errorf("creating Kinesis Firehose Delivery Stream: %s", err) } s, err := waitDeliveryStreamCreated(conn, sn) if err != nil { - return fmt.Errorf("error waiting for Kinesis Firehose Delivery Stream (%s) create: %w", sn, err) + return fmt.Errorf("creating Kinesis Firehose Delivery Stream: waiting for completion: %s", err) } d.SetId(aws.StringValue(s.DeliveryStreamARN)) @@ -2737,7 +2741,7 @@ func resourceDeliveryStreamUpdate(d *schema.ResourceData, meta interface{}) erro } else if d.Get("destination").(string) == destinationTypeElasticsearch { esUpdate, err := updateElasticsearchConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("updating Kinesis Firehose Delivery Stream (%s): %s", sn, err) } updateInput.ElasticsearchDestinationUpdate = esUpdate } else if d.Get("destination").(string) == destinationTypeRedshift { @@ -2749,19 +2753,19 @@ func resourceDeliveryStreamUpdate(d *schema.ResourceData, meta interface{}) erro } rc, err := updateRedshiftConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("updating Kinesis Firehose Delivery Stream (%s): %s", sn, err) } updateInput.RedshiftDestinationUpdate = rc } else if d.Get("destination").(string) == destinationTypeSplunk { rc, err := updateSplunkConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("updating Kinesis Firehose Delivery Stream (%s): %s", sn, err) } updateInput.SplunkDestinationUpdate = rc } else if d.Get("destination").(string) == destinationTypeHTTPEndpoint { rc, err := updateHTTPEndpointConfig(d, s3Config) if err != nil { - return err + return fmt.Errorf("updating Kinesis Firehose Delivery Stream (%s): %s", sn, err) } updateInput.HttpEndpointDestinationUpdate = rc } @@ -2803,9 +2807,7 @@ func resourceDeliveryStreamUpdate(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf( - "Error Updating Kinesis Firehose Delivery Stream: \"%s\"\n%s", - sn, err) + return fmt.Errorf("updating Kinesis Firehose Delivery Stream (%s): %s", sn, err) } } @@ -2813,7 +2815,7 @@ func resourceDeliveryStreamUpdate(d *schema.ResourceData, meta interface{}) erro o, n := d.GetChange("tags_all") if err := UpdateTags(conn, sn, o, n); err != nil { - return fmt.Errorf("error updating Kinesis Firehose Delivery Stream (%s) tags: %s", sn, err) + return fmt.Errorf("updating Kinesis Firehose Delivery Stream (%s): updating tags: %s", sn, err) } } @@ -2868,19 +2870,16 @@ func resourceDeliveryStreamRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading Kinesis Firehose Delivery Stream (%s): %w", sn, err) + return fmt.Errorf("reading Kinesis Firehose Delivery Stream (%s): %w", sn, err) } - err = flattenDeliveryStream(d, s) - - if err != nil { - return err + if err := flattenDeliveryStream(d, s); err != nil { + return fmt.Errorf("reading Kinesis Firehose Delivery Stream (%s): %w", sn, err) } tags, err := ListTags(conn, sn) - if err != nil { - return fmt.Errorf("error listing tags for Kinesis Firehose Delivery Stream (%s): %w", sn, err) + return fmt.Errorf("reading Kinesis Firehose Delivery Stream (%s): listing tags: %w", sn, err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) From fb3a12e9fcc748949a8a0faee8cea1e073dd9732 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 12:26:28 -0800 Subject: [PATCH 051/106] Fixes bare errors in `events` --- internal/service/events/bus_policy.go | 9 ++++----- internal/service/events/rule.go | 20 ++++++++++---------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/internal/service/events/bus_policy.go b/internal/service/events/bus_policy.go index 4a1e8f150bb..26d02b54aad 100644 --- a/internal/service/events/bus_policy.go +++ b/internal/service/events/bus_policy.go @@ -120,7 +120,7 @@ func resourceBusPolicyRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error reading policy from EventBridge Bus (%s): %w", d.Id(), err) + return fmt.Errorf("reading policy from EventBridge Bus (%s): %w", d.Id(), err) } busName := aws.StringValue(output.Name) @@ -130,9 +130,8 @@ func resourceBusPolicyRead(d *schema.ResourceData, meta interface{}) error { d.Set("event_bus_name", busName) policyToSet, err := verify.PolicyToSet(d.Get("policy").(string), aws.StringValue(policy)) - if err != nil { - return err + return fmt.Errorf("reading policy from EventBridge Bus (%s): %w", d.Id(), err) } d.Set("policy", policyToSet) @@ -170,7 +169,7 @@ func resourceBusPolicyUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Update EventBridge Bus policy: %s", input) _, err = conn.PutPermission(&input) if err != nil { - return fmt.Errorf("error updating policy for EventBridge Bus (%s): %w", d.Id(), err) + return fmt.Errorf("updating policy for EventBridge Bus (%s): %w", d.Id(), err) } return resourceBusPolicyRead(d, meta) @@ -193,7 +192,7 @@ func resourceBusPolicyDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error deleting policy for EventBridge Bus (%s): %w", d.Id(), err) + return fmt.Errorf("deleting policy for EventBridge Bus (%s): %w", d.Id(), err) } return nil } diff --git a/internal/service/events/rule.go b/internal/service/events/rule.go index 70ca63dbf4a..0f7f2d9f7a3 100644 --- a/internal/service/events/rule.go +++ b/internal/service/events/rule.go @@ -111,7 +111,7 @@ func resourceRuleCreate(d *schema.ResourceData, meta interface{}) error { input, err := buildPutRuleInputStruct(d, name) if err != nil { - return err + return fmt.Errorf("creating EventBridge Rule (%s): %w", name, err) } if len(tags) > 0 { @@ -130,7 +130,7 @@ func resourceRuleCreate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error creating EventBridge Rule (%s): %w", name, err) + return fmt.Errorf("creating EventBridge Rule (%s): %w", name, err) } d.SetId(RuleCreateResourceID(aws.StringValue(input.EventBusName), aws.StringValue(input.Name))) @@ -160,7 +160,7 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { eventBusName, ruleName, err := RuleParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EventBridge Rule (%s): %w", d.Id(), err) } output, err := FindRuleByEventBusAndRuleNames(conn, eventBusName, ruleName) @@ -172,7 +172,7 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading EventBridge Rule (%s): %w", d.Id(), err) + return fmt.Errorf("reading EventBridge Rule (%s): %w", d.Id(), err) } arn := aws.StringValue(output.Arn) @@ -194,7 +194,7 @@ func resourceRuleRead(d *schema.ResourceData, meta interface{}) error { enabled, err := RuleEnabledFromState(aws.StringValue(output.State)) if err != nil { - return err + return fmt.Errorf("reading EventBridge Rule (%s): %w", d.Id(), err) } d.Set("is_enabled", enabled) @@ -231,13 +231,13 @@ func resourceRuleUpdate(d *schema.ResourceData, meta interface{}) error { _, ruleName, err := RuleParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating EventBridge Rule (%s): %w", d.Id(), err) } input, err := buildPutRuleInputStruct(d, ruleName) if err != nil { - return err + return fmt.Errorf("updating EventBridge Rule (%s): %w", d.Id(), err) } // IAM Roles take some time to propagate @@ -260,7 +260,7 @@ func resourceRuleUpdate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error updating EventBridge Rule (%s): %w", d.Id(), err) + return fmt.Errorf("updating EventBridge Rule (%s): %w", d.Id(), err) } arn := d.Get("arn").(string) @@ -288,7 +288,7 @@ func resourceRuleDelete(d *schema.ResourceData, meta interface{}) error { eventBusName, ruleName, err := RuleParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EventBridge Rule (%s): %w", d.Id(), err) } input := &eventbridge.DeleteRuleInput{ @@ -322,7 +322,7 @@ func resourceRuleDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting EventBridge Rule (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EventBridge Rule (%s): %w", d.Id(), err) } return nil From b0b8d81aba8fcb94b51f00cc15b1232b2dca37c8 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:27:16 -0800 Subject: [PATCH 052/106] Removes unnecessary `[ERROR]` in error messages --- .../traffic_policy_document_data_source_test.go | 12 ++++++------ internal/service/storagegateway/tape_pool.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/service/route53/traffic_policy_document_data_source_test.go b/internal/service/route53/traffic_policy_document_data_source_test.go index bbf7292d7a3..be5dfce448e 100644 --- a/internal/service/route53/traffic_policy_document_data_source_test.go +++ b/internal/service/route53/traffic_policy_document_data_source_test.go @@ -56,25 +56,25 @@ func testAccCheckTrafficPolicySameJSON(resourceName, jsonExpected string) resour var j, j2 tfrouter53.Route53TrafficPolicyDoc if err := json.Unmarshal([]byte(rs.Primary.Attributes["json"]), &j); err != nil { - return fmt.Errorf("[ERROR] json.Unmarshal %v", err) + return fmt.Errorf("json.Unmarshal: %w", err) } if err := json.Unmarshal([]byte(jsonExpected), &j2); err != nil { - return fmt.Errorf("[ERROR] json.Unmarshal %v", err) + return fmt.Errorf("json.Unmarshal: %w", err) } // Marshall again so it can re order the json data because of arrays jsonDoc, err := json.Marshal(j) if err != nil { - return fmt.Errorf("[ERROR] json.marshal %v", err) + return fmt.Errorf("json.Marshal: %w", err) } jsonDoc2, err := json.Marshal(j2) if err != nil { - return fmt.Errorf("[ERROR] json.marshal %v", err) + return fmt.Errorf("json.Marshal: %w", err) } if err = json.Unmarshal(jsonDoc, &j); err != nil { - return fmt.Errorf("[ERROR] json.Unmarshal %v", err) + return fmt.Errorf("json.Unmarshal: %w", err) } if err = json.Unmarshal(jsonDoc2, &j); err != nil { - return fmt.Errorf("[ERROR] json.Unmarshal %v", err) + return fmt.Errorf("json.Unmarshal: %w", err) } if !awsutil.DeepEqual(&j, &j2) { diff --git a/internal/service/storagegateway/tape_pool.go b/internal/service/storagegateway/tape_pool.go index 6832411df2d..def9c6dfe6c 100644 --- a/internal/service/storagegateway/tape_pool.go +++ b/internal/service/storagegateway/tape_pool.go @@ -112,7 +112,7 @@ func resourceTapePoolRead(d *schema.ResourceData, meta interface{}) error { output, err := conn.ListTapePools(input) if err != nil { - return fmt.Errorf("[ERROR] Listing Storage Gateway Tape Pools %w", err) + return fmt.Errorf("listing Storage Gateway Tape Pools: %w", err) } if output == nil || len(output.PoolInfos) == 0 || output.PoolInfos[0] == nil || aws.StringValue(output.PoolInfos[0].PoolARN) != d.Id() { From 56821d6f81fd30c74ddf1b03456b212ce42128fb Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:27:33 -0800 Subject: [PATCH 053/106] Fixes bare errors in `emr` --- internal/service/emr/cluster.go | 52 +++++++++---------- internal/service/emr/instance_group.go | 13 +++-- .../service/emr/security_configuration.go | 7 +-- .../service/emr/studio_session_mapping.go | 8 +-- 4 files changed, 38 insertions(+), 42 deletions(-) diff --git a/internal/service/emr/cluster.go b/internal/service/emr/cluster.go index 73e4643bcb2..99cb9a60774 100644 --- a/internal/service/emr/cluster.go +++ b/internal/service/emr/cluster.go @@ -3,6 +3,7 @@ package emr import ( "bytes" "encoding/json" + "errors" "fmt" "log" "net/http" @@ -1191,13 +1192,12 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EMRConn() if d.HasChange("visible_to_all_users") { - _, errModify := conn.SetVisibleToAllUsers(&emr.SetVisibleToAllUsersInput{ + _, err := conn.SetVisibleToAllUsers(&emr.SetVisibleToAllUsersInput{ JobFlowIds: []*string{aws.String(d.Id())}, VisibleToAllUsers: aws.Bool(d.Get("visible_to_all_users").(bool)), }) - if errModify != nil { - log.Printf("[ERROR] %s", errModify) - return errModify + if err != nil { + return fmt.Errorf("updating EMR Cluster (%s): setting visibility: %w", d.Id(), err) } } @@ -1206,35 +1206,32 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { if len(n.([]interface{})) > 0 { log.Printf("[DEBUG] Putting EMR cluster Auto Termination Policy") - _, errModify := conn.PutAutoTerminationPolicy(&emr.PutAutoTerminationPolicyInput{ + _, err := conn.PutAutoTerminationPolicy(&emr.PutAutoTerminationPolicyInput{ AutoTerminationPolicy: expandAutoTerminationPolicy(n.([]interface{})), ClusterId: aws.String(d.Id()), }) - if errModify != nil { - log.Printf("[ERROR] %s", errModify) - return errModify + if err != nil { + return fmt.Errorf("updating EMR Cluster (%s): setting auto termination policy: %w", d.Id(), err) } } else { log.Printf("[DEBUG] Removing EMR cluster Auto Termination Policy") - _, errModify := conn.RemoveAutoTerminationPolicy(&emr.RemoveAutoTerminationPolicyInput{ + _, err := conn.RemoveAutoTerminationPolicy(&emr.RemoveAutoTerminationPolicyInput{ ClusterId: aws.String(d.Id()), }) - if errModify != nil { - log.Printf("[ERROR] %s", errModify) - return errModify + if err != nil { + return fmt.Errorf("updating EMR Cluster (%s): removing auto termination policy: %w", d.Id(), err) } } } if d.HasChange("termination_protection") { - _, errModify := conn.SetTerminationProtection(&emr.SetTerminationProtectionInput{ + _, err := conn.SetTerminationProtection(&emr.SetTerminationProtectionInput{ JobFlowIds: []*string{aws.String(d.Id())}, TerminationProtected: aws.Bool(d.Get("termination_protection").(bool)), }) - if errModify != nil { - log.Printf("[ERROR] %s", errModify) - return errModify + if err != nil { + return fmt.Errorf("updating EMR Cluster (%s): setting termination protection: %w", d.Id(), err) } } @@ -1256,7 +1253,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { } if _, err := conn.PutAutoScalingPolicy(input); err != nil { - return fmt.Errorf("error updating EMR Cluster (%s) Instance Group (%s) Auto Scaling Policy: %s", d.Id(), instanceGroupID, err) + return fmt.Errorf("updating EMR Cluster (%s): setting autoscaling policy: %w", d.Id(), err) } } else { input := &emr.RemoveAutoScalingPolicyInput{ @@ -1265,7 +1262,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { } if _, err := conn.RemoveAutoScalingPolicy(input); err != nil { - return fmt.Errorf("error removing EMR Cluster (%s) Instance Group (%s) Auto Scaling Policy: %s", d.Id(), instanceGroupID, err) + return fmt.Errorf("updating EMR Cluster (%s): removing autoscaling policy: %w", d.Id(), err) } // RemoveAutoScalingPolicy seems to have eventual consistency. @@ -1278,7 +1275,7 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { } if autoscalingPolicy != nil { - return resource.RetryableError(fmt.Errorf("EMR Cluster (%s) Instance Group (%s) Auto Scaling Policy still exists", d.Id(), instanceGroupID)) + return resource.RetryableError(errors.New("still exists")) } return nil @@ -1290,12 +1287,12 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { autoscalingPolicy, err = getCoreInstanceGroupAutoScalingPolicy(conn, d.Id()) if autoscalingPolicy != nil { - err = fmt.Errorf("EMR Cluster (%s) Instance Group (%s) Auto Scaling Policy still exists", d.Id(), instanceGroupID) + err = errors.New("still exists") } } if err != nil { - return fmt.Errorf("error waiting for EMR Cluster (%s) Instance Group (%s) Auto Scaling Policy removal: %s", d.Id(), instanceGroupID, err) + return fmt.Errorf("updating EMR Cluster (%s): removing autoscaling policy: waiting for completion: %w", d.Id(), err) } } } @@ -1381,18 +1378,17 @@ func resourceClusterUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EMR Cluster (%s) tags: %s", d.Id(), err) + return fmt.Errorf("updating EMR Cluster (%s): setting tags: %w", d.Id(), err) } } if d.HasChange("step_concurrency_level") { - _, errModify := conn.ModifyCluster(&emr.ModifyClusterInput{ + _, err := conn.ModifyCluster(&emr.ModifyClusterInput{ ClusterId: aws.String(d.Id()), StepConcurrencyLevel: aws.Int64(int64(d.Get("step_concurrency_level").(int))), }) - if errModify != nil { - log.Printf("[ERROR] %s", errModify) - return errModify + if err != nil { + return fmt.Errorf("updating EMR Cluster (%s): updating step concurrency level: %w", d.Id(), err) } } @@ -1511,13 +1507,13 @@ func flattenAutoScalingPolicyDescription(policy *emr.AutoScalingPolicyDescriptio } autoscalingPolicyConstraintsBytes, err := json.Marshal(tmpAutoScalingPolicy.Constraints) if err != nil { - return "", fmt.Errorf("error parsing EMR Cluster Instance Groups AutoScalingPolicy Constraints: %w", err) + return "", fmt.Errorf("parsing EMR Cluster Instance Groups AutoScalingPolicy Constraints: %w", err) } autoscalingPolicyConstraintsString := string(autoscalingPolicyConstraintsBytes) autoscalingPolicyRulesBytes, err := json.Marshal(tmpAutoScalingPolicy.Rules) if err != nil { - return "", fmt.Errorf("error parsing EMR Cluster Instance Groups AutoScalingPolicy Rules: %w", err) + return "", fmt.Errorf("parsing EMR Cluster Instance Groups AutoScalingPolicy Rules: %w", err) } var rules []map[string]interface{} diff --git a/internal/service/emr/instance_group.go b/internal/service/emr/instance_group.go index 081c608ddf6..f876e94295e 100644 --- a/internal/service/emr/instance_group.go +++ b/internal/service/emr/instance_group.go @@ -2,6 +2,7 @@ package emr import ( "encoding/json" + "errors" "fmt" "log" "strings" @@ -183,20 +184,18 @@ func resourceInstanceGroupCreate(d *schema.ResourceData, meta interface{}) error JobFlowId: aws.String(d.Get("cluster_id").(string)), } - log.Printf("[DEBUG] Creating EMR %s group with the following params: %s", instanceRole, params) resp, err := conn.AddInstanceGroups(params) if err != nil { - return err + return fmt.Errorf("creating EMR Instance Group: %w", err) } - log.Printf("[DEBUG] Created EMR %s group finished: %#v", instanceRole, resp) if resp == nil || len(resp.InstanceGroupIds) == 0 { - return fmt.Errorf("Error creating instance groups: no instance group returned") + return errors.New("creating EMR Instance Group: empty response") } d.SetId(aws.StringValue(resp.InstanceGroupIds[0])) if err := waitForInstanceGroupStateRunning(conn, d.Get("cluster_id").(string), d.Id(), instanceGroupCreateTimeout); err != nil { - return fmt.Errorf("error waiting for EMR Instance Group (%s) creation: %s", d.Id(), err) + return fmt.Errorf("creating EMR Instance Group (%s): waiting for completion: %s", d.Id(), err) } return resourceInstanceGroupRead(d, meta) @@ -219,7 +218,7 @@ func resourceInstanceGroupRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return fmt.Errorf("error reading EMR Instance Group (%s): %s", d.Id(), err) + return fmt.Errorf("reading EMR Instance Group (%s): %s", d.Id(), err) } if ig.Status != nil { @@ -249,7 +248,7 @@ func resourceInstanceGroupRead(d *schema.ResourceData, meta interface{}) error { autoscalingPolicyString, err := flattenAutoScalingPolicyDescription(ig.AutoScalingPolicy) if err != nil { - return err + return fmt.Errorf("reading EMR Instance Group (%s): %s", d.Id(), err) } d.Set("autoscaling_policy", autoscalingPolicyString) diff --git a/internal/service/emr/security_configuration.go b/internal/service/emr/security_configuration.go index 52014cf34be..2699bf0d208 100644 --- a/internal/service/emr/security_configuration.go +++ b/internal/service/emr/security_configuration.go @@ -1,6 +1,7 @@ package emr import ( + "fmt" "log" "time" @@ -74,7 +75,7 @@ func resourceSecurityConfigurationCreate(d *schema.ResourceData, meta interface{ }) if err != nil { - return err + return fmt.Errorf("creating EMR Security Configuration (%s): %w", emrSCName, err) } d.SetId(aws.StringValue(resp.Name)) @@ -93,7 +94,7 @@ func resourceSecurityConfigurationRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return err + return fmt.Errorf("reading EMR Security Configuration (%s): %w", d.Id(), err) } d.Set("creation_date", aws.TimeValue(resp.CreationDateTime).Format(time.RFC3339)) @@ -113,7 +114,7 @@ func resourceSecurityConfigurationDelete(d *schema.ResourceData, meta interface{ if tfawserr.ErrMessageContains(err, "InvalidRequestException", "does not exist") { return nil } - return err + return fmt.Errorf("deleting EMR Security Configuration (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/emr/studio_session_mapping.go b/internal/service/emr/studio_session_mapping.go index 8103eee5f01..112942b36e1 100644 --- a/internal/service/emr/studio_session_mapping.go +++ b/internal/service/emr/studio_session_mapping.go @@ -96,7 +96,7 @@ func resourceStudioSessionMappingUpdate(d *schema.ResourceData, meta interface{} studioId, identityType, identityId, err := readStudioSessionMapping(d.Id()) if err != nil { - return err + return fmt.Errorf("updating EMR Studio Session Mapping (%s): %w", d.Id(), err) } input := &emr.UpdateStudioSessionMappingInput{ @@ -108,7 +108,7 @@ func resourceStudioSessionMappingUpdate(d *schema.ResourceData, meta interface{} _, err = conn.UpdateStudioSessionMapping(input) if err != nil { - return fmt.Errorf("error updating EMR Studio Session Mapping: %w", err) + return fmt.Errorf("updating EMR Studio Session Mapping (%s): %w", d.Id(), err) } return resourceStudioSessionMappingRead(d, meta) @@ -141,7 +141,7 @@ func resourceStudioSessionMappingDelete(d *schema.ResourceData, meta interface{} conn := meta.(*conns.AWSClient).EMRConn() studioId, identityType, identityId, err := readStudioSessionMapping(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EMR Studio Session Mapping (%s): %w", d.Id(), err) } input := &emr.DeleteStudioSessionMappingInput{ @@ -157,7 +157,7 @@ func resourceStudioSessionMappingDelete(d *schema.ResourceData, meta interface{} if tfawserr.ErrMessageContains(err, emr.ErrCodeInvalidRequestException, "Studio session mapping does not exist.") { return nil } - return fmt.Errorf("error deleting EMR Studio Session Mapping (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EMR Studio Session Mapping (%s): %w", d.Id(), err) } return nil From dfad739835e1dfbc7dffaeb99f69c995d0424a5e Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:27:47 -0800 Subject: [PATCH 054/106] Fixes bare errors in `elbv2` --- internal/service/elbv2/listener_certificate.go | 6 +++--- internal/service/elbv2/listener_rule.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/service/elbv2/listener_certificate.go b/internal/service/elbv2/listener_certificate.go index 5edc54b5cda..75df588e68c 100644 --- a/internal/service/elbv2/listener_certificate.go +++ b/internal/service/elbv2/listener_certificate.go @@ -91,7 +91,7 @@ func resourceListenerCertificateRead(d *schema.ResourceData, meta interface{}) e listenerArn, certificateArn, err := listenerCertificateParseID(d.Id()) if err != nil { - return fmt.Errorf("parsing ELBv2 Listener Certificate ID (%s): %w", d.Id(), err) + return fmt.Errorf("reading ELB v2 Listener Certificate (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Reading certificate: %s of listener: %s", certificateArn, listenerArn) @@ -119,11 +119,11 @@ func resourceListenerCertificateRead(d *schema.ResourceData, meta interface{}) e } if err != nil { if certificate == nil { - log.Printf("[WARN] %s - removing from state", err) + log.Printf("[WARN] ELB v2 Listener Certificate (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading ELB v2 Listener Certificate (%s): %w", d.Id(), err) } d.Set("certificate_arn", certificateArn) diff --git a/internal/service/elbv2/listener_rule.go b/internal/service/elbv2/listener_rule.go index b7fda425251..4c104076434 100644 --- a/internal/service/elbv2/listener_rule.go +++ b/internal/service/elbv2/listener_rule.go @@ -805,7 +805,7 @@ func resourceListenerRuleUpdate(d *schema.ResourceData, meta interface{}) error _, err := conn.SetRulePriorities(params) if err != nil { - return err + return fmt.Errorf("updating ELB v2 Listener Rule (%s): setting priority: %w", d.Id(), err) } } From bc29e4cbef6a7cd55bf15e3ec7768a07d00c6fa4 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:27:55 -0800 Subject: [PATCH 055/106] Fixes bare errors in `elb` --- .../elb/app_cookie_stickiness_policy.go | 11 ++++---- internal/service/elb/flex.go | 4 +-- .../elb/lb_cookie_stickiness_policy.go | 6 ++--- .../service/elb/lb_ssl_negotiation_policy.go | 10 +++---- internal/service/elb/load_balancer.go | 26 +++++++++---------- .../service/elb/load_balancer_data_source.go | 2 +- internal/service/elb/policy.go | 2 +- internal/service/elb/proxy_protocol_policy.go | 10 +++---- 8 files changed, 35 insertions(+), 36 deletions(-) diff --git a/internal/service/elb/app_cookie_stickiness_policy.go b/internal/service/elb/app_cookie_stickiness_policy.go index 0721bc1d980..753b46b384b 100644 --- a/internal/service/elb/app_cookie_stickiness_policy.go +++ b/internal/service/elb/app_cookie_stickiness_policy.go @@ -1,6 +1,7 @@ package elb import ( + "errors" "fmt" "log" "regexp" @@ -123,9 +124,9 @@ func resourceAppCookieStickinessPolicyRead(d *schema.ResourceData, meta interfac } // we know the policy exists now, but we have to check if it's assigned to a listener - assigned, err := resourceSticknessPolicyAssigned(policyName, lbName, lbPort, conn) + assigned, err := resourceSticknessPolicyAssigned(conn, policyName, lbName, lbPort) if err != nil { - return err + return fmt.Errorf("reading ELB Classic App Cookie Stickiness Policy (%s): %w", d.Id(), err) } if !d.IsNewResource() && !assigned { log.Printf("[WARN] ELB Classic LB (%s) App Cookie Policy (%s) exists, but isn't assigned to a listener", lbName, policyName) @@ -152,7 +153,7 @@ func resourceAppCookieStickinessPolicyRead(d *schema.ResourceData, meta interfac } // Determine if a particular policy is assigned to an ELB listener -func resourceSticknessPolicyAssigned(policyName, lbName, lbPort string, conn *elb.ELB) (bool, error) { +func resourceSticknessPolicyAssigned(conn *elb.ELB, policyName, lbName, lbPort string) (bool, error) { describeElbOpts := &elb.DescribeLoadBalancersInput{ LoadBalancerNames: []*string{aws.String(lbName)}, } @@ -163,11 +164,11 @@ func resourceSticknessPolicyAssigned(policyName, lbName, lbPort string, conn *el } if err != nil { - return false, fmt.Errorf("Error retrieving ELB description: %s", err) + return false, fmt.Errorf("retrieving LB: %s", err) } if len(describeResp.LoadBalancerDescriptions) != 1 { - return false, fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions) + return false, errors.New("retrieving LB: empty response") } lb := describeResp.LoadBalancerDescriptions[0] diff --git a/internal/service/elb/flex.go b/internal/service/elb/flex.go index 9549e000748..676525774b2 100644 --- a/internal/service/elb/flex.go +++ b/internal/service/elb/flex.go @@ -1,7 +1,7 @@ package elb import ( - "fmt" + "errors" "sort" "strings" @@ -124,7 +124,7 @@ func ExpandListeners(configured []interface{}) ([]*elb.Listener, error) { if valid { listeners = append(listeners, l) } else { - return nil, fmt.Errorf("ELB Listener: ssl_certificate_id may be set only when protocol is 'https' or 'ssl'") + return nil, errors.New(`"ssl_certificate_id" may be set only when "protocol" is "https" or "ssl"`) } } diff --git a/internal/service/elb/lb_cookie_stickiness_policy.go b/internal/service/elb/lb_cookie_stickiness_policy.go index 07d80ff46ef..0779134d9e6 100644 --- a/internal/service/elb/lb_cookie_stickiness_policy.go +++ b/internal/service/elb/lb_cookie_stickiness_policy.go @@ -117,9 +117,9 @@ func resourceCookieStickinessPolicyRead(d *schema.ResourceData, meta interface{} } // we know the policy exists now, but we have to check if it's assigned to a listener - assigned, err := resourceSticknessPolicyAssigned(policyName, lbName, lbPort, conn) + assigned, err := resourceSticknessPolicyAssigned(conn, policyName, lbName, lbPort) if err != nil { - return err + return fmt.Errorf("reading ELB Classic LB Cookie Stickiness Policy (%s): %w", d.Id(), err) } if !d.IsNewResource() && !assigned { // policy exists, but isn't assigned to a listener @@ -145,7 +145,7 @@ func resourceCookieStickinessPolicyRead(d *schema.ResourceData, meta interface{} d.Set("load_balancer", lbName) lbPortInt, err := strconv.Atoi(lbPort) if err != nil { - return err + return fmt.Errorf("reading ELB Classic LB Cookie Stickiness Policy (%s): parsing port number: %w", d.Id(), err) } d.Set("lb_port", lbPortInt) diff --git a/internal/service/elb/lb_ssl_negotiation_policy.go b/internal/service/elb/lb_ssl_negotiation_policy.go index 6bed98cd261..bda3858c139 100644 --- a/internal/service/elb/lb_ssl_negotiation_policy.go +++ b/internal/service/elb/lb_ssl_negotiation_policy.go @@ -114,7 +114,7 @@ func resourceSSLNegotiationPolicyRead(d *schema.ResourceData, meta interface{}) lbName, lbPort, policyName, err := SSLNegotiationPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading ELB Classic (%s) SSL Negotiation Policy: %w", lbName, err) } request := &elb.DescribeLoadBalancerPoliciesInput{ @@ -133,7 +133,7 @@ func resourceSSLNegotiationPolicyRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return fmt.Errorf("retrieving ELB Classic (%s) SSL Negotiation Policy: %w", lbName, err) + return fmt.Errorf("reading ELB Classic (%s) SSL Negotiation Policy: %w", lbName, err) } if len(getResp.PolicyDescriptions) != 1 { @@ -167,7 +167,7 @@ func resourceSSLNegotiationPolicyDelete(d *schema.ResourceData, meta interface{} lbName, _, policyName, err := SSLNegotiationPolicyParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting ELB Classic SSL Negotiation Policy (%s): %s", d.Id(), err) } // Perversely, if we Set an empty list of PolicyNames, we detach the @@ -180,7 +180,7 @@ func resourceSSLNegotiationPolicyDelete(d *schema.ResourceData, meta interface{} } if _, err := conn.SetLoadBalancerPoliciesOfListener(setLoadBalancerOpts); err != nil { - return fmt.Errorf("Error removing SSLNegotiationPolicy: %s", err) + return fmt.Errorf("removing SSLNegotiationPolicy: %s", err) } request := &elb.DeleteLoadBalancerPolicyInput{ @@ -189,7 +189,7 @@ func resourceSSLNegotiationPolicyDelete(d *schema.ResourceData, meta interface{} } if _, err := conn.DeleteLoadBalancerPolicy(request); err != nil { - return fmt.Errorf("Error deleting SSL negotiation policy %s: %s", d.Id(), err) + return fmt.Errorf("deleting ELB Classic SSL Negotiation Policy (%s): %s", d.Id(), err) } return nil } diff --git a/internal/service/elb/load_balancer.go b/internal/service/elb/load_balancer.go index 1a917c8cbcd..4d4c4549bf7 100644 --- a/internal/service/elb/load_balancer.go +++ b/internal/service/elb/load_balancer.go @@ -277,12 +277,6 @@ func resourceLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) - // Expand the "listener" set to aws-sdk-go compat []*elb.Listener - listeners, err := ExpandListeners(d.Get("listener").(*schema.Set).List()) - if err != nil { - return err - } - var elbName string if v, ok := d.GetOk("name"); ok { elbName = v.(string) @@ -295,6 +289,11 @@ func resourceLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error d.Set("name", elbName) } + // Expand the "listener" set to aws-sdk-go compat []*elb.Listener + listeners, err := ExpandListeners(d.Get("listener").(*schema.Set).List()) + if err != nil { + return fmt.Errorf("creating ELB Classic Load Balancer (%s): %s", elbName, err) + } // Provision the elb elbOpts := &elb.CreateLoadBalancerInput{ LoadBalancerName: aws.String(elbName), @@ -321,12 +320,11 @@ func resourceLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error elbOpts.Subnets = flex.ExpandStringSet(v.(*schema.Set)) } - log.Printf("[DEBUG] ELB create configuration: %#v", elbOpts) err = resource.Retry(5*time.Minute, func() *resource.RetryError { _, err := elbconn.CreateLoadBalancer(elbOpts) if tfawserr.ErrCodeEquals(err, elb.ErrCodeCertificateNotFoundException) { - return resource.RetryableError(fmt.Errorf("Error creating ELB Listener with SSL Cert, retrying: %w", err)) + return resource.RetryableError(fmt.Errorf("creating ELB Listener with SSL Cert, retrying: %w", err)) } if err != nil { @@ -339,7 +337,7 @@ func resourceLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error _, err = elbconn.CreateLoadBalancer(elbOpts) } if err != nil { - return fmt.Errorf("Error creating ELB: %s", err) + return fmt.Errorf("creating ELB Classic Load Balancer (%s): %s", elbName, err) } // Assign the elb's unique identifier for use later @@ -384,11 +382,11 @@ func resourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions) } - return flattenLoadBalancerEResource(d, meta.(*conns.AWSClient).EC2Conn(), elbconn, describeResp.LoadBalancerDescriptions[0], ignoreTagsConfig, defaultTagsConfig) + return flattenLoadBalancerResource(d, meta.(*conns.AWSClient).EC2Conn(), elbconn, describeResp.LoadBalancerDescriptions[0], ignoreTagsConfig, defaultTagsConfig) } -// flattenLoadBalancerEResource takes a *elbv2.LoadBalancer and populates all respective resource fields. -func flattenLoadBalancerEResource(d *schema.ResourceData, ec2conn *ec2.EC2, elbconn *elb.ELB, lb *elb.LoadBalancerDescription, ignoreTagsConfig *tftags.IgnoreConfig, defaultTagsConfig *tftags.DefaultConfig) error { +// flattenLoadBalancerResource takes a *elb.LoadBalancerDescription and populates all respective resource fields. +func flattenLoadBalancerResource(d *schema.ResourceData, ec2conn *ec2.EC2, elbconn *elb.ELB, lb *elb.LoadBalancerDescription, ignoreTagsConfig *tftags.IgnoreConfig, defaultTagsConfig *tftags.DefaultConfig) error { describeAttrsOpts := &elb.DescribeLoadBalancerAttributesInput{ LoadBalancerName: aws.String(d.Id()), } @@ -458,7 +456,7 @@ func flattenLoadBalancerEResource(d *schema.ResourceData, ec2conn *ec2.EC2, elbc elbal = nil } if err := d.Set("access_logs", flattenAccessLog(elbal)); err != nil { - return err + return fmt.Errorf("reading ELB Classic Load Balancer (%s): setting access_logs: %w", d.Id(), err) } } @@ -506,7 +504,7 @@ func resourceLoadBalancerUpdate(d *schema.ResourceData, meta interface{}) error remove, _ := ExpandListeners(os.Difference(ns).List()) add, err := ExpandListeners(ns.Difference(os).List()) if err != nil { - return err + return fmt.Errorf("updating ELB Classic Load Balancer (%s): %s", d.Id(), err) } if len(remove) > 0 { diff --git a/internal/service/elb/load_balancer_data_source.go b/internal/service/elb/load_balancer_data_source.go index 1cd246f2569..bd1d1007e6c 100644 --- a/internal/service/elb/load_balancer_data_source.go +++ b/internal/service/elb/load_balancer_data_source.go @@ -306,7 +306,7 @@ func dataSourceLoadBalancerRead(d *schema.ResourceData, meta interface{}) error elbal = nil } if err := d.Set("access_logs", flattenAccessLog(elbal)); err != nil { - return err + return fmt.Errorf("reading ELB Classic Load Balancer (%s): setting access_logs: %w", d.Id(), err) } } diff --git a/internal/service/elb/policy.go b/internal/service/elb/policy.go index a18dc538c49..19c29dee6c2 100644 --- a/internal/service/elb/policy.go +++ b/internal/service/elb/policy.go @@ -164,7 +164,7 @@ func resourcePolicyUpdate(d *schema.ResourceData, meta interface{}) error { err = resourcePolicyCreate(d, meta) if err != nil { - return err + return fmt.Errorf("updating ELB Classic Policy (%s): %w", d.Id(), err) } for _, listenerAssignment := range reassignments.listenerPolicies { diff --git a/internal/service/elb/proxy_protocol_policy.go b/internal/service/elb/proxy_protocol_policy.go index fdd0cf7be19..b39a3f87d7a 100644 --- a/internal/service/elb/proxy_protocol_policy.go +++ b/internal/service/elb/proxy_protocol_policy.go @@ -123,13 +123,13 @@ func resourceProxyProtocolPolicyUpdate(d *schema.ResourceData, meta interface{}) i, err := resourceProxyProtocolPolicyRemove(policyName, remove, backends) if err != nil { - return err + return fmt.Errorf("updating ELB Classic Proxy Protocol Policy (%s): %w", d.Id(), err) } inputs = append(inputs, i...) i, err = resourceProxyProtocolPolicyAdd(policyName, add, backends) if err != nil { - return err + return fmt.Errorf("updating ELB Classic Proxy Protocol Policy (%s): %w", d.Id(), err) } inputs = append(inputs, i...) @@ -166,7 +166,7 @@ func resourceProxyProtocolPolicyDelete(d *schema.ResourceData, meta interface{}) inputs, err := resourceProxyProtocolPolicyRemove(policyName, ports, backends) if err != nil { - return fmt.Errorf("Error detaching a policy from backend: %w", err) + return fmt.Errorf("deleting ELB Classic Proxy Protocol Policy (%s): %w", d.Id(), err) } for _, input := range inputs { input.LoadBalancerName = elbname @@ -191,7 +191,7 @@ func resourceProxyProtocolPolicyRemove(policyName string, ports []interface{}, b for _, p := range ports { ip, err := strconv.ParseInt(p.(string), 10, 64) if err != nil { - return nil, fmt.Errorf("Error detaching the policy: %s", err) + return nil, fmt.Errorf("detaching the policy: %s", err) } newPolicies := []*string{} @@ -222,7 +222,7 @@ func resourceProxyProtocolPolicyAdd(policyName string, ports []interface{}, back for _, p := range ports { ip, err := strconv.ParseInt(p.(string), 10, 64) if err != nil { - return nil, fmt.Errorf("Error attaching the policy: %s", err) + return nil, fmt.Errorf("attaching the policy: %s", err) } newPolicies := []*string{} From 81981170a3569876c746bed797889cbceefe4f91 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:28:20 -0800 Subject: [PATCH 056/106] Fixes bare errors in `elastictranscoder` --- .../service/elastictranscoder/pipeline.go | 6 ++--- internal/service/elastictranscoder/preset.go | 27 ++++++++++--------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/internal/service/elastictranscoder/pipeline.go b/internal/service/elastictranscoder/pipeline.go index ecda66d548f..099b20a0419 100644 --- a/internal/service/elastictranscoder/pipeline.go +++ b/internal/service/elastictranscoder/pipeline.go @@ -461,15 +461,13 @@ func resourcePipelineRead(d *schema.ResourceData, meta interface{}) error { if err != nil { if tfawserr.ErrCodeEquals(err, elastictranscoder.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] No such resource found for Elastic Transcoder Pipeline (%s)", d.Id()) + log.Printf("[WARN] Elastic Transcoder Pipeline (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading Elastic Transcoder Pipeline (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Elastic Transcoder Pipeline Read response: %#v", resp) - pipeline := resp.Pipeline d.Set("arn", pipeline.Arn) diff --git a/internal/service/elastictranscoder/preset.go b/internal/service/elastictranscoder/preset.go index 5e9ae5d87f9..394eaac11ef 100644 --- a/internal/service/elastictranscoder/preset.go +++ b/internal/service/elastictranscoder/preset.go @@ -754,26 +754,25 @@ func resourcePresetRead(d *schema.ResourceData, meta interface{}) error { if err != nil { if tfawserr.ErrCodeEquals(err, elastictranscoder.ErrCodeResourceNotFoundException) { - log.Printf("[WARN] ElasticTranscoder Preset (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] Elastic Transcoder Preset (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading Elastic Transcoder Preset (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Elastic Transcoder Preset Read response: %#v", resp) - preset := resp.Preset d.Set("arn", preset.Arn) if preset.Audio != nil { - err := d.Set("audio", flattenETAudioParameters(preset.Audio)) - if err != nil { - return err + if err := d.Set("audio", flattenETAudioParameters(preset.Audio)); err != nil { + return fmt.Errorf("reading Elastic Transcoder Preset (%s): setting audio: %w", d.Id(), err) } if preset.Audio.CodecOptions != nil { - d.Set("audio_codec_options", flattenETAudioCodecOptions(preset.Audio.CodecOptions)) + if err := d.Set("audio_codec_options", flattenETAudioCodecOptions(preset.Audio.CodecOptions)); err != nil { + return fmt.Errorf("reading Elastic Transcoder Preset (%s): setting audio_codec_options: %w", d.Id(), err) + } } } @@ -784,7 +783,7 @@ func resourcePresetRead(d *schema.ResourceData, meta interface{}) error { if preset.Thumbnails != nil { err := d.Set("thumbnails", flattenETThumbnails(preset.Thumbnails)) if err != nil { - return err + return fmt.Errorf("reading Elastic Transcoder Preset (%s): setting thumbnails: %w", d.Id(), err) } } @@ -793,15 +792,19 @@ func resourcePresetRead(d *schema.ResourceData, meta interface{}) error { if preset.Video != nil { err := d.Set("video", flattenETVideoParams(preset.Video)) if err != nil { - return err + return fmt.Errorf("reading Elastic Transcoder Preset (%s): setting video: %w", d.Id(), err) } if preset.Video.CodecOptions != nil { - d.Set("video_codec_options", aws.StringValueMap(preset.Video.CodecOptions)) + if err := d.Set("video_codec_options", aws.StringValueMap(preset.Video.CodecOptions)); err != nil { + return fmt.Errorf("reading Elastic Transcoder Preset (%s): setting video_codec_options: %w", d.Id(), err) + } } if preset.Video.Watermarks != nil { - d.Set("video_watermarks", flattenETWatermarks(preset.Video.Watermarks)) + if err := d.Set("video_watermarks", flattenETWatermarks(preset.Video.Watermarks)); err != nil { + return fmt.Errorf("reading Elastic Transcoder Preset (%s): setting video_watermarks: %w", d.Id(), err) + } } } From c8daebe7c21fb0e651132e1fe13b727f94a23e76 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:28:36 -0800 Subject: [PATCH 057/106] Fixes bare errors in `elasticsearch` --- internal/service/elasticsearch/domain.go | 6 +++--- internal/service/elasticsearch/domain_policy.go | 14 ++++++-------- .../service/elasticsearch/domain_saml_options.go | 8 ++++---- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/internal/service/elasticsearch/domain.go b/internal/service/elasticsearch/domain.go index 3eb1fbc25cb..2d9d2272e98 100644 --- a/internal/service/elasticsearch/domain.go +++ b/internal/service/elasticsearch/domain.go @@ -722,7 +722,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Elasticsearch Domain (%s): %w", d.Id(), err) + return fmt.Errorf("reading Elasticsearch Domain (%s): %w", d.Id(), err) } output, err := conn.DescribeElasticsearchDomainConfig(&elasticsearch.DescribeElasticsearchDomainConfigInput{ @@ -730,7 +730,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("error reading Elasticsearch Domain (%s) config: %w", d.Id(), err) + return fmt.Errorf("reading Elasticsearch Domain (%s) config: %w", d.Id(), err) } dc := output.DomainConfig @@ -739,7 +739,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { policies, err := verify.PolicyToSet(d.Get("access_policies").(string), v) if err != nil { - return err + return fmt.Errorf("reading Elasticsearch Domain (%s) config: setting policy: %w", d.Id(), err) } d.Set("access_policies", policies) diff --git a/internal/service/elasticsearch/domain_policy.go b/internal/service/elasticsearch/domain_policy.go index e3fbb48ff86..78f77e6da66 100644 --- a/internal/service/elasticsearch/domain_policy.go +++ b/internal/service/elasticsearch/domain_policy.go @@ -59,15 +59,13 @@ func resourceDomainPolicyRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Elasticsearch Domain Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading Elasticsearch Domain Policy (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Received Elasticsearch domain: %s", ds) - policies, err := verify.PolicyToSet(d.Get("access_policies").(string), aws.StringValue(ds.AccessPolicies)) if err != nil { - return err + return fmt.Errorf("reading Elasticsearch Domain Policy (%s): %w", d.Id(), err) } d.Set("access_policies", policies) @@ -90,13 +88,13 @@ func resourceDomainPolicyUpsert(d *schema.ResourceData, meta interface{}) error AccessPolicies: aws.String(policy), }) if err != nil { - return err + return fmt.Errorf("setting Elasticsearch Domain Policy (%s): %w", d.Id(), err) } d.SetId("esd-policy-" + domainName) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for Elasticsearch Domain Policy (%s) to be updated: %w", d.Id(), err) + return fmt.Errorf("setting Elasticsearch Domain Policy (%s): waiting for completion: %w", d.Id(), err) } return resourceDomainPolicyRead(d, meta) @@ -110,13 +108,13 @@ func resourceDomainPolicyDelete(d *schema.ResourceData, meta interface{}) error AccessPolicies: aws.String(""), }) if err != nil { - return err + return fmt.Errorf("deleting Elasticsearch Domain Policy (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Waiting for Elasticsearch domain policy %q to be deleted", d.Get("domain_name").(string)) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for Elasticsearch Domain Policy (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting Elasticsearch Domain Policy (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/elasticsearch/domain_saml_options.go b/internal/service/elasticsearch/domain_saml_options.go index 5a871c71c27..16463181d23 100644 --- a/internal/service/elasticsearch/domain_saml_options.go +++ b/internal/service/elasticsearch/domain_saml_options.go @@ -151,13 +151,13 @@ func resourceDomainSAMLOptionsPut(d *schema.ResourceData, meta interface{}) erro }) if err != nil { - return err + return fmt.Errorf("setting Elasticsearch Domain SAML Options (%s): %w", d.Id(), err) } d.SetId(domainName) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for Elasticsearch Domain SAML Options update (%s) to succeed: %w", d.Id(), err) + return fmt.Errorf("setting Elasticsearch Domain SAML Options (%s): waiting for completion: %w", d.Id(), err) } return resourceDomainSAMLOptionsRead(d, meta) @@ -175,13 +175,13 @@ func resourceDomainSAMLOptionsDelete(d *schema.ResourceData, meta interface{}) e AdvancedSecurityOptions: &config, }) if err != nil { - return err + return fmt.Errorf("deleting Elasticsearch Domain SAML Options (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Waiting for Elasticsearch domain SAML Options %q to be deleted", d.Get("domain_name").(string)) if err := waitForDomainUpdate(conn, d.Get("domain_name").(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for Elasticsearch Domain SAML Options (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting Elasticsearch Domain SAML Options (%s): waiting for completion: %w", d.Id(), err) } return nil From f5ebd6bfcb0e95f62891c31db48ee91dd33631eb Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:28:54 -0800 Subject: [PATCH 058/106] Fixes bare errors in `elasticbeanstalk` --- .../service/elasticbeanstalk/application.go | 30 ++--- .../elasticbeanstalk/application_version.go | 14 +-- .../configuration_template.go | 14 ++- .../service/elasticbeanstalk/environment.go | 118 +++++++----------- .../solution_stack_data_source.go | 2 +- 5 files changed, 76 insertions(+), 102 deletions(-) diff --git a/internal/service/elasticbeanstalk/application.go b/internal/service/elasticbeanstalk/application.go index dd4a2e381d4..9bd2979242f 100644 --- a/internal/service/elasticbeanstalk/application.go +++ b/internal/service/elasticbeanstalk/application.go @@ -92,13 +92,13 @@ func resourceApplicationCreate(d *schema.ResourceData, meta interface{}) error { app, err := beanstalkConn.CreateApplication(req) if err != nil { - return err + return fmt.Errorf("creating Elastic Beanstalk Application (%s): %w", name, err) } d.SetId(name) - if err = resourceApplicationAppversionLifecycleUpdate(beanstalkConn, d, app.Application); err != nil { - return err + if err = resourceApplicationAppVersionLifecycleUpdate(beanstalkConn, d, app.Application); err != nil { + return fmt.Errorf("creating Elastic Beanstalk Application (%s): %w", name, err) } return resourceApplicationRead(d, meta) @@ -109,13 +109,13 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("description") { if err := resourceApplicationDescriptionUpdate(conn, d); err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Application (%s): %w", d.Id(), err) } } if d.HasChange("appversion_lifecycle") { - if err := resourceApplicationAppversionLifecycleUpdate(conn, d, nil); err != nil { - return err + if err := resourceApplicationAppVersionLifecycleUpdate(conn, d, nil); err != nil { + return fmt.Errorf("updating Elastic Beanstalk Application (%s): %w", d.Id(), err) } } @@ -124,7 +124,7 @@ func resourceApplicationUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating Elastic Beanstalk Application (%s) tags: %s", arn, err) + return fmt.Errorf("updating Elastic Beanstalk Application (%s): updating tags: %w", d.Id(), err) } } @@ -145,7 +145,7 @@ func resourceApplicationDescriptionUpdate(beanstalkConn *elasticbeanstalk.Elasti return err } -func resourceApplicationAppversionLifecycleUpdate(beanstalkConn *elasticbeanstalk.ElasticBeanstalk, d *schema.ResourceData, app *elasticbeanstalk.ApplicationDescription) error { +func resourceApplicationAppVersionLifecycleUpdate(beanstalkConn *elasticbeanstalk.ElasticBeanstalk, d *schema.ResourceData, app *elasticbeanstalk.ApplicationDescription) error { name := d.Get("name").(string) appversion_lifecycles := d.Get("appversion_lifecycle").([]interface{}) var appversion_lifecycle map[string]interface{} = nil @@ -161,8 +161,6 @@ func resourceApplicationAppversionLifecycleUpdate(beanstalkConn *elasticbeanstal return nil } - log.Printf("[DEBUG] Elastic Beanstalk application: %s, update appversion_lifecycle: %v", name, appversion_lifecycle) - rlc := &elasticbeanstalk.ApplicationResourceLifecycleConfig{ ServiceRole: nil, VersionLifecycleConfig: &elasticbeanstalk.ApplicationVersionLifecycleConfig{ @@ -213,8 +211,10 @@ func resourceApplicationAppversionLifecycleUpdate(beanstalkConn *elasticbeanstal ApplicationName: aws.String(name), ResourceLifecycleConfig: rlc, }) - - return err + if err != nil { + return fmt.Errorf("updating application resource lifecycle: %w", err) + } + return nil } func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { @@ -248,7 +248,7 @@ func resourceApplicationRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading Elastic Beanstalk Application (%s): %w", d.Id(), err) } arn := aws.StringValue(app.ApplicationArn) @@ -287,7 +287,7 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { ApplicationName: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("deleting Elastic Beanstalk Application (%s): %w", d.Id(), err) } var app *elasticbeanstalk.ApplicationDescription @@ -307,7 +307,7 @@ func resourceApplicationDelete(d *schema.ResourceData, meta interface{}) error { app, err = getApplication(d.Id(), meta.(*conns.AWSClient).ElasticBeanstalkConn()) } if err != nil { - return fmt.Errorf("Error deleting Beanstalk application: %s", err) + return fmt.Errorf("deleting Elastic Beanstalk Application (%s): %w", d.Id(), err) } return nil } diff --git a/internal/service/elasticbeanstalk/application_version.go b/internal/service/elasticbeanstalk/application_version.go index e870fa33ec6..e6c1642b741 100644 --- a/internal/service/elasticbeanstalk/application_version.go +++ b/internal/service/elasticbeanstalk/application_version.go @@ -87,14 +87,12 @@ func resourceApplicationVersionCreate(d *schema.ResourceData, meta interface{}) VersionLabel: aws.String(name), } - log.Printf("[DEBUG] Elastic Beanstalk Application Version create opts: %s", createOpts) _, err := conn.CreateApplicationVersion(&createOpts) if err != nil { - return err + return fmt.Errorf("creating Elastic Beanstalk Application Version (%s): %w", name, err) } d.SetId(name) - log.Printf("[INFO] Elastic Beanstalk Application Version Label: %s", name) return resourceApplicationVersionRead(d, meta) } @@ -109,7 +107,7 @@ func resourceApplicationVersionRead(d *schema.ResourceData, meta interface{}) er VersionLabels: []*string{aws.String(d.Id())}, }) if err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Application Version (%s): %w", d.Id(), err) } if len(resp.ApplicationVersions) == 0 { @@ -152,7 +150,7 @@ func resourceApplicationVersionUpdate(d *schema.ResourceData, meta interface{}) if d.HasChange("description") { if err := resourceApplicationVersionDescriptionUpdate(conn, d); err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Application Version (%s): %w", d.Id(), err) } } @@ -161,7 +159,7 @@ func resourceApplicationVersionUpdate(d *schema.ResourceData, meta interface{}) o, n := d.GetChange("tags_all") if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating Elastic Beanstalk Application version (%s) tags: %s", arn, err) + return fmt.Errorf("updating Elastic Beanstalk Application Version (%s): setting tags: %w", d.Id(), err) } } @@ -177,7 +175,7 @@ func resourceApplicationVersionDelete(d *schema.ResourceData, meta interface{}) if !d.Get("force_delete").(bool) { environments, err := versionUsedBy(application, name, conn) if err != nil { - return err + return fmt.Errorf("deleting Elastic Beanstalk Application Version (%s): %w", d.Id(), err) } if len(environments) > 1 { @@ -207,8 +205,6 @@ func resourceApplicationVersionDescriptionUpdate(conn *elasticbeanstalk.ElasticB description := d.Get("description").(string) name := d.Get("name").(string) - log.Printf("[DEBUG] Elastic Beanstalk application version: %s, update description: %s", name, description) - _, err := conn.UpdateApplicationVersion(&elasticbeanstalk.UpdateApplicationVersionInput{ ApplicationName: aws.String(application), Description: aws.String(description), diff --git a/internal/service/elasticbeanstalk/configuration_template.go b/internal/service/elasticbeanstalk/configuration_template.go index 985aea85f17..ee31950e1db 100644 --- a/internal/service/elasticbeanstalk/configuration_template.go +++ b/internal/service/elasticbeanstalk/configuration_template.go @@ -114,15 +114,15 @@ func resourceConfigurationTemplateRead(d *schema.ResourceData, meta interface{}) return nil } } - return err + return fmt.Errorf("reading Elastic Beanstalk Configuration Template (%s): %w", d.Id(), err) } if len(resp.ConfigurationSettings) != 1 { - log.Printf("[DEBUG] Elastic Beanstalk unexpected describe configuration template response: %+v", resp) return fmt.Errorf("Error reading application properties: found %d applications, expected 1", len(resp.ConfigurationSettings)) } d.Set("description", resp.ConfigurationSettings[0].Description) + return nil } @@ -133,13 +133,13 @@ func resourceConfigurationTemplateUpdate(d *schema.ResourceData, meta interface{ if d.HasChange("description") { if err := resourceConfigurationTemplateDescriptionUpdate(conn, d); err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Configuration Template (%s): %w", d.Id(), err) } } if d.HasChange("setting") { if err := resourceConfigurationTemplateOptionSettingsUpdate(conn, d); err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Configuration Template (%s): %w", d.Id(), err) } } @@ -231,8 +231,10 @@ func resourceConfigurationTemplateDelete(d *schema.ResourceData, meta interface{ ApplicationName: aws.String(application), TemplateName: aws.String(d.Id()), }) - - return err + if err != nil { + return fmt.Errorf("deleting Elastic Beanstalk Configuration Template (%s): %w", d.Id(), err) + } + return nil } func gatherOptionSettings(d *schema.ResourceData) []*elasticbeanstalk.ConfigurationOptionSetting { diff --git a/internal/service/elasticbeanstalk/environment.go b/internal/service/elasticbeanstalk/environment.go index c6cb0a70b04..4ed43349634 100644 --- a/internal/service/elasticbeanstalk/environment.go +++ b/internal/service/elasticbeanstalk/environment.go @@ -285,10 +285,9 @@ func resourceEnvironmentCreate(d *schema.ResourceData, meta interface{}) error { // Get the current time to filter getEnvironmentErrors messages t := time.Now() - log.Printf("[DEBUG] Elastic Beanstalk Environment create opts: %s", createOpts) resp, err := conn.CreateEnvironment(&createOpts) if err != nil { - return err + return fmt.Errorf("creating Elastic Beanstalk Environment (%s): %w", name, err) } // Assign the application name as the resource ID @@ -296,7 +295,7 @@ func resourceEnvironmentCreate(d *schema.ResourceData, meta interface{}) error { waitForReadyTimeOut, err := time.ParseDuration(d.Get("wait_for_ready_timeout").(string)) if err != nil { - return err + return fmt.Errorf("creating Elastic Beanstalk Environment (%s): %w", name, err) } pollInterval, err := time.ParseDuration(d.Get("poll_interval").(string)) @@ -307,12 +306,12 @@ func resourceEnvironmentCreate(d *schema.ResourceData, meta interface{}) error { err = waitForEnvironmentReady(conn, d.Id(), waitForReadyTimeOut, pollInterval, t) if err != nil { - return fmt.Errorf("Error waiting for Elastic Beanstalk Environment (%s) to become ready: %w", d.Id(), err) + return fmt.Errorf("creating Elastic Beanstalk Environment (%s): waiting for completion: %w", name, err) } envErrors, err := getEnvironmentErrors(conn, d.Id(), t) if err != nil { - return err + return fmt.Errorf("creating Elastic Beanstalk Environment (%s): %w", name, err) } if envErrors != nil { return envErrors @@ -432,15 +431,14 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { if hasChange { // Get the current time to filter getEnvironmentErrors messages t := time.Now() - log.Printf("[DEBUG] Elastic Beanstalk Environment update opts: %s", updateOpts) _, err := conn.UpdateEnvironment(&updateOpts) if err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): %w", d.Id(), err) } waitForReadyTimeOut, err := time.ParseDuration(d.Get("wait_for_ready_timeout").(string)) if err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): %w", d.Id(), err) } pollInterval, err := time.ParseDuration(d.Get("poll_interval").(string)) if err != nil { @@ -450,14 +448,12 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { err = waitForEnvironmentReady(conn, d.Id(), waitForReadyTimeOut, pollInterval, t) if err != nil { - return fmt.Errorf( - "Error waiting for Elastic Beanstalk Environment (%s) to become ready: %s", - d.Id(), err) + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): waiting for completion: %w", d.Id(), err) } envErrors, err := getEnvironmentErrors(conn, d.Id(), t) if err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if envErrors != nil { return envErrors @@ -471,12 +467,12 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { // Get the current time to filter getEnvironmentErrors messages t := time.Now() if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating Elastic Beanstalk environment (%s) tags: %s", arn, err) + return fmt.Errorf("updating Elastic Beanstalk environment (%s): updating tags: %s", arn, err) } waitForReadyTimeOut, err := time.ParseDuration(d.Get("wait_for_ready_timeout").(string)) if err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): %w", d.Id(), err) } pollInterval, err := time.ParseDuration(d.Get("poll_interval").(string)) if err != nil { @@ -486,12 +482,12 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { err = waitForEnvironmentReady(conn, d.Id(), waitForReadyTimeOut, pollInterval, t) if err != nil { - return fmt.Errorf("error waiting for Elastic Beanstalk Environment %q to become ready: %w", d.Id(), err) + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): waiting for completion: %w", d.Id(), err) } envErrors, err := getEnvironmentErrors(conn, d.Id(), t) if err != nil { - return err + return fmt.Errorf("updating Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if envErrors != nil { return envErrors @@ -515,7 +511,7 @@ func resourceEnvironmentRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if len(resp.Environments) == 0 { @@ -541,35 +537,23 @@ func resourceEnvironmentRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } arn := aws.StringValue(env.EnvironmentArn) d.Set("arn", arn) - if err := d.Set("name", env.EnvironmentName); err != nil { - return err - } + d.Set("name", env.EnvironmentName) - if err := d.Set("application", env.ApplicationName); err != nil { - return err - } + d.Set("application", env.ApplicationName) - if err := d.Set("description", env.Description); err != nil { - return err - } + d.Set("description", env.Description) - if err := d.Set("cname", env.CNAME); err != nil { - return err - } + d.Set("cname", env.CNAME) - if err := d.Set("version_label", env.VersionLabel); err != nil { - return err - } + d.Set("version_label", env.VersionLabel) - if err := d.Set("tier", env.Tier.Name); err != nil { - return err - } + d.Set("tier", env.Tier.Name) if env.CNAME != nil { beanstalkCnamePrefixRegexp := regexp.MustCompile(`(^[^.]+)(.\w{2}-\w{4,9}-\d)?\.(elasticbeanstalk\.com|eb\.amazonaws\.com\.cn)$`) @@ -582,44 +566,36 @@ func resourceEnvironmentRead(d *schema.ResourceData, meta interface{}) error { cnamePrefix = cnamePrefixMatch[1] } - if err := d.Set("cname_prefix", cnamePrefix); err != nil { - return err - } + d.Set("cname_prefix", cnamePrefix) } else { - if err := d.Set("cname_prefix", ""); err != nil { - return err - } + d.Set("cname_prefix", "") } - if err := d.Set("solution_stack_name", env.SolutionStackName); err != nil { - return err - } + d.Set("solution_stack_name", env.SolutionStackName) - if err := d.Set("platform_arn", env.PlatformArn); err != nil { - return err - } + d.Set("platform_arn", env.PlatformArn) if err := d.Set("autoscaling_groups", flattenASG(resources.EnvironmentResources.AutoScalingGroups)); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if err := d.Set("instances", flattenInstances(resources.EnvironmentResources.Instances)); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if err := d.Set("launch_configurations", flattenLc(resources.EnvironmentResources.LaunchConfigurations)); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if err := d.Set("load_balancers", flattenELB(resources.EnvironmentResources.LoadBalancers)); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if err := d.Set("queues", flattenSQS(resources.EnvironmentResources.Queues)); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if err := d.Set("triggers", flattenTrigger(resources.EnvironmentResources.Triggers)); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } if err := d.Set("endpoint_url", env.EndpointURL); err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) } tags, err := ListTags(conn, arn) @@ -639,7 +615,11 @@ func resourceEnvironmentRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags_all: %w", err) } - return resourceEnvironmentSettingsRead(d, meta) + if err := resourceEnvironmentSettingsRead(d, meta); err != nil { + return fmt.Errorf("reading Elastic Beanstalk Environment (%s): %w", d.Id(), err) + } + + return nil } func fetchEnvironmentSettings(d *schema.ResourceData, meta interface{}) (*schema.Set, error) { @@ -703,14 +683,11 @@ func resourceEnvironmentSettingsRead(d *schema.ResourceData, meta interface{}) e allSettings, err := fetchEnvironmentSettings(d, meta) if err != nil { - return err + return err // nosemgrep:bare-error-returns } settings := d.Get("setting").(*schema.Set) - log.Printf("[DEBUG] Elastic Beanstalk allSettings: %s", allSettings.GoString()) - log.Printf("[DEBUG] Elastic Beanstalk settings: %s", settings.GoString()) - // perform the set operation with only name/namespace as keys, excluding value // this is so we override things in the settings resource data key with updated values // from the api. we skip values we didn't know about before because there are so many @@ -721,18 +698,14 @@ func resourceEnvironmentSettingsRead(d *schema.ResourceData, meta interface{}) e settingsKeySet := schema.NewSet(optionSettingKeyHash, settings.List()) updatedSettingsKeySet := allSettingsKeySet.Intersection(settingsKeySet) - log.Printf("[DEBUG] Elastic Beanstalk updatedSettingsKeySet: %s", updatedSettingsKeySet.GoString()) - updatedSettings := schema.NewSet(optionSettingValueHash, updatedSettingsKeySet.List()) - log.Printf("[DEBUG] Elastic Beanstalk updatedSettings: %s", updatedSettings.GoString()) - if err := d.Set("all_settings", allSettings.List()); err != nil { - return err + return err // nosemgrep:bare-error-returns } if err := d.Set("setting", updatedSettings.List()); err != nil { - return err + return err // nosemgrep:bare-error-returns } return nil @@ -743,7 +716,7 @@ func resourceEnvironmentDelete(d *schema.ResourceData, meta interface{}) error { waitForReadyTimeOut, err := time.ParseDuration(d.Get("wait_for_ready_timeout").(string)) if err != nil { - return err + return fmt.Errorf("deleting Elastic Beanstalk Environment (%s): %w", d.Id(), err) } pollInterval, err := time.ParseDuration(d.Get("poll_interval").(string)) if err != nil { @@ -754,10 +727,13 @@ func resourceEnvironmentDelete(d *schema.ResourceData, meta interface{}) error { // The Environment needs to be in a Ready state before it can be terminated err = waitForEnvironmentReadyIgnoreErrorEvents(conn, d.Id(), waitForReadyTimeOut, pollInterval) if err != nil { - return fmt.Errorf("error waiting for Elastic Beanstalk Environment %q to be ready before terminating: %w", d.Id(), err) + return fmt.Errorf("deleting Elastic Beanstalk Environment (%s): waiting for ready state: %w", d.Id(), err) } - return DeleteEnvironment(conn, d.Id(), waitForReadyTimeOut, pollInterval) + if err := DeleteEnvironment(conn, d.Id(), waitForReadyTimeOut, pollInterval); err != nil { + return fmt.Errorf("deleting Elastic Beanstalk Environment (%s): %w", d.Id(), err) + } + return nil } func DeleteEnvironment(conn *elasticbeanstalk.ElasticBeanstalk, id string, timeout, pollInterval time.Duration) error { @@ -788,7 +764,7 @@ func DeleteEnvironment(conn *elasticbeanstalk.ElasticBeanstalk, id string, timeo _, err = stateConf.WaitForState() if err != nil { - return fmt.Errorf("error waiting for Elastic Beanstalk Environment %q to become terminated: %w", id, err) + return fmt.Errorf("waiting for completion: %w", err) } return nil @@ -1041,7 +1017,7 @@ func getEnvironmentErrors(conn *elasticbeanstalk.ElasticBeanstalk, environmentId }) if err != nil { - return nil, fmt.Errorf("unable to get Elastic Beanstalk Environment events: %w", err) + return nil, fmt.Errorf("getting events: %w", err) } var events beanstalkEnvironmentErrors diff --git a/internal/service/elasticbeanstalk/solution_stack_data_source.go b/internal/service/elasticbeanstalk/solution_stack_data_source.go index 0eb06f99ae8..87fe7ad910a 100644 --- a/internal/service/elasticbeanstalk/solution_stack_data_source.go +++ b/internal/service/elasticbeanstalk/solution_stack_data_source.go @@ -47,7 +47,7 @@ func dataSourceSolutionStackRead(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] Reading Elastic Beanstalk Solution Stack: %s", params) resp, err := conn.ListAvailableSolutionStacks(params) if err != nil { - return err + return fmt.Errorf("reading Elastic Beanstalk Solution Stack: %w", err) } var filteredSolutionStacks []*string From 1e3dce5487fd15c0c28c67f78d6f489eb2c939be Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:29:10 -0800 Subject: [PATCH 059/106] Fixes bare errors in `elasticache` --- internal/service/elasticache/cluster.go | 10 +++++----- .../elasticache/cluster_data_source.go | 4 ++-- .../service/elasticache/engine_version.go | 2 +- .../service/elasticache/parameter_group.go | 2 +- .../service/elasticache/replication_group.go | 6 +++--- .../service/elasticache/security_group.go | 13 +++++++------ .../service/elasticache/user_data_source.go | 19 +++++-------------- 7 files changed, 24 insertions(+), 32 deletions(-) diff --git a/internal/service/elasticache/cluster.go b/internal/service/elasticache/cluster.go index 7f7030807b7..e300f7ef38d 100644 --- a/internal/service/elasticache/cluster.go +++ b/internal/service/elasticache/cluster.go @@ -511,7 +511,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { d.Set("cluster_id", c.CacheClusterId) if err := setFromCacheCluster(d, c); err != nil { - return err + return fmt.Errorf("reading ElastiCache Cache Cluster (%s): %w", d.Id(), err) } d.Set("log_delivery_configuration", flattenLogDeliveryConfigurations(c.LogDeliveryConfigurations)) @@ -545,7 +545,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { } if err := setCacheNodeData(d, c); err != nil { - return err + return fmt.Errorf("reading ElastiCache Cache Cluster (%s): %w", d.Id(), err) } d.Set("arn", c.ARN) @@ -586,7 +586,7 @@ func setFromCacheCluster(d *schema.ResourceData, c *elasticache.CacheCluster) er d.Set("engine", c.Engine) if aws.StringValue(c.Engine) == engineRedis { if err := setEngineVersionRedis(d, c.EngineVersion); err != nil { - return err + return err // nosemgrep:bare-error-returns } } else { setEngineVersionMemcached(d, c.EngineVersion) @@ -595,10 +595,10 @@ func setFromCacheCluster(d *schema.ResourceData, c *elasticache.CacheCluster) er d.Set("subnet_group_name", c.CacheSubnetGroupName) if err := d.Set("security_group_names", flattenSecurityGroupNames(c.CacheSecurityGroups)); err != nil { - return fmt.Errorf("error setting security_group_names: %w", err) + return fmt.Errorf("setting security_group_names: %w", err) } if err := d.Set("security_group_ids", flattenSecurityGroupIDs(c.SecurityGroups)); err != nil { - return fmt.Errorf("error setting security_group_ids: %w", err) + return fmt.Errorf("setting security_group_ids: %w", err) } if c.CacheParameterGroup != nil { diff --git a/internal/service/elasticache/cluster_data_source.go b/internal/service/elasticache/cluster_data_source.go index 191875857dc..3a5b580a6f1 100644 --- a/internal/service/elasticache/cluster_data_source.go +++ b/internal/service/elasticache/cluster_data_source.go @@ -179,7 +179,7 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Your query returned no results. Please change your search criteria and try again") } if err != nil { - return fmt.Errorf("error reading ElastiCache Cache Cluster (%s): %w", clusterID, err) + return fmt.Errorf("reading ElastiCache Cache Cluster (%s): %w", clusterID, err) } d.SetId(aws.StringValue(cluster.CacheClusterId)) @@ -223,7 +223,7 @@ func dataSourceClusterRead(d *schema.ResourceData, meta interface{}) error { } if err := setCacheNodeData(d, cluster); err != nil { - return err + return fmt.Errorf("reading ElastiCache Cache Cluster (%s): %w", clusterID, err) } d.Set("arn", cluster.ARN) diff --git a/internal/service/elasticache/engine_version.go b/internal/service/elasticache/engine_version.go index 7a8d79b3713..842665370ea 100644 --- a/internal/service/elasticache/engine_version.go +++ b/internal/service/elasticache/engine_version.go @@ -150,7 +150,7 @@ func setEngineVersionMemcached(d *schema.ResourceData, version *string) { func setEngineVersionRedis(d *schema.ResourceData, version *string) error { engineVersion, err := gversion.NewVersion(aws.StringValue(version)) if err != nil { - return fmt.Errorf("error reading engine version: %w", err) + return fmt.Errorf("reading engine version: %w", err) } if engineVersion.Segments()[0] < 6 { d.Set("engine_version", engineVersion.String()) diff --git a/internal/service/elasticache/parameter_group.go b/internal/service/elasticache/parameter_group.go index 39db55f203d..47890a8ac6e 100644 --- a/internal/service/elasticache/parameter_group.go +++ b/internal/service/elasticache/parameter_group.go @@ -136,7 +136,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error describeParametersResp, err := conn.DescribeCacheParameters(&describeParametersOpts) if err != nil { - return err + return fmt.Errorf("reading ElastiCache Parameter Group (%s): %w", d.Id(), err) } d.Set("parameter", FlattenParameters(describeParametersResp.Parameters)) diff --git a/internal/service/elasticache/replication_group.go b/internal/service/elasticache/replication_group.go index 5c71075492d..04a3a54de11 100644 --- a/internal/service/elasticache/replication_group.go +++ b/internal/service/elasticache/replication_group.go @@ -622,7 +622,7 @@ func resourceReplicationGroupRead(d *schema.ResourceData, meta interface{}) erro return nil } if err != nil { - return err + return fmt.Errorf("reading ElastiCache Replication Group (%s): %w", d.Id(), err) } if aws.StringValue(rgp.Status) == ReplicationGroupStatusDeleting { @@ -750,7 +750,7 @@ func resourceReplicationGroupRead(d *schema.ResourceData, meta interface{}) erro ShowCacheNodeInfo: aws.Bool(true), }) if err != nil { - return err + return fmt.Errorf("reading ElastiCache Replication Group (%s): reading Cache Cluster (%s): %w", d.Id(), aws.StringValue(cacheCluster.CacheClusterId), err) } if len(res.CacheClusters) == 0 { @@ -760,7 +760,7 @@ func resourceReplicationGroupRead(d *schema.ResourceData, meta interface{}) erro c := res.CacheClusters[0] if err := setFromCacheCluster(d, c); err != nil { - return err + return fmt.Errorf("reading ElastiCache Replication Group (%s): reading Cache Cluster (%s): %w", d.Id(), aws.StringValue(cacheCluster.CacheClusterId), err) } d.Set("at_rest_encryption_enabled", c.AtRestEncryptionEnabled) diff --git a/internal/service/elasticache/security_group.go b/internal/service/elasticache/security_group.go index 3b2c2214a64..9c120ffb3c9 100644 --- a/internal/service/elasticache/security_group.go +++ b/internal/service/elasticache/security_group.go @@ -61,21 +61,20 @@ func resourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { res, err := conn.DescribeCacheSecurityGroups(req) if err != nil { - return err + return fmt.Errorf("reading ElastiCache Cache Security Group (%s): %w", d.Id(), err) } if len(res.CacheSecurityGroups) == 0 { - return fmt.Errorf("Error missing %v", d.Id()) + return fmt.Errorf("reading ElastiCache Cache Security Group (%s): empty response", d.Id()) } var group *elasticache.CacheSecurityGroup for _, g := range res.CacheSecurityGroups { - log.Printf("[DEBUG] CacheSecurityGroupName: %v, id: %v", g.CacheSecurityGroupName, d.Id()) if aws.StringValue(g.CacheSecurityGroupName) == d.Id() { group = g } } if group == nil { - return fmt.Errorf("Error retrieving cache security group: %v", res) + return fmt.Errorf("reading ElastiCache Cache Security Group (%s): not found", d.Id()) } d.Set("name", group.CacheSecurityGroupName) @@ -123,6 +122,8 @@ func resourceSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error CacheSecurityGroupName: aws.String(d.Id()), }) } - - return err + if err != nil { + return fmt.Errorf("deleting ElastiCache Cache Security Group (%s): %w", d.Id(), err) + } + return nil } diff --git a/internal/service/elasticache/user_data_source.go b/internal/service/elasticache/user_data_source.go index 2f0fe0f78fa..c76ce335c75 100644 --- a/internal/service/elasticache/user_data_source.go +++ b/internal/service/elasticache/user_data_source.go @@ -2,12 +2,11 @@ package elasticache import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elasticache" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/tfresource" ) func DataSourceUser() *schema.Resource { @@ -49,22 +48,14 @@ func DataSourceUser() *schema.Resource { func dataSourceUserRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).ElastiCacheConn() - params := &elasticache.DescribeUsersInput{ - UserId: aws.String(d.Get("user_id").(string)), + user, err := FindUserByID(conn, d.Get("user_id").(string)) + if tfresource.NotFound(err) { + return fmt.Errorf("reading ElastiCache Cache Cluster (%s): Not found. Please change your search criteria and try again: %w", d.Get("user_id").(string), err) } - - log.Printf("[DEBUG] Reading ElastiCache User: %s", params) - response, err := conn.DescribeUsers(params) if err != nil { - return err - } - - if len(response.Users) != 1 { - return fmt.Errorf("[ERROR] Query returned wrong number of results. Please change your search criteria and try again.") + return fmt.Errorf("reading ElastiCache Cache Cluster (%s): %w", d.Get("user_id").(string), err) } - user := response.Users[0] - d.SetId(aws.StringValue(user.UserId)) d.Set("access_string", user.AccessString) From 1f9897fdaf8dcbdfa4092ce36bf437e15b63acf5 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:29:30 -0800 Subject: [PATCH 060/106] Fixes bare errors in `eks` --- internal/service/eks/fargate_profile.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/service/eks/fargate_profile.go b/internal/service/eks/fargate_profile.go index c8105ce7301..b44c9cf0dd8 100644 --- a/internal/service/eks/fargate_profile.go +++ b/internal/service/eks/fargate_profile.go @@ -167,7 +167,7 @@ func resourceFargateProfileRead(d *schema.ResourceData, meta interface{}) error clusterName, fargateProfileName, err := FargateProfileParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EKS Fargate Profile (%s): %w", d.Id(), err) } fargateProfile, err := FindFargateProfileByClusterNameAndFargateProfileName(conn, clusterName, fargateProfileName) @@ -179,7 +179,7 @@ func resourceFargateProfileRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading EKS Fargate Profile (%s): %w", d.Id(), err) + return fmt.Errorf("reading EKS Fargate Profile (%s): %w", d.Id(), err) } d.Set("arn", fargateProfile.FargateProfileArn) @@ -230,7 +230,7 @@ func resourceFargateProfileDelete(d *schema.ResourceData, meta interface{}) erro clusterName, fargateProfileName, err := FargateProfileParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EKS Fargate Profile (%s): %w", d.Id(), err) } // mutex lock for creation/deletion serialization @@ -249,13 +249,13 @@ func resourceFargateProfileDelete(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("error deleting EKS Fargate Profile (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EKS Fargate Profile (%s): %w", d.Id(), err) } _, err = waitFargateProfileDeleted(conn, clusterName, fargateProfileName, d.Timeout(schema.TimeoutDelete)) if err != nil { - return fmt.Errorf("error waiting for EKS Fargate Profile (%s) to delete: %w", d.Id(), err) + return fmt.Errorf("deleting EKS Fargate Profile (%s): waiting for completion: %w", d.Id(), err) } return nil From b60b1b84e806f845a4525c0b1e585cdbcf1c7f27 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:29:41 -0800 Subject: [PATCH 061/106] Fixes bare errors in `efs` --- internal/service/efs/backup_policy.go | 4 ++-- internal/service/efs/mount_target.go | 17 ++++++----------- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/internal/service/efs/backup_policy.go b/internal/service/efs/backup_policy.go index d466dd7d0c2..e224a97deec 100644 --- a/internal/service/efs/backup_policy.go +++ b/internal/service/efs/backup_policy.go @@ -57,7 +57,7 @@ func resourceBackupPolicyCreate(d *schema.ResourceData, meta interface{}) error fsID := d.Get("file_system_id").(string) if err := backupPolicyPut(conn, fsID, d.Get("backup_policy").([]interface{})[0].(map[string]interface{})); err != nil { - return err + return fmt.Errorf("creating EFS Backup Policy (%s): %w", fsID, err) } d.SetId(fsID) @@ -93,7 +93,7 @@ func resourceBackupPolicyUpdate(d *schema.ResourceData, meta interface{}) error conn := meta.(*conns.AWSClient).EFSConn() if err := backupPolicyPut(conn, d.Id(), d.Get("backup_policy").([]interface{})[0].(map[string]interface{})); err != nil { - return err + return fmt.Errorf("updating EFS Backup Policy (%s): %w", d.Id(), err) } return resourceBackupPolicyRead(d, meta) diff --git a/internal/service/efs/mount_target.go b/internal/service/efs/mount_target.go index 139a85b87be..e2dd479ff39 100644 --- a/internal/service/efs/mount_target.go +++ b/internal/service/efs/mount_target.go @@ -122,11 +122,9 @@ func resourceMountTargetCreate(d *schema.ResourceData, meta interface{}) error { input.SecurityGroups = flex.ExpandStringSet(v.(*schema.Set)) } - log.Printf("[DEBUG] Creating EFS mount target: %#v", input) - mt, err := conn.CreateMountTarget(&input) if err != nil { - return err + return fmt.Errorf("creating EFS Mount Target (%s): %w", fsId, err) } d.SetId(aws.StringValue(mt.MountTargetId)) @@ -177,7 +175,7 @@ func resourceMountTargetUpdate(d *schema.ResourceData, meta interface{}) error { } _, err := conn.ModifyMountTargetSecurityGroups(&input) if err != nil { - return err + return fmt.Errorf("updating EFS Mount Target (%s): %w", d.Id(), err) } } @@ -230,12 +228,12 @@ func resourceMountTargetRead(d *schema.ResourceData, meta interface{}) error { MountTargetId: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("reading EFS Mount Target (%s): %w", d.Id(), err) } err = d.Set("security_groups", flex.FlattenStringSet(sgResp.SecurityGroups)) if err != nil { - return err + return fmt.Errorf("reading EFS Mount Target (%s): %w", d.Id(), err) } d.Set("dns_name", meta.(*conns.AWSClient).RegionalHostname(fmt.Sprintf("%s.efs", aws.StringValue(mt.FileSystemId)))) @@ -257,21 +255,18 @@ func getAzFromSubnetId(subnetId string, meta interface{}) (string, error) { func resourceMountTargetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EFSConn() - log.Printf("[DEBUG] Deleting EFS mount target %q", d.Id()) _, err := conn.DeleteMountTarget(&efs.DeleteMountTargetInput{ MountTargetId: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("deleting EFS Mount Target (%s): %w", d.Id(), err) } err = WaitForDeleteMountTarget(conn, d.Id(), mountTargetDeleteTimeout) if err != nil { - return fmt.Errorf("Error waiting for EFS mount target (%q) to delete: %s", d.Id(), err.Error()) + return fmt.Errorf("deleting EFS Mount Target (%s): waiting for completion: %w", d.Id(), err) } - log.Printf("[DEBUG] EFS mount target %q deleted.", d.Id()) - return nil } From b524557a005024d42700902b92df1504bf99f128 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:30:01 -0800 Subject: [PATCH 062/106] Fixes bare errors in `ecs` --- .../service/ecs/account_setting_default.go | 4 ++-- internal/service/ecs/service.go | 14 +++++------ internal/service/ecs/service_data_source.go | 2 +- internal/service/ecs/task_definition.go | 14 +++++------ internal/service/ecs/task_set.go | 24 +++++++++---------- 5 files changed, 29 insertions(+), 29 deletions(-) diff --git a/internal/service/ecs/account_setting_default.go b/internal/service/ecs/account_setting_default.go index 0352cd4ec54..21f64e26c19 100644 --- a/internal/service/ecs/account_setting_default.go +++ b/internal/service/ecs/account_setting_default.go @@ -70,7 +70,7 @@ func resourceAccountSettingDefaultCreate(d *schema.ResourceData, meta interface{ out, err := conn.PutAccountSettingDefault(&input) if err != nil { - return err + return fmt.Errorf("creating ECS Account Setting Defauilt (%s): %w", settingName, err) } log.Printf("[DEBUG] Account Setting Default %s set", aws.StringValue(out.Setting.Value)) @@ -92,7 +92,7 @@ func resourceAccountSettingDefaultRead(d *schema.ResourceData, meta interface{}) resp, err := conn.ListAccountSettings(input) if err != nil { - return err + return fmt.Errorf("reading ECS Account Setting Defauilt (%s): %w", d.Get("name").(string), err) } if len(resp.Settings) == 0 { diff --git a/internal/service/ecs/service.go b/internal/service/ecs/service.go index c5b83277bd3..eaabc936f61 100644 --- a/internal/service/ecs/service.go +++ b/internal/service/ecs/service.go @@ -535,7 +535,7 @@ func resourceServiceCreate(d *schema.ResourceData, meta interface{}) error { ps, err := expandPlacementStrategy(v.([]interface{})) if err != nil { - return err + return fmt.Errorf("creating ECS Service (%s): %w", d.Get("name").(string), err) } input.PlacementStrategy = ps @@ -545,7 +545,7 @@ func resourceServiceCreate(d *schema.ResourceData, meta interface{}) error { pc, err := expandPlacementConstraints(v.List()) if err != nil { - return err + return fmt.Errorf("creating ECS Service (%s): %w", d.Get("name").(string), err) } input.PlacementConstraints = pc @@ -838,7 +838,7 @@ func resourceServiceUpdate(d *schema.ResourceData, meta interface{}) error { ps, err := expandPlacementStrategy(v.([]interface{})) if err != nil { - return err + return fmt.Errorf("updating ECS Service (%s): %w", d.Get("name").(string), err) } input.PlacementStrategy = ps @@ -854,7 +854,7 @@ func resourceServiceUpdate(d *schema.ResourceData, meta interface{}) error { pc, err := expandPlacementConstraints(v.List()) if err != nil { - return err + return fmt.Errorf("updating ECS Service (%s): %w", d.Get("name").(string), err) } input.PlacementConstraints = pc @@ -994,7 +994,7 @@ func resourceServiceDelete(d *schema.ResourceData, meta interface{}) error { DesiredCount: aws.Int64(0), }) if err != nil { - return err + return fmt.Errorf("deleting ECS Service (%s): draining service: %w", d.Get("name").(string), err) } } @@ -1026,11 +1026,11 @@ func resourceServiceDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting ECS Service (%s): %w", d.Id(), err) + return fmt.Errorf("deleting ECS Service (%s): %w", d.Id(), err) } if err := waitServiceInactive(conn, d.Id(), d.Get("cluster").(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for ECS Service (%s) to be deleted: %w", d.Id(), err) + return fmt.Errorf("deleting ECS Service (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ecs/service_data_source.go b/internal/service/ecs/service_data_source.go index e68dbfd2bb0..1ad8cfc32c2 100644 --- a/internal/service/ecs/service_data_source.go +++ b/internal/service/ecs/service_data_source.go @@ -65,7 +65,7 @@ func dataSourceServiceRead(d *schema.ResourceData, meta interface{}) error { desc, err := conn.DescribeServices(params) if err != nil { - return err + return fmt.Errorf("reading ECS Service (%s): %w", serviceName, err) } if desc == nil || len(desc.Services) == 0 { diff --git a/internal/service/ecs/task_definition.go b/internal/service/ecs/task_definition.go index 62e7987cb5b..bdfdadbc20a 100644 --- a/internal/service/ecs/task_definition.go +++ b/internal/service/ecs/task_definition.go @@ -437,7 +437,7 @@ func resourceTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) erro rawDefinitions := d.Get("container_definitions").(string) definitions, err := expandContainerDefinitions(rawDefinitions) if err != nil { - return err + return fmt.Errorf("creating ECS Task Definition (%s): %w", d.Get("family").(string), err) } input := ecs.RegisterTaskDefinitionInput{ @@ -491,7 +491,7 @@ func resourceTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) erro if len(constraints) > 0 { cons, err := expandTaskDefinitionPlacementConstraints(constraints) if err != nil { - return err + return fmt.Errorf("creating ECS Task Definition (%s): %w", d.Get("family").(string), err) } input.PlacementConstraints = cons } @@ -526,7 +526,7 @@ func resourceTaskDefinitionCreate(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("failed creating ECS Task Definition (%s): %w", d.Get("family").(string), err) + return fmt.Errorf("creating ECS Task Definition (%s): %w", d.Get("family").(string), err) } taskDefinition := *out.TaskDefinition // nosemgrep:ci.prefer-aws-go-sdk-pointer-conversion-assignment // false positive @@ -578,7 +578,7 @@ func resourceTaskDefinitionRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return err + return fmt.Errorf("reading ECS Task Definition (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Received task definition %s, status:%s\n %s", aws.StringValue(out.TaskDefinition.Family), @@ -604,11 +604,11 @@ func resourceTaskDefinitionRead(d *schema.ResourceData, meta interface{}) error defs, err := flattenContainerDefinitions(taskDefinition.ContainerDefinitions) if err != nil { - return err + return fmt.Errorf("reading ECS Task Definition (%s): %w", d.Id(), err) } err = d.Set("container_definitions", defs) if err != nil { - return err + return fmt.Errorf("reading ECS Task Definition (%s): %w", d.Id(), err) } d.Set("task_role_arn", taskDefinition.TaskRoleArn) @@ -757,7 +757,7 @@ func resourceTaskDefinitionDelete(d *schema.ResourceData, meta interface{}) erro TaskDefinition: aws.String(d.Get("arn").(string)), }) if err != nil { - return err + return fmt.Errorf("deleting ECS Task Definition (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Task definition %q deregistered.", d.Get("arn").(string)) diff --git a/internal/service/ecs/task_set.go b/internal/service/ecs/task_set.go index f28449515d5..6cd1f5770ce 100644 --- a/internal/service/ecs/task_set.go +++ b/internal/service/ecs/task_set.go @@ -352,7 +352,7 @@ func resourceTaskSetCreate(d *schema.ResourceData, meta interface{}) error { if d.Get("wait_until_stable").(bool) { timeout, _ := time.ParseDuration(d.Get("wait_until_stable_timeout").(string)) if err := waitTaskSetStable(conn, timeout, taskSetId, service, cluster); err != nil { - return fmt.Errorf("error waiting for ECS TaskSet (%s) to be stable: %w", d.Id(), err) + return fmt.Errorf("error waiting for ECS Task Set (%s) to be stable: %w", d.Id(), err) } } @@ -382,7 +382,7 @@ func resourceTaskSetRead(d *schema.ResourceData, meta interface{}) error { taskSetId, service, cluster, err := TaskSetParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading ECS Task Set (%s): %w", d.Id(), err) } input := &ecs.DescribeTaskSetsInput{ @@ -395,7 +395,7 @@ func resourceTaskSetRead(d *schema.ResourceData, meta interface{}) error { out, err := conn.DescribeTaskSets(input) if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, ecs.ErrCodeClusterNotFoundException, ecs.ErrCodeServiceNotFoundException, ecs.ErrCodeTaskSetNotFoundException) { - log.Printf("[WARN] ECS TaskSet (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] ECS Task Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -409,14 +409,14 @@ func resourceTaskSetRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading ECS TaskSet (%s): %w", d.Id(), err) + return fmt.Errorf("reading ECS Task Set (%s): %w", d.Id(), err) } if out == nil || len(out.TaskSets) == 0 { if d.IsNewResource() { - return fmt.Errorf("error reading ECS TaskSet (%s): empty output after creation", d.Id()) + return fmt.Errorf("error reading ECS Task Set (%s): empty output after creation", d.Id()) } - log.Printf("[WARN] ECS TaskSet (%s) not found, removing from state", d.Id()) + log.Printf("[WARN] ECS Task Set (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -475,7 +475,7 @@ func resourceTaskSetUpdate(d *schema.ResourceData, meta interface{}) error { taskSetId, service, cluster, err := TaskSetParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating ECS Task Set (%s): %w", d.Id(), err) } input := &ecs.UpdateTaskSetInput{ @@ -488,13 +488,13 @@ func resourceTaskSetUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateTaskSet(input) if err != nil { - return fmt.Errorf("error updating ECS TaskSet (%s): %w", d.Id(), err) + return fmt.Errorf("updating ECS Task Set (%s): %w", d.Id(), err) } if d.Get("wait_until_stable").(bool) { timeout, _ := time.ParseDuration(d.Get("wait_until_stable_timeout").(string)) if err := waitTaskSetStable(conn, timeout, taskSetId, service, cluster); err != nil { - return fmt.Errorf("error waiting for ECS TaskSet (%s) to be stable after update: %w", d.Id(), err) + return fmt.Errorf("error waiting for ECS Task Set (%s) to be stable after update: %w", d.Id(), err) } } } @@ -524,7 +524,7 @@ func resourceTaskSetDelete(d *schema.ResourceData, meta interface{}) error { taskSetId, service, cluster, err := TaskSetParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting ECS Task Set (%s): %w", d.Id(), err) } input := &ecs.DeleteTaskSetInput{ @@ -541,14 +541,14 @@ func resourceTaskSetDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting ECS TaskSet (%s): %w", d.Id(), err) + return fmt.Errorf("deleting ECS Task Set (%s): %w", d.Id(), err) } if err := waitTaskSetDeleted(conn, taskSetId, service, cluster); err != nil { if tfawserr.ErrCodeEquals(err, ecs.ErrCodeTaskSetNotFoundException) { return nil } - return fmt.Errorf("error waiting for ECS TaskSet (%s) to delete: %w", d.Id(), err) + return fmt.Errorf("deleting ECS Task Set (%s): waiting for completion: %w", d.Id(), err) } return nil From d6ea3d47e3b317c8484dc4eb4c377fa9894a3fe4 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:30:14 -0800 Subject: [PATCH 063/106] Fixes bare errors in `ecrpublic` --- internal/service/ecrpublic/repository.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/ecrpublic/repository.go b/internal/service/ecrpublic/repository.go index 3e210a95d3d..601a9e541dd 100644 --- a/internal/service/ecrpublic/repository.go +++ b/internal/service/ecrpublic/repository.go @@ -307,7 +307,7 @@ func resourceRepositoryUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("catalog_data") { if err := resourceRepositoryUpdateCatalogData(conn, d); err != nil { - return err + return fmt.Errorf("updating ECR Public Repository (%s): %w", d.Id(), err) } } From 0fe4aae170b37e30de881860afce718cfa74ce82 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Wed, 11 Jan 2023 17:30:19 -0800 Subject: [PATCH 064/106] Fixes bare errors in `ecr` --- internal/service/ecr/lifecycle_policy.go | 4 ++-- internal/service/ecr/registry_policy.go | 8 ++++---- internal/service/ecr/repository.go | 10 +++++----- internal/service/ecr/repository_policy.go | 4 +--- 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/internal/service/ecr/lifecycle_policy.go b/internal/service/ecr/lifecycle_policy.go index fe8fd090a6c..234266b8a87 100644 --- a/internal/service/ecr/lifecycle_policy.go +++ b/internal/service/ecr/lifecycle_policy.go @@ -75,7 +75,7 @@ func resourceLifecyclePolicyCreate(d *schema.ResourceData, meta interface{}) err resp, err := conn.PutLifecyclePolicy(input) if err != nil { - return err + return fmt.Errorf("creating ECR Lifecycle Policy (%s): %w", d.Get("repository").(string), err) } d.SetId(aws.StringValue(resp.RepositoryName)) d.Set("registry_id", resp.RegistryId) @@ -172,7 +172,7 @@ func resourceLifecyclePolicyDelete(d *schema.ResourceData, meta interface{}) err if tfawserr.ErrCodeEquals(err, ecr.ErrCodeLifecyclePolicyNotFoundException) { return nil } - return err + return fmt.Errorf("deleting ECR Lifecycle Policy (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ecr/registry_policy.go b/internal/service/ecr/registry_policy.go index 489f2d55a56..14d13b4423c 100644 --- a/internal/service/ecr/registry_policy.go +++ b/internal/service/ecr/registry_policy.go @@ -80,7 +80,7 @@ func resourceRegistryPolicyRead(d *schema.ResourceData, meta interface{}) error d.SetId("") return nil } - return err + return fmt.Errorf("reading ECR Registry Policy (%s): %w", d.Id(), err) } d.Set("registry_id", out.RegistryId) @@ -88,13 +88,13 @@ func resourceRegistryPolicyRead(d *schema.ResourceData, meta interface{}) error policyToSet, err := verify.SecondJSONUnlessEquivalent(d.Get("policy").(string), aws.StringValue(out.PolicyText)) if err != nil { - return fmt.Errorf("while setting policy (%s), encountered: %w", policyToSet, err) + return fmt.Errorf("reading ECR Registry Policy (%s): setting policy: %w", d.Id(), err) } policyToSet, err = structure.NormalizeJsonString(policyToSet) if err != nil { - return fmt.Errorf("policy (%s) is an invalid JSON: %w", policyToSet, err) + return fmt.Errorf("reading ECR Registry Policy (%s): setting policy: %w", d.Id(), err) } d.Set("policy", policyToSet) @@ -110,7 +110,7 @@ func resourceRegistryPolicyDelete(d *schema.ResourceData, meta interface{}) erro if tfawserr.ErrCodeEquals(err, ecr.ErrCodeRegistryPolicyNotFoundException) { return nil } - return err + return fmt.Errorf("deleting ECR Registry Policy (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ecr/repository.go b/internal/service/ecr/repository.go index 30354a63f41..7b7c7e8cac8 100644 --- a/internal/service/ecr/repository.go +++ b/internal/service/ecr/repository.go @@ -315,13 +315,13 @@ func resourceRepositoryUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("image_tag_mutability") { if err := resourceRepositoryUpdateImageTagMutability(conn, d); err != nil { - return err + return fmt.Errorf("updating ECR Repository (%s): %w", d.Id(), err) } } if d.HasChange("image_scanning_configuration") { if err := resourceRepositoryUpdateImageScanningConfiguration(conn, d); err != nil { - return err + return fmt.Errorf("updating ECR Repository (%s): %w", d.Id(), err) } } @@ -337,7 +337,7 @@ func resourceRepositoryUpdate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("failed updating tags for ECR Repository (%s): %w", d.Id(), err) + return fmt.Errorf("updating ECR Repository (%s): updating tags: %w", d.Id(), err) } } @@ -403,7 +403,7 @@ func resourceRepositoryUpdateImageTagMutability(conn *ecr.ECR, d *schema.Resourc _, err := conn.PutImageTagMutability(input) if err != nil { - return fmt.Errorf("Error setting image tag mutability: %s", err.Error()) + return fmt.Errorf("setting image tag mutability: %s", err) } return nil @@ -427,7 +427,7 @@ func resourceRepositoryUpdateImageScanningConfiguration(conn *ecr.ECR, d *schema _, err := conn.PutImageScanningConfiguration(input) if err != nil { - return fmt.Errorf("Error setting image scanning configuration: %s", err.Error()) + return fmt.Errorf("setting image scanning configuration: %s", err) } return nil diff --git a/internal/service/ecr/repository_policy.go b/internal/service/ecr/repository_policy.go index 931b7e71b34..6327d9f4175 100644 --- a/internal/service/ecr/repository_policy.go +++ b/internal/service/ecr/repository_policy.go @@ -181,10 +181,8 @@ func resourceRepositoryPolicyDelete(d *schema.ResourceData, meta interface{}) er tfawserr.ErrCodeEquals(err, ecr.ErrCodeRepositoryPolicyNotFoundException) { return nil } - return err + return fmt.Errorf("deleting ECR Repository Policy (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] repository policy %s deleted.", d.Id()) - return nil } From 844452f0013aa9d470cc2cdc65c8484e743479be Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:26:06 -0800 Subject: [PATCH 065/106] Fixes bare errors in `ec2` --- internal/provider/provider.go | 2 +- .../ebs_snapshot_create_volume_permission.go | 4 +- internal/service/ec2/ebs_volume_attachment.go | 2 +- internal/service/ec2/ec2_ami.go | 12 +-- internal/service/ec2/ec2_ami_copy.go | 4 +- internal/service/ec2/ec2_ami_from_instance.go | 4 +- .../ec2/ec2_availability_zone_group.go | 10 +-- internal/service/ec2/ec2_eip.go | 16 ++-- internal/service/ec2/ec2_instance.go | 84 +++++++++---------- .../service/ec2/ec2_instance_data_source.go | 14 ++-- internal/service/ec2/ec2_launch_template.go | 14 ++-- .../ec2/ec2_launch_template_data_source.go | 6 +- .../service/ec2/ec2_spot_fleet_request.go | 2 +- .../service/ec2/ec2_spot_instance_request.go | 20 ++--- internal/service/ec2/ipam_pool_cidr.go | 4 +- .../service/ec2/ipam_pool_cidr_allocation.go | 4 +- .../service/ec2/ipam_preview_next_cidr.go | 2 +- .../ec2/outposts_local_gateway_route.go | 8 +- ...transitgateway_policy_table_association.go | 4 +- .../transitgateway_prefix_list_reference.go | 4 +- internal/service/ec2/transitgateway_route.go | 4 +- .../transitgateway_route_table_association.go | 4 +- .../transitgateway_route_table_propagation.go | 4 +- .../ec2/transitgateway_vpc_attachment.go | 8 +- .../transitgateway_vpc_attachment_accepter.go | 14 ++-- internal/service/ec2/vpc_.go | 52 ++++++------ .../service/ec2/vpc_default_network_acl.go | 26 +++--- .../service/ec2/vpc_default_route_table.go | 14 ++-- internal/service/ec2/vpc_default_subnet.go | 2 +- internal/service/ec2/vpc_default_vpc.go | 8 +- internal/service/ec2/vpc_dhcp_options.go | 8 +- .../ec2/vpc_dhcp_options_association.go | 10 +-- .../ec2/vpc_dhcp_options_data_source.go | 2 +- internal/service/ec2/vpc_endpoint.go | 6 +- .../ec2/vpc_endpoint_connection_accepter.go | 8 +- ...vpc_endpoint_security_group_association.go | 10 +-- internal/service/ec2/vpc_internet_gateway.go | 14 ++-- .../ec2/vpc_internet_gateway_attachment.go | 11 ++- internal/service/ec2/vpc_network_acl.go | 28 +++---- .../ec2/vpc_network_acl_association.go | 20 ++--- internal/service/ec2/vpc_network_acl_rule.go | 10 +-- internal/service/ec2/vpc_network_interface.go | 12 +-- .../ec2/vpc_network_interface_attachment.go | 8 +- .../service/ec2/vpc_peering_connection.go | 16 ++-- .../ec2/vpc_peering_connection_accepter.go | 4 +- .../ec2/vpc_peering_connection_options.go | 4 +- internal/service/ec2/vpc_route_table.go | 68 +++++++-------- .../ec2/vpc_route_table_association.go | 4 +- .../ec2/vpc_route_table_data_source.go | 7 +- internal/service/ec2/vpc_subnet.go | 70 ++++++++-------- .../ec2/vpc_subnet_cidr_reservation.go | 4 +- .../ec2/vpnclient_authorization_rule.go | 10 +-- internal/service/ec2/vpnclient_route.go | 10 +-- internal/service/ec2/vpnsite_connection.go | 4 +- .../service/ec2/vpnsite_connection_route.go | 10 +-- internal/service/ec2/vpnsite_gateway.go | 30 +++---- .../ec2/vpnsite_gateway_route_propagation.go | 10 +-- internal/service/ecs/task_definition.go | 2 - internal/tfresource/not_found_error.go | 2 +- 59 files changed, 376 insertions(+), 382 deletions(-) diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 5a6e18ae7e6..9864591afd1 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -1600,7 +1600,7 @@ func New(ctx context.Context) (*schema.Provider, error) { "aws_guardduty_organization_admin_account": guardduty.ResourceOrganizationAdminAccount(), "aws_guardduty_organization_configuration": guardduty.ResourceOrganizationConfiguration(), "aws_guardduty_publishing_destination": guardduty.ResourcePublishingDestination(), - "aws_guardduty_threatintelset": guardduty.ResourceThreatintelset(), + "aws_guardduty_threatintelset": guardduty.ResourceThreatIntelSet(), "aws_iam_access_key": iam.ResourceAccessKey(), "aws_iam_account_alias": iam.ResourceAccountAlias(), diff --git a/internal/service/ec2/ebs_snapshot_create_volume_permission.go b/internal/service/ec2/ebs_snapshot_create_volume_permission.go index 0b8291cb38b..f36012ef07b 100644 --- a/internal/service/ec2/ebs_snapshot_create_volume_permission.go +++ b/internal/service/ec2/ebs_snapshot_create_volume_permission.go @@ -85,7 +85,7 @@ func resourceSnapshotCreateVolumePermissionRead(d *schema.ResourceData, meta int snapshotID, accountID, err := EBSSnapshotCreateVolumePermissionParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EBS Snapshot CreateVolumePermission (%s): %w", d.Id(), err) } _, err = FindCreateSnapshotCreateVolumePermissionByTwoPartKey(conn, snapshotID, accountID) @@ -109,7 +109,7 @@ func resourceSnapshotCreateVolumePermissionDelete(d *schema.ResourceData, meta i snapshotID, accountID, err := EBSSnapshotCreateVolumePermissionParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EBS Snapshot CreateVolumePermission (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting EBS Snapshot CreateVolumePermission: %s", d.Id()) diff --git a/internal/service/ec2/ebs_volume_attachment.go b/internal/service/ec2/ebs_volume_attachment.go index 1158a98c9f2..d607cf53692 100644 --- a/internal/service/ec2/ebs_volume_attachment.go +++ b/internal/service/ec2/ebs_volume_attachment.go @@ -154,7 +154,7 @@ func resourceVolumeAttachmentDelete(d *schema.ResourceData, meta interface{}) er if _, ok := d.GetOk("stop_instance_before_detaching"); ok { if err := StopInstance(conn, instanceID, InstanceStopTimeout); err != nil { - return err + return fmt.Errorf("deleting EBS Volume (%s) Attachment (%s): %w", volumeID, instanceID, err) } } diff --git a/internal/service/ec2/ec2_ami.go b/internal/service/ec2/ec2_ami.go index ee9ced164a1..05c68c210d1 100644 --- a/internal/service/ec2/ec2_ami.go +++ b/internal/service/ec2/ec2_ami.go @@ -355,7 +355,7 @@ func resourceAMICreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.RegisterImage(input) if err != nil { - return fmt.Errorf("error creating EC2 AMI (%s): %w", name, err) + return fmt.Errorf("creating EC2 AMI (%s): %w", name, err) } d.SetId(aws.StringValue(output.ImageId)) @@ -367,12 +367,12 @@ func resourceAMICreate(d *schema.ResourceData, meta interface{}) error { } if _, err := WaitImageAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("error waiting for EC2 AMI (%s) create: %w", d.Id(), err) + return fmt.Errorf("creating EC2 AMI (%s): waiting for completion: %w", name, err) } if v, ok := d.GetOk("deprecation_time"); ok { if err := enableImageDeprecation(conn, d.Id(), v.(string)); err != nil { - return err + return fmt.Errorf("creating EC2 AMI (%s): %w", name, err) } } @@ -486,13 +486,13 @@ func resourceAMIUpdate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("error updating EC2 AMI (%s) description: %w", d.Id(), err) + return fmt.Errorf("updating EC2 AMI (%s) description: %w", d.Id(), err) } } if d.HasChange("deprecation_time") { if err := enableImageDeprecation(conn, d.Id(), d.Get("deprecation_time").(string)); err != nil { - return err + return fmt.Errorf("updating EC2 AMI (%s): %w", d.Id(), err) } } @@ -559,7 +559,7 @@ func enableImageDeprecation(conn *ec2.EC2, id string, deprecateAt string) error _, err := conn.EnableImageDeprecation(input) if err != nil { - return fmt.Errorf("error enabling EC2 AMI (%s) image deprecation: %w", id, err) + return fmt.Errorf("enabling deprecation: %w", err) } return nil diff --git a/internal/service/ec2/ec2_ami_copy.go b/internal/service/ec2/ec2_ami_copy.go index 0a4204f9d47..ba68cf411a7 100644 --- a/internal/service/ec2/ec2_ami_copy.go +++ b/internal/service/ec2/ec2_ami_copy.go @@ -300,12 +300,12 @@ func resourceAMICopyCreate(d *schema.ResourceData, meta interface{}) error { } if _, err := WaitImageAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("waiting for EC2 AMI (%s) create: %w", d.Id(), err) + return fmt.Errorf("creating EC2 AMI (%s) from source EC2 AMI (%s): waiting for completion: %w", name, sourceImageID, err) } if v, ok := d.GetOk("deprecation_time"); ok { if err := enableImageDeprecation(conn, d.Id(), v.(string)); err != nil { - return err + return fmt.Errorf("creating EC2 AMI (%s) from source EC2 AMI (%s): %w", name, sourceImageID, err) } } diff --git a/internal/service/ec2/ec2_ami_from_instance.go b/internal/service/ec2/ec2_ami_from_instance.go index 751a1b85ac8..08e310573c1 100644 --- a/internal/service/ec2/ec2_ami_from_instance.go +++ b/internal/service/ec2/ec2_ami_from_instance.go @@ -266,12 +266,12 @@ func resourceAMIFromInstanceCreate(d *schema.ResourceData, meta interface{}) err d.Set("manage_ebs_snapshots", true) if _, err := WaitImageAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("waiting for EC2 AMI (%s) create: %w", d.Id(), err) + return fmt.Errorf("creating EC2 AMI (%s) from EC2 Instance (%s): waiting for completion: %w", name, instanceID, err) } if v, ok := d.GetOk("deprecation_time"); ok { if err := enableImageDeprecation(conn, d.Id(), v.(string)); err != nil { - return err + return fmt.Errorf("creating EC2 AMI (%s) from EC2 Instance (%s): %w", name, instanceID, err) } } diff --git a/internal/service/ec2/ec2_availability_zone_group.go b/internal/service/ec2/ec2_availability_zone_group.go index ecee7daad9d..4fbb708ea05 100644 --- a/internal/service/ec2/ec2_availability_zone_group.go +++ b/internal/service/ec2/ec2_availability_zone_group.go @@ -46,12 +46,12 @@ func resourceAvailabilityZoneGroupCreate(d *schema.ResourceData, meta interface{ availabilityZone, err := FindAvailabilityZoneGroupByName(conn, groupName) if err != nil { - return fmt.Errorf("reading EC2 Availability Zone Group (%s): %w", groupName, err) + return fmt.Errorf("creating EC2 Availability Zone Group (%s): %w", groupName, err) } if v := d.Get("opt_in_status").(string); v != aws.StringValue(availabilityZone.OptInStatus) { if err := modifyAvailabilityZoneOptInStatus(conn, groupName, v); err != nil { - return err + return fmt.Errorf("creating EC2 Availability Zone Group (%s): %w", groupName, err) } } @@ -83,7 +83,7 @@ func resourceAvailabilityZoneGroupUpdate(d *schema.ResourceData, meta interface{ conn := meta.(*conns.AWSClient).EC2Conn() if err := modifyAvailabilityZoneOptInStatus(conn, d.Id(), d.Get("opt_in_status").(string)); err != nil { - return err + return fmt.Errorf("updating EC2 Availability Zone Group (%s): %w", d.Id(), err) } return resourceAvailabilityZoneGroupRead(d, meta) @@ -96,7 +96,7 @@ func modifyAvailabilityZoneOptInStatus(conn *ec2.EC2, groupName, optInStatus str } if _, err := conn.ModifyAvailabilityZoneGroup(input); err != nil { - return fmt.Errorf("modifying EC2 Availability Zone Group (%s): %w", groupName, err) + return err } waiter := WaitAvailabilityZoneGroupOptedIn @@ -105,7 +105,7 @@ func modifyAvailabilityZoneOptInStatus(conn *ec2.EC2, groupName, optInStatus str } if _, err := waiter(conn, groupName); err != nil { - return fmt.Errorf("waiting for EC2 Availability Zone Group (%s) opt-in status update: %w", groupName, err) + return fmt.Errorf("waiting for completion: %w", err) } return nil diff --git a/internal/service/ec2/ec2_eip.go b/internal/service/ec2/ec2_eip.go index 7d6040c2648..20c40350ca6 100644 --- a/internal/service/ec2/ec2_eip.go +++ b/internal/service/ec2/ec2_eip.go @@ -184,7 +184,7 @@ func resourceEIPCreate(d *schema.ResourceData, meta interface{}) error { }, errCodeInvalidAllocationIDNotFound) if err != nil { - return err + return fmt.Errorf("creating EC2 EIP (%s): %w", d.Id(), err) } } @@ -267,7 +267,7 @@ func resourceEIPUpdate(d *schema.ResourceData, meta interface{}) error { if oldInstanceID != "" || associationID != "" { if err := disassociateEIP(conn, d.Id(), associationID); err != nil { - return err + return fmt.Errorf("updating EC2 EIP (%s): %w", d.Id(), err) } } @@ -275,7 +275,7 @@ func resourceEIPUpdate(d *schema.ResourceData, meta interface{}) error { if newInstanceID != "" || newNetworkInterfaceID != "" { if err := associateEIP(conn, d.Id(), newInstanceID, newNetworkInterfaceID, d.Get("associate_with_private_ip").(string)); err != nil { - return err + return fmt.Errorf("updating EC2 EIP (%s): %w", d.Id(), err) } } } @@ -301,7 +301,7 @@ func resourceEIPDelete(d *schema.ResourceData, meta interface{}) error { // If we are attached to an instance or interface, detach first. if associationID := d.Get("association_id").(string); associationID != "" || d.Get("instance").(string) != "" { if err := disassociateEIP(conn, d.Id(), associationID); err != nil { - return err + return fmt.Errorf("deleting EC2 EIP (%s): %w", d.Id(), err) } } @@ -361,7 +361,7 @@ func associateEIP(conn *ec2.EC2, id, instanceID, networkInterfaceID, privateIPAd output, err := conn.AssociateAddress(input) if err != nil { - return fmt.Errorf("associating EC2 EIP (%s): %w", id, err) + return fmt.Errorf("associating: %w", err) } if associationID := aws.StringValue(output.AssociationId); associationID != "" { @@ -384,11 +384,11 @@ func associateEIP(conn *ec2.EC2, id, instanceID, networkInterfaceID, privateIPAd ) if err != nil { - return fmt.Errorf("waiting for EC2 EIP (%s) Association (%s) create: %w", id, associationID, err) + return fmt.Errorf("associating: waiting for completion: %w", err) } } else { if err := waitForAddressAssociationClassic(conn, id, instanceID); err != nil { - return fmt.Errorf("waiting for EC2 EIP (%s) to associate with EC2-Classic Instance (%s): %w", id, instanceID, err) + return fmt.Errorf("associating: waiting for completion: %w", err) } } @@ -415,7 +415,7 @@ func disassociateEIP(conn *ec2.EC2, id, associationID string) error { } if err != nil { - return fmt.Errorf("disassociating EC2 EIP (%s): %w", id, err) + return fmt.Errorf("disassociating: %w", err) } return nil diff --git a/internal/service/ec2/ec2_instance.go b/internal/service/ec2/ec2_instance.go index 87178efe69e..9a0a712a8a1 100644 --- a/internal/service/ec2/ec2_instance.go +++ b/internal/service/ec2/ec2_instance.go @@ -1162,7 +1162,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { if _, ok := d.GetOk("volume_tags"); ok && !blockDeviceTagsDefined(d) { volumeTags, err := readVolumeTags(conn, d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", d.Id(), err) } if err := d.Set("volume_tags", KeyValueTags(volumeTags).IgnoreAWS().Map()); err != nil { @@ -1171,16 +1171,16 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { } if err := readSecurityGroups(d, instance, conn); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", d.Id(), err) } // Retrieve instance shutdown behavior if err := readInstanceShutdownBehavior(d, conn); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", d.Id(), err) } if err := readBlockDevices(d, instance, conn); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", d.Id(), err) } if _, ok := d.GetOk("ephemeral_block_device"); !ok { d.Set("ephemeral_block_device", []interface{}{}) @@ -1204,7 +1204,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { InstanceId: aws.String(d.Id()), }) if err != nil && !verify.ErrorISOUnsupported(meta.(*conns.AWSClient).Partition, err) { - return fmt.Errorf("reading EC2 Instance (%s) attribute: %w ", d.Id(), err) + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameDisableApiStop, err) } if !verify.ErrorISOUnsupported(meta.(*conns.AWSClient).Partition, err) { d.Set("disable_api_stop", attr.DisableApiStop.Value) @@ -1220,7 +1220,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("reading EC2 Instance (%s) attribute: %w ", d.Id(), err) + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameDisableApiTermination, err) } d.Set("disable_api_termination", output.DisableApiTermination.Value) @@ -1232,7 +1232,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { InstanceId: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameUserData, err) } if attr.UserData != nil && attr.UserData.Value != nil { // Since user_data and user_data_base64 conflict with each other, @@ -1275,7 +1275,7 @@ func resourceInstanceRead(d *schema.ResourceData, meta interface{}) error { if d.Get("get_password_data").(bool) { passwordData, err := getInstancePasswordData(aws.StringValue(instance.InstanceId), conn) if err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", d.Id(), err) } d.Set("password_data", passwordData) } else { @@ -1308,7 +1308,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("volume_tags") && !d.IsNewResource() { volumeIds, err := getInstanceVolumeIDs(conn, d.Id()) if err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } o, n := d.GetChange("volume_tags") @@ -1332,7 +1332,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.DescribeIamInstanceProfileAssociations(request) if err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } // An Iam Instance Profile has been provided and is pending a change @@ -1341,7 +1341,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { // Does not have an Iam Instance Profile associated with it, need to associate if len(resp.IamInstanceProfileAssociations) == 0 { if err := associateInstanceProfile(d, conn); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } } else { // Has an Iam Instance Profile associated with it, need to replace the association @@ -1360,10 +1360,10 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { if instanceState != "" { if instanceState == ec2.InstanceStateNameStopped || instanceState == ec2.InstanceStateNameStopping || instanceState == ec2.InstanceStateNameShuttingDown { if err := disassociateInstanceProfile(associationId, conn); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } if err := associateInstanceProfile(d, conn); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } } else { err := resource.Retry(propagationTimeout, func() *resource.RetryError { @@ -1380,7 +1380,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.ReplaceIamInstanceProfileAssociation(input) } if err != nil { - return fmt.Errorf("Error replacing instance profile association: %s", err) + return fmt.Errorf("updating EC2 Instance (%s): replacing instance profile: %w", d.Id(), err) } } } @@ -1391,7 +1391,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { // Has an Iam Instance Profile associated with it, need to remove the association associationId := resp.IamInstanceProfileAssociations[0].AssociationId if err := disassociateInstanceProfile(associationId, conn); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } } } @@ -1508,7 +1508,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { NetworkInterfaceId: primaryInterface.NetworkInterfaceId, Groups: groups, }); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): modifying network interface: %w", d.Id(), err) } } } @@ -1586,13 +1586,13 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("disable_api_stop") && !d.IsNewResource() { if err := disableInstanceAPIStop(conn, d.Id(), d.Get("disable_api_stop").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } } if d.HasChange("disable_api_termination") && !d.IsNewResource() { if err := disableInstanceAPITermination(conn, d.Id(), d.Get("disable_api_termination").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): %w", d.Id(), err) } } @@ -1605,7 +1605,7 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { }, }) if err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): modifying InstanceInitiatedShutdownBehavior: %w", d.Id(), err) } } @@ -1619,11 +1619,11 @@ func resourceInstanceUpdate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("updating EC2 Instance (%s): modifying maintenance options: %w", d.Id(), err) } if _, err := WaitInstanceMaintenanceOptionsAutoRecoveryUpdated(conn, d.Id(), autoRecovery, d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("waiting for EC2 Instance (%s) maintenance options update: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Instance (%s): modifying maintenance options: waiting for completion: %w", d.Id(), err) } } @@ -1834,7 +1834,7 @@ func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { } if err := terminateInstance(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return nil @@ -1854,7 +1854,7 @@ func disableInstanceAPIStop(conn *ec2.EC2, id string, disableAPIStop bool) error } if err != nil { - return fmt.Errorf("modifying EC2 Instance (%s) DisableApiStop attribute: %w", id, err) + return fmt.Errorf("modifying DisableApiStop: %w", err) } return nil @@ -1874,7 +1874,7 @@ func disableInstanceAPITermination(conn *ec2.EC2, id string, disableAPITerminati } if err != nil { - return fmt.Errorf("modifying EC2 Instance (%s) DisableApiTermination attribute: %w", id, err) + return fmt.Errorf("modifying DisableApiTermination: %w", err) } return nil @@ -1919,7 +1919,7 @@ func modifyInstanceAttributeWithStopStart(conn *ec2.EC2, input *ec2.ModifyInstan func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error { ibds, err := readBlockDevicesFromInstance(d, instance, conn) if err != nil { - return err + return fmt.Errorf("reading block devices: %w", err) } // Special handling for instances where the only block device is the root device: @@ -1948,20 +1948,20 @@ func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2. } if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { - return err + return err // nosemgrep:bare-error-returns } // This handles the import case which needs to be defaulted to empty if _, ok := d.GetOk("root_block_device"); !ok { if err := d.Set("root_block_device", []interface{}{}); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if ibds["root"] != nil { roots := []interface{}{ibds["root"]} if err := d.Set("root_block_device", roots); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -1989,7 +1989,7 @@ func associateInstanceProfile(d *schema.ResourceData, conn *ec2.EC2) error { _, err = conn.AssociateIamInstanceProfile(input) } if err != nil { - return fmt.Errorf("error associating instance with instance profile: %s", err) + return fmt.Errorf("associating instance profile: %s", err) } return nil } @@ -1999,7 +1999,7 @@ func disassociateInstanceProfile(associationId *string, conn *ec2.EC2) error { AssociationId: associationId, }) if err != nil { - return fmt.Errorf("error disassociating instance with instance profile: %w", err) + return fmt.Errorf("disassociating instance profile: %w", err) } return nil } @@ -2386,7 +2386,7 @@ func readBlockDeviceMappingsFromConfig(d *schema.ResourceData, conn *ec2.EC2) ([ func readVolumeTags(conn *ec2.EC2, instanceId string) ([]*ec2.Tag, error) { volumeIds, err := getInstanceVolumeIDs(conn, instanceId) if err != nil { - return nil, err + return nil, fmt.Errorf("getting tags for volumes (%s): %s", volumeIds, err) } resp, err := conn.DescribeTags(&ec2.DescribeTagsInput{ @@ -2395,7 +2395,7 @@ func readVolumeTags(conn *ec2.EC2, instanceId string) ([]*ec2.Tag, error) { }), }) if err != nil { - return nil, fmt.Errorf("error getting tags for volumes (%s): %s", volumeIds, err) + return nil, fmt.Errorf("getting tags for volumes (%s): %s", volumeIds, err) } return tagsFromTagDescriptions(resp.Tags), nil @@ -2431,11 +2431,11 @@ func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec } log.Printf("[DEBUG] Setting Security Group IDs: %#v", sgs) if err := d.Set("vpc_security_group_ids", sgs); err != nil { - return err + return err // nosemgrep:bare-error-returns } } else { if err := d.Set("vpc_security_group_ids", []string{}); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if useName { @@ -2445,11 +2445,11 @@ func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec } log.Printf("[DEBUG] Setting Security Group Names: %#v", sgs) if err := d.Set("security_groups", sgs); err != nil { - return err + return err // nosemgrep:bare-error-returns } } else { if err := d.Set("security_groups", []string{}); err != nil { - return err + return err // nosemgrep:bare-error-returns } } return nil @@ -2462,7 +2462,7 @@ func readInstanceShutdownBehavior(d *schema.ResourceData, conn *ec2.EC2) error { }) if err != nil { - return fmt.Errorf("error while describing instance (%s) attribute (%s): %w", d.Id(), ec2.InstanceAttributeNameInstanceInitiatedShutdownBehavior, err) + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameInstanceInitiatedShutdownBehavior, err) } if output != nil && output.InstanceInitiatedShutdownBehavior != nil { @@ -2500,10 +2500,10 @@ func getInstancePasswordData(instanceID string, conn *ec2.EC2) (string, error) { if tfresource.TimedOut(err) { resp, err = conn.GetPasswordData(input) if err != nil { - return "", fmt.Errorf("Error getting password data: %s", err) + return "", fmt.Errorf("getting password data: %s", err) } if resp.PasswordData == nil || aws.StringValue(resp.PasswordData) == "" { - return "", fmt.Errorf("Password data is blank for instance ID: %s", instanceID) + return "", errors.New("password data is blank") } passwordData = strings.TrimSpace(aws.StringValue(resp.PasswordData)) } @@ -2782,11 +2782,11 @@ func StopInstance(conn *ec2.EC2, id string, timeout time.Duration) error { }) if err != nil { - return fmt.Errorf("stopping EC2 Instance (%s): %w", id, err) + return fmt.Errorf("stopping EC2 Instance: %w", err) } if _, err := WaitInstanceStopped(conn, id, timeout); err != nil { - return fmt.Errorf("waiting for EC2 Instance (%s) stop: %w", id, err) + return fmt.Errorf("stopping EC2 Instance: waiting for completion: %w", err) } return nil @@ -2836,7 +2836,7 @@ func getInstanceVolumeIDs(conn *ec2.EC2, instanceId string) ([]string, error) { }), }) if err != nil { - return nil, fmt.Errorf("error getting volumes for instance (%s): %s", instanceId, err) + return nil, fmt.Errorf("getting volumes: %s", err) } for _, v := range resp.Volumes { diff --git a/internal/service/ec2/ec2_instance_data_source.go b/internal/service/ec2/ec2_instance_data_source.go index ad9eceae245..584e09c7820 100644 --- a/internal/service/ec2/ec2_instance_data_source.go +++ b/internal/service/ec2/ec2_instance_data_source.go @@ -419,13 +419,13 @@ func dataSourceInstanceRead(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] aws_instance - Single Instance ID found: %s", aws.StringValue(instance.InstanceId)) if err := instanceDescriptionAttributes(d, instance, conn, ignoreTagsConfig); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", aws.StringValue(instance.InstanceId), err) } if d.Get("get_password_data").(bool) { passwordData, err := getInstancePasswordData(aws.StringValue(instance.InstanceId), conn) if err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", aws.StringValue(instance.InstanceId), err) } d.Set("password_data", passwordData) } @@ -544,12 +544,12 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc // Security Groups if err := readSecurityGroups(d, instance, conn); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", aws.StringValue(instance.InstanceId), err) } // Block devices if err := readBlockDevices(d, instance, conn); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", aws.StringValue(instance.InstanceId), err) } if _, ok := d.GetOk("ephemeral_block_device"); !ok { d.Set("ephemeral_block_device", []interface{}{}) @@ -562,7 +562,7 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc InstanceId: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameDisableApiStop, err) } d.Set("disable_api_stop", attr.DisableApiStop.Value) } @@ -572,7 +572,7 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc InstanceId: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameDisableApiTermination, err) } d.Set("disable_api_termination", attr.DisableApiTermination.Value) } @@ -582,7 +582,7 @@ func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instanc InstanceId: aws.String(d.Id()), }) if err != nil { - return err + return fmt.Errorf("getting attribute (%s): %w", ec2.InstanceAttributeNameUserData, err) } if attr != nil && attr.UserData != nil && attr.UserData.Value != nil { d.Set("user_data", userDataHashSum(aws.StringValue(attr.UserData.Value))) diff --git a/internal/service/ec2/ec2_launch_template.go b/internal/service/ec2/ec2_launch_template.go index d6c00fb23e2..366773184d1 100644 --- a/internal/service/ec2/ec2_launch_template.go +++ b/internal/service/ec2/ec2_launch_template.go @@ -970,14 +970,14 @@ func resourceLaunchTemplateCreate(d *schema.ResourceData, meta interface{}) erro if v, err := expandRequestLaunchTemplateData(conn, d); err == nil { input.LaunchTemplateData = v } else { - return err + return fmt.Errorf("creating EC2 Launch Template (%s): %w", name, err) } log.Printf("[DEBUG] Creating EC2 Launch Template: %s", input) output, err := conn.CreateLaunchTemplate(input) if err != nil { - return fmt.Errorf("error creating EC2 Launch Template: %w", err) + return fmt.Errorf("creating EC2 Launch Template: %w", err) } d.SetId(aws.StringValue(output.LaunchTemplate.LaunchTemplateId)) @@ -1006,7 +1006,7 @@ func resourceLaunchTemplateRead(d *schema.ResourceData, meta interface{}) error ltv, err := FindLaunchTemplateVersionByTwoPartKey(conn, d.Id(), version) if err != nil { - return fmt.Errorf("error reading EC2 Launch Template (%s) Version (%s): %w", d.Id(), version, err) + return fmt.Errorf("reading EC2 Launch Template (%s) Version (%s): %w", d.Id(), version, err) } arn := arn.ARN{ @@ -1024,7 +1024,7 @@ func resourceLaunchTemplateRead(d *schema.ResourceData, meta interface{}) error d.Set("name_prefix", create.NamePrefixFromName(aws.StringValue(lt.LaunchTemplateName))) if err := flattenResponseLaunchTemplateData(conn, d, ltv.LaunchTemplateData); err != nil { - return err + return fmt.Errorf("reading EC2 Launch Template (%s): %w", d.Id(), err) } tags := KeyValueTags(lt.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -1092,7 +1092,7 @@ func resourceLaunchTemplateUpdate(d *schema.ResourceData, meta interface{}) erro if v, err := expandRequestLaunchTemplateData(conn, d); err == nil { input.LaunchTemplateData = v } else { - return err + return fmt.Errorf("updating EC2 Launch Template (%s): %w", d.Id(), err) } output, err := conn.CreateLaunchTemplateVersion(input) @@ -1118,7 +1118,7 @@ func resourceLaunchTemplateUpdate(d *schema.ResourceData, meta interface{}) erro _, err := conn.ModifyLaunchTemplate(input) if err != nil { - return fmt.Errorf("error updating EC2 Launch Template (%s): %w", d.Id(), err) + return fmt.Errorf("updating EC2 Launch Template (%s): %w", d.Id(), err) } } @@ -1126,7 +1126,7 @@ func resourceLaunchTemplateUpdate(d *schema.ResourceData, meta interface{}) erro o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 Launch Template (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Launch Template (%s) tags: %w", d.Id(), err) } } diff --git a/internal/service/ec2/ec2_launch_template_data_source.go b/internal/service/ec2/ec2_launch_template_data_source.go index 4b34eee3253..2b9ec7c0db8 100644 --- a/internal/service/ec2/ec2_launch_template_data_source.go +++ b/internal/service/ec2/ec2_launch_template_data_source.go @@ -784,7 +784,7 @@ func dataSourceLaunchTemplateRead(d *schema.ResourceData, meta interface{}) erro ltv, err := FindLaunchTemplateVersionByTwoPartKey(conn, d.Id(), version) if err != nil { - return fmt.Errorf("error reading EC2 Launch Template (%s) Version (%s): %w", d.Id(), version, err) + return fmt.Errorf("reading EC2 Launch Template (%s) Version (%s): %w", d.Id(), version, err) } arn := arn.ARN{ @@ -801,11 +801,11 @@ func dataSourceLaunchTemplateRead(d *schema.ResourceData, meta interface{}) erro d.Set("name", lt.LaunchTemplateName) if err := flattenResponseLaunchTemplateData(conn, d, ltv.LaunchTemplateData); err != nil { - return err + return fmt.Errorf("reading EC2 Launch Template (%s): %w", d.Id(), err) } if err := d.Set("tags", KeyValueTags(lt.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("reading EC2 Launch Template (%s): setting tags: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/ec2_spot_fleet_request.go b/internal/service/ec2/ec2_spot_fleet_request.go index ed2e927b16f..f802944aa25 100644 --- a/internal/service/ec2/ec2_spot_fleet_request.go +++ b/internal/service/ec2/ec2_spot_fleet_request.go @@ -849,7 +849,7 @@ func resourceSpotFleetRequestCreate(d *schema.ResourceData, meta interface{}) er if launchSpecificationOk { launchSpecs, err := buildSpotFleetLaunchSpecifications(d, meta) if err != nil { - return err + return fmt.Errorf("creating EC2 Spot Fleet Request: %w", err) } spotFleetConfig.LaunchSpecifications = launchSpecs } diff --git a/internal/service/ec2/ec2_spot_instance_request.go b/internal/service/ec2/ec2_spot_instance_request.go index 204ba9a6e55..fe0560864ed 100644 --- a/internal/service/ec2/ec2_spot_instance_request.go +++ b/internal/service/ec2/ec2_spot_instance_request.go @@ -137,7 +137,7 @@ func resourceSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) instanceOpts, err := buildInstanceOpts(d, meta) if err != nil { - return err + return fmt.Errorf("requesting EC2 Spot Instances: %s", err) } spotOpts := &ec2.RequestSpotInstancesInput{ @@ -177,7 +177,7 @@ func resourceSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) if v, ok := d.GetOk("valid_from"); ok { validFrom, err := time.Parse(time.RFC3339, v.(string)) if err != nil { - return err + return fmt.Errorf("requesting EC2 Spot Instances: %s", err) } spotOpts.ValidFrom = aws.Time(validFrom) } @@ -185,7 +185,7 @@ func resourceSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) if v, ok := d.GetOk("valid_until"); ok { validUntil, err := time.Parse(time.RFC3339, v.(string)) if err != nil { - return err + return fmt.Errorf("requesting EC2 Spot Instances: %s", err) } spotOpts.ValidUntil = aws.Time(validUntil) } @@ -196,8 +196,6 @@ func resourceSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) } // Make the spot instance request - log.Printf("[DEBUG] Requesting spot bid opts: %s", spotOpts) - var resp *ec2.RequestSpotInstancesOutput err = resource.Retry(propagationTimeout, func() *resource.RetryError { resp, err = conn.RequestSpotInstances(spotOpts) @@ -223,7 +221,7 @@ func resourceSpotInstanceRequestCreate(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("Error requesting spot instances: %s", err) + return fmt.Errorf("requesting EC2 Spot Instances: %s", err) } if len(resp.SpotInstanceRequests) != 1 { return fmt.Errorf( @@ -320,7 +318,7 @@ func readInstance(d *schema.ResourceData, meta interface{}) error { instance, err := FindInstanceByID(conn, d.Get("spot_instance_id").(string)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } d.Set("public_dns", instance.PublicDnsName) @@ -342,7 +340,7 @@ func readInstance(d *schema.ResourceData, meta interface{}) error { }) } if err := readBlockDevices(d, instance, conn); err != nil { - return err + return err // nosemgrep:bare-error-returns } var ipv6Addresses []string @@ -369,13 +367,13 @@ func readInstance(d *schema.ResourceData, meta interface{}) error { } if err := readSecurityGroups(d, instance, conn); err != nil { - return err + return fmt.Errorf("reading EC2 Instance (%s): %w", aws.StringValue(instance.InstanceId), err) } if d.Get("get_password_data").(bool) { passwordData, err := getInstancePasswordData(*instance.InstanceId, conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } d.Set("password_data", passwordData) } else { @@ -414,7 +412,7 @@ func resourceSpotInstanceRequestDelete(d *schema.ResourceData, meta interface{}) if instanceId := d.Get("spot_instance_id").(string); instanceId != "" { if err := terminateInstance(conn, instanceId, d.Timeout(schema.TimeoutDelete)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } diff --git a/internal/service/ec2/ipam_pool_cidr.go b/internal/service/ec2/ipam_pool_cidr.go index 9d4b85f5243..a44fc1de6a8 100644 --- a/internal/service/ec2/ipam_pool_cidr.go +++ b/internal/service/ec2/ipam_pool_cidr.go @@ -110,7 +110,7 @@ func resourceIPAMPoolCIDRRead(d *schema.ResourceData, meta interface{}) error { cidrBlock, poolID, err := IPAMPoolCIDRParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IPAM Pool CIDR (%s): %w", d.Id(), err) } output, err := FindIPAMPoolCIDRByTwoPartKey(conn, cidrBlock, poolID) @@ -137,7 +137,7 @@ func resourceIPAMPoolCIDRDelete(d *schema.ResourceData, meta interface{}) error cidrBlock, poolID, err := IPAMPoolCIDRParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IPAM Pool CIDR (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting IPAM Pool CIDR: %s", d.Id()) diff --git a/internal/service/ec2/ipam_pool_cidr_allocation.go b/internal/service/ec2/ipam_pool_cidr_allocation.go index 91752f1f3bf..d08c4788230 100644 --- a/internal/service/ec2/ipam_pool_cidr_allocation.go +++ b/internal/service/ec2/ipam_pool_cidr_allocation.go @@ -130,7 +130,7 @@ func resourceIPAMPoolCIDRAllocationRead(d *schema.ResourceData, meta interface{} allocationID, poolID, err := IPAMPoolCIDRAllocationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading IPAM Pool CIDR Allocation (%s): %w", d.Id(), err) } allocation, err := FindIPAMPoolAllocationByTwoPartKey(conn, allocationID, poolID) @@ -167,7 +167,7 @@ func resourceIPAMPoolCIDRAllocationDelete(d *schema.ResourceData, meta interface allocationID, poolID, err := IPAMPoolCIDRAllocationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting IPAM Pool CIDR Allocation (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting IPAM Pool CIDR Allocation: %s", d.Id()) diff --git a/internal/service/ec2/ipam_preview_next_cidr.go b/internal/service/ec2/ipam_preview_next_cidr.go index 3b7d8b180ac..4f93278b741 100644 --- a/internal/service/ec2/ipam_preview_next_cidr.go +++ b/internal/service/ec2/ipam_preview_next_cidr.go @@ -99,7 +99,7 @@ func resourceIPAMPreviewNextCIDRRead(d *schema.ResourceData, meta interface{}) e cidr, poolId, err := decodeIPAMPreviewNextCIDRID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 IPAM Preview Next CIDR: %w", err) } d.Set("cidr", cidr) diff --git a/internal/service/ec2/outposts_local_gateway_route.go b/internal/service/ec2/outposts_local_gateway_route.go index 8139bf200fd..929ad884297 100644 --- a/internal/service/ec2/outposts_local_gateway_route.go +++ b/internal/service/ec2/outposts_local_gateway_route.go @@ -78,7 +78,7 @@ func resourceLocalGatewayRouteRead(d *schema.ResourceData, meta interface{}) err localGatewayRouteTableID, destination, err := DecodeLocalGatewayRouteID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Local Gateway Route (%s): %s", d.Id(), err) } var localGatewayRoute *ec2.LocalGatewayRoute @@ -114,7 +114,7 @@ func resourceLocalGatewayRouteRead(d *schema.ResourceData, meta interface{}) err } if err != nil { - return fmt.Errorf("error reading EC2 Local Gateway Route: %s", err) + return fmt.Errorf("reading EC2 Local Gateway Route (%s): %s", d.Id(), err) } if localGatewayRoute == nil { @@ -142,7 +142,7 @@ func resourceLocalGatewayRouteDelete(d *schema.ResourceData, meta interface{}) e localGatewayRouteTableID, destination, err := DecodeLocalGatewayRouteID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Local Gateway Route (%s): %s", d.Id(), err) } input := &ec2.DeleteLocalGatewayRouteInput{ @@ -158,7 +158,7 @@ func resourceLocalGatewayRouteDelete(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("error deleting EC2 Local Gateway Route: %s", err) + return fmt.Errorf("deleting EC2 Local Gateway Route (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/ec2/transitgateway_policy_table_association.go b/internal/service/ec2/transitgateway_policy_table_association.go index e5e9882cb7a..9ec9e14fb88 100644 --- a/internal/service/ec2/transitgateway_policy_table_association.go +++ b/internal/service/ec2/transitgateway_policy_table_association.go @@ -107,7 +107,7 @@ func resourceTransitGatewayPolicyTableAssociationRead(d *schema.ResourceData, me transitGatewayPolicyTableID, transitGatewayAttachmentID, err := TransitGatewayPolicyTableAssociationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Transit Gateway Policy Table Association (%s): %w", d.Id(), err) } transitGatewayPolicyTableAssociation, err := FindTransitGatewayPolicyTableAssociationByTwoPartKey(conn, transitGatewayPolicyTableID, transitGatewayAttachmentID) @@ -136,7 +136,7 @@ func resourceTransitGatewayPolicyTableAssociationDelete(d *schema.ResourceData, transitGatewayPolicyTableID, transitGatewayAttachmentID, err := TransitGatewayPolicyTableAssociationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Transit Gateway Policy Table Association (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting EC2 Transit Gateway Policy Table Association: %s", d.Id()) diff --git a/internal/service/ec2/transitgateway_prefix_list_reference.go b/internal/service/ec2/transitgateway_prefix_list_reference.go index 2d0717d8912..0d79b4cb4fa 100644 --- a/internal/service/ec2/transitgateway_prefix_list_reference.go +++ b/internal/service/ec2/transitgateway_prefix_list_reference.go @@ -97,7 +97,7 @@ func resourceTransitGatewayPrefixListReferenceRead(d *schema.ResourceData, meta transitGatewayRouteTableID, prefixListID, err := TransitGatewayPrefixListReferenceParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Transit Gateway Prefix List Reference (%s): %w", d.Id(), err) } transitGatewayPrefixListReference, err := FindTransitGatewayPrefixListReferenceByTwoPartKey(conn, transitGatewayRouteTableID, prefixListID) @@ -165,7 +165,7 @@ func resourceTransitGatewayPrefixListReferenceDelete(d *schema.ResourceData, met transitGatewayRouteTableID, prefixListID, err := TransitGatewayPrefixListReferenceParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Transit Gateway Prefix List Reference (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Creating EC2 Transit Gateway Prefix List Reference: %s", d.Id()) diff --git a/internal/service/ec2/transitgateway_route.go b/internal/service/ec2/transitgateway_route.go index 122b2094336..920e432ca6b 100644 --- a/internal/service/ec2/transitgateway_route.go +++ b/internal/service/ec2/transitgateway_route.go @@ -89,7 +89,7 @@ func resourceTransitGatewayRouteRead(d *schema.ResourceData, meta interface{}) e transitGatewayRouteTableID, destination, err := TransitGatewayRouteParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Transit Gateway Route (%s): %w", d.Id(), err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(propagationTimeout, func() (interface{}, error) { @@ -127,7 +127,7 @@ func resourceTransitGatewayRouteDelete(d *schema.ResourceData, meta interface{}) transitGatewayRouteTableID, destination, err := TransitGatewayRouteParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Transit Gateway Route (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting EC2 Transit Gateway Route: %s", d.Id()) diff --git a/internal/service/ec2/transitgateway_route_table_association.go b/internal/service/ec2/transitgateway_route_table_association.go index 393b4295354..1ca900cb668 100644 --- a/internal/service/ec2/transitgateway_route_table_association.go +++ b/internal/service/ec2/transitgateway_route_table_association.go @@ -81,7 +81,7 @@ func resourceTransitGatewayRouteTableAssociationRead(d *schema.ResourceData, met transitGatewayRouteTableID, transitGatewayAttachmentID, err := TransitGatewayRouteTableAssociationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Transit Gateway Route Table Association (%s): %w", d.Id(), err) } transitGatewayRouteTableAssociation, err := FindTransitGatewayRouteTableAssociationByTwoPartKey(conn, transitGatewayRouteTableID, transitGatewayAttachmentID) @@ -110,7 +110,7 @@ func resourceTransitGatewayRouteTableAssociationDelete(d *schema.ResourceData, m transitGatewayRouteTableID, transitGatewayAttachmentID, err := TransitGatewayRouteTableAssociationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Transit Gateway Route Table Association (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting EC2 Transit Gateway Route Table Association: %s", d.Id()) diff --git a/internal/service/ec2/transitgateway_route_table_propagation.go b/internal/service/ec2/transitgateway_route_table_propagation.go index 1e85cf2c99e..d8e416c5cb7 100644 --- a/internal/service/ec2/transitgateway_route_table_propagation.go +++ b/internal/service/ec2/transitgateway_route_table_propagation.go @@ -81,7 +81,7 @@ func resourceTransitGatewayRouteTablePropagationRead(d *schema.ResourceData, met transitGatewayRouteTableID, transitGatewayAttachmentID, err := TransitGatewayRouteTablePropagationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Transit Gateway Route Table Propagation (%s): %w", d.Id(), err) } transitGatewayPropagation, err := FindTransitGatewayRouteTablePropagationByTwoPartKey(conn, transitGatewayRouteTableID, transitGatewayAttachmentID) @@ -110,7 +110,7 @@ func resourceTransitGatewayRouteTablePropagationDelete(d *schema.ResourceData, m transitGatewayRouteTableID, transitGatewayAttachmentID, err := TransitGatewayRouteTablePropagationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Transit Gateway Route Table Propagation (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting EC2 Transit Gateway Route Table Propagation: %s", d.Id()) diff --git a/internal/service/ec2/transitgateway_vpc_attachment.go b/internal/service/ec2/transitgateway_vpc_attachment.go index 6e039162200..d2d27cb1bb2 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment.go +++ b/internal/service/ec2/transitgateway_vpc_attachment.go @@ -126,11 +126,11 @@ func resourceTransitGatewayVPCAttachmentCreate(d *schema.ResourceData, meta inte // We cannot modify Transit Gateway Route Tables for Resource Access Manager shared Transit Gateways. if aws.StringValue(transitGateway.OwnerId) == aws.StringValue(output.TransitGatewayVpcAttachment.VpcOwnerId) { if err := transitGatewayRouteTableAssociationUpdate(conn, aws.StringValue(transitGateway.Options.AssociationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_association").(bool)); err != nil { - return err + return fmt.Errorf("creating EC2 Transit Gateway VPC Attachment: %w", err) } if err := transitGatewayRouteTablePropagationUpdate(conn, aws.StringValue(transitGateway.Options.PropagationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_propagation").(bool)); err != nil { - return err + return fmt.Errorf("creating EC2 Transit Gateway VPC Attachment: %w", err) } } @@ -259,13 +259,13 @@ func resourceTransitGatewayVPCAttachmentUpdate(d *schema.ResourceData, meta inte if d.HasChange("transit_gateway_default_route_table_association") { if err := transitGatewayRouteTableAssociationUpdate(conn, aws.StringValue(transitGateway.Options.AssociationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_association").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 Transit Gateway VPC Attachment (%s): %w", d.Id(), err) } } if d.HasChange("transit_gateway_default_route_table_propagation") { if err := transitGatewayRouteTablePropagationUpdate(conn, aws.StringValue(transitGateway.Options.PropagationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_propagation").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 Transit Gateway VPC Attachment (%s): %w", d.Id(), err) } } } diff --git a/internal/service/ec2/transitgateway_vpc_attachment_accepter.go b/internal/service/ec2/transitgateway_vpc_attachment_accepter.go index 441a30bd63d..1536b04bd2a 100644 --- a/internal/service/ec2/transitgateway_vpc_attachment_accepter.go +++ b/internal/service/ec2/transitgateway_vpc_attachment_accepter.go @@ -99,12 +99,12 @@ func resourceTransitGatewayVPCAttachmentAccepterCreate(d *schema.ResourceData, m transitGatewayID := aws.StringValue(output.TransitGatewayVpcAttachment.TransitGatewayId) if _, err := WaitTransitGatewayVPCAttachmentAccepted(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for EC2 Transit Gateway VPC Attachment (%s) update: %w", d.Id(), err) + return fmt.Errorf("accepting EC2 Transit Gateway VPC Attachment (%s): waiting for completion: %w", transitGatewayAttachmentID, err) } if len(tags) > 0 { if err := CreateTags(conn, d.Id(), tags); err != nil { - return fmt.Errorf("updating EC2 Transit Gateway VPC Attachment (%s) tags: %w", d.Id(), err) + return fmt.Errorf("accepting EC2 Transit Gateway VPC Attachment (%s): setting tags: %w", transitGatewayAttachmentID, err) } } @@ -115,11 +115,11 @@ func resourceTransitGatewayVPCAttachmentAccepterCreate(d *schema.ResourceData, m } if err := transitGatewayRouteTableAssociationUpdate(conn, aws.StringValue(transitGateway.Options.AssociationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_association").(bool)); err != nil { - return err + return fmt.Errorf("accepting EC2 Transit Gateway VPC Attachment (%s): %w", transitGatewayAttachmentID, err) } if err := transitGatewayRouteTablePropagationUpdate(conn, aws.StringValue(transitGateway.Options.PropagationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_propagation").(bool)); err != nil { - return err + return fmt.Errorf("accepting EC2 Transit Gateway VPC Attachment (%s): %w", transitGatewayAttachmentID, err) } return resourceTransitGatewayVPCAttachmentAccepterRead(d, meta) @@ -214,13 +214,13 @@ func resourceTransitGatewayVPCAttachmentAccepterUpdate(d *schema.ResourceData, m if d.HasChange("transit_gateway_default_route_table_association") { if err := transitGatewayRouteTableAssociationUpdate(conn, aws.StringValue(transitGateway.Options.AssociationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_association").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 Transit Gateway VPC Attachment (%s): %w", d.Id(), err) } } if d.HasChange("transit_gateway_default_route_table_propagation") { if err := transitGatewayRouteTablePropagationUpdate(conn, aws.StringValue(transitGateway.Options.PropagationDefaultRouteTableId), d.Id(), d.Get("transit_gateway_default_route_table_propagation").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 Transit Gateway VPC Attachment (%s): %w", d.Id(), err) } } } @@ -253,7 +253,7 @@ func resourceTransitGatewayVPCAttachmentAccepterDelete(d *schema.ResourceData, m } if _, err := WaitTransitGatewayVPCAttachmentDeleted(conn, d.Id()); err != nil { - return fmt.Errorf("waiting for EC2 Transit Gateway VPC Attachment (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Transit Gateway VPC Attachment (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_.go b/internal/service/ec2/vpc_.go index 721e83df91c..cc1edb4360b 100644 --- a/internal/service/ec2/vpc_.go +++ b/internal/service/ec2/vpc_.go @@ -221,7 +221,7 @@ func resourceVPCCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateVpc(input) if err != nil { - return fmt.Errorf("error creating EC2 VPC: %w", err) + return fmt.Errorf("creating EC2 VPC: %w", err) } d.SetId(aws.StringValue(output.Vpc.VpcId)) @@ -252,7 +252,7 @@ func resourceVPCCreate(d *schema.ResourceData, meta interface{}) error { } if err := modifyVPCAttributesOnCreate(conn, d, &vpcInfo); err != nil { - return err + return fmt.Errorf("creating EC2 VPC: %w", err) } return resourceVPCRead(d, meta) @@ -407,37 +407,37 @@ func resourceVPCUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("enable_dns_hostnames") { if err := modifyVPCDNSHostnames(conn, d.Id(), d.Get("enable_dns_hostnames").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } } if d.HasChange("enable_dns_support") { if err := modifyVPCDNSSupport(conn, d.Id(), d.Get("enable_dns_support").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } } if d.HasChange("enable_network_address_usage_metrics") { if err := modifyVPCNetworkAddressUsageMetrics(conn, d.Id(), d.Get("enable_network_address_usage_metrics").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } } if d.HasChange("enable_classiclink") { if err := modifyVPCClassicLink(conn, d.Id(), d.Get("enable_classiclink").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } } if d.HasChange("enable_classiclink_dns_support") { if err := modifyVPCClassicLinkDNSSupport(conn, d.Id(), d.Get("enable_classiclink_dns_support").(bool)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } } if d.HasChange("instance_tenancy") { if err := modifyVPCTenancy(conn, d.Id(), d.Get("instance_tenancy").(string)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } } @@ -451,7 +451,7 @@ func resourceVPCUpdate(d *schema.ResourceData, meta interface{}) error { d.Get("ipv6_cidr_block_network_border_group").(string)) if err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } d.Set("ipv6_association_id", associationID) @@ -467,7 +467,7 @@ func resourceVPCUpdate(d *schema.ResourceData, meta interface{}) error { "") if err != nil { - return err + return fmt.Errorf("updating EC2 VPC (%s): %w", d.Id(), err) } d.Set("ipv6_association_id", associationID) @@ -477,7 +477,7 @@ func resourceVPCUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 VPC (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 VPC (%s): updating tags: %w", d.Id(), err) } } @@ -628,7 +628,7 @@ func modifyVPCClassicLink(conn *ec2.EC2, vpcID string, v bool) error { } if _, err := conn.EnableVpcClassicLink(input); err != nil { - return fmt.Errorf("error enabling EC2 VPC (%s) ClassicLink: %w", vpcID, err) + return fmt.Errorf("enabling EnableDnsHostnames: %w", err) } } else { input := &ec2.DisableVpcClassicLinkInput{ @@ -636,7 +636,7 @@ func modifyVPCClassicLink(conn *ec2.EC2, vpcID string, v bool) error { } if _, err := conn.DisableVpcClassicLink(input); err != nil { - return fmt.Errorf("error disabling EC2 VPC (%s) ClassicLink: %w", vpcID, err) + return fmt.Errorf("disabling EnableDnsHostnames: %w", err) } } @@ -650,7 +650,7 @@ func modifyVPCClassicLinkDNSSupport(conn *ec2.EC2, vpcID string, v bool) error { } if _, err := conn.EnableVpcClassicLinkDnsSupport(input); err != nil { - return fmt.Errorf("error enabling EC2 VPC (%s) ClassicLinkDnsSupport: %w", vpcID, err) + return fmt.Errorf("enabling ClassicLinkDnsSupport: %w", err) } } else { input := &ec2.DisableVpcClassicLinkDnsSupportInput{ @@ -658,7 +658,7 @@ func modifyVPCClassicLinkDNSSupport(conn *ec2.EC2, vpcID string, v bool) error { } if _, err := conn.DisableVpcClassicLinkDnsSupport(input); err != nil { - return fmt.Errorf("error disabling EC2 VPC (%s) ClassicLinkDnsSupport: %w", vpcID, err) + return fmt.Errorf("disabling ClassicLinkDnsSupport: %w", err) } } @@ -674,11 +674,11 @@ func modifyVPCDNSHostnames(conn *ec2.EC2, vpcID string, v bool) error { } if _, err := conn.ModifyVpcAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 VPC (%s) EnableDnsHostnames: %w", vpcID, err) + return fmt.Errorf("modifying EnableDnsHostnames: %w", err) } if _, err := WaitVPCAttributeUpdated(conn, vpcID, ec2.VpcAttributeNameEnableDnsHostnames, v); err != nil { - return fmt.Errorf("error waiting for EC2 VPC (%s) EnableDnsHostnames update: %w", vpcID, err) + return fmt.Errorf("modifying EnableDnsHostnames: waiting for completion: %w", err) } return nil @@ -693,11 +693,11 @@ func modifyVPCDNSSupport(conn *ec2.EC2, vpcID string, v bool) error { } if _, err := conn.ModifyVpcAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 VPC (%s) EnableDnsSupport: %w", vpcID, err) + return fmt.Errorf("modifying EnableDnsSupport: %w", err) } if _, err := WaitVPCAttributeUpdated(conn, vpcID, ec2.VpcAttributeNameEnableDnsSupport, v); err != nil { - return fmt.Errorf("error waiting for EC2 VPC (%s) EnableDnsSupport update: %w", vpcID, err) + return fmt.Errorf("modifying EnableDnsSupport: waiting for completion: %w", err) } return nil @@ -712,11 +712,11 @@ func modifyVPCNetworkAddressUsageMetrics(conn *ec2.EC2, vpcID string, v bool) er } if _, err := conn.ModifyVpcAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 VPC (%s) EnableNetworkAddressUsageMetrics: %w", vpcID, err) + return fmt.Errorf("modifying EnableNetworkAddressUsageMetrics: %w", err) } if _, err := WaitVPCAttributeUpdated(conn, vpcID, ec2.VpcAttributeNameEnableNetworkAddressUsageMetrics, v); err != nil { - return fmt.Errorf("error waiting for EC2 VPC (%s) EnableNetworkAddressUsageMetrics update: %w", vpcID, err) + return fmt.Errorf("modifying EnableNetworkAddressUsageMetrics: waiting for completion: %w", err) } return nil @@ -733,13 +733,13 @@ func modifyVPCIPv6CIDRBlockAssociation(conn *ec2.EC2, vpcID, associationID strin _, err := conn.DisassociateVpcCidrBlock(input) if err != nil { - return "", fmt.Errorf("error disassociating EC2 VPC (%s) IPv6 CIDR block (%s): %w", vpcID, associationID, err) + return "", fmt.Errorf("disassociating IPv6 CIDR block (%s): %w", associationID, err) } _, err = WaitVPCIPv6CIDRBlockAssociationDeleted(conn, associationID, vpcIPv6CIDRBlockAssociationDeletedTimeout) if err != nil { - return "", fmt.Errorf("error waiting for EC2 VPC (%s) IPv6 CIDR block (%s) to become disassociated: %w", vpcID, associationID, err) + return "", fmt.Errorf("disassociating IPv6 CIDR block (%s): waiting for completion: %w", associationID, err) } } @@ -771,7 +771,7 @@ func modifyVPCIPv6CIDRBlockAssociation(conn *ec2.EC2, vpcID, associationID strin output, err := conn.AssociateVpcCidrBlock(input) if err != nil { - return "", fmt.Errorf("error associating EC2 VPC (%s) IPv6 CIDR block: %w", vpcID, err) + return "", fmt.Errorf("associating IPv6 CIDR block: %w", err) } associationID = aws.StringValue(output.Ipv6CidrBlockAssociation.AssociationId) @@ -779,7 +779,7 @@ func modifyVPCIPv6CIDRBlockAssociation(conn *ec2.EC2, vpcID, associationID strin _, err = WaitVPCIPv6CIDRBlockAssociationCreated(conn, associationID, vpcIPv6CIDRBlockAssociationCreatedTimeout) if err != nil { - return "", fmt.Errorf("error waiting for EC2 VPC (%s) IPv6 CIDR block (%s) to become associated: %w", vpcID, associationID, err) + return "", fmt.Errorf("associating IPv6 CIDR block: waiting for completion: %w", err) } } @@ -793,7 +793,7 @@ func modifyVPCTenancy(conn *ec2.EC2, vpcID string, v string) error { } if _, err := conn.ModifyVpcTenancy(input); err != nil { - return fmt.Errorf("error modifying EC2 VPC (%s) Tenancy: %w", vpcID, err) + return fmt.Errorf("modifying Tenancy: %w", err) } return nil diff --git a/internal/service/ec2/vpc_default_network_acl.go b/internal/service/ec2/vpc_default_network_acl.go index 3af72d98d6a..5f8fc02ac90 100644 --- a/internal/service/ec2/vpc_default_network_acl.go +++ b/internal/service/ec2/vpc_default_network_acl.go @@ -1,12 +1,14 @@ package ec2 import ( + "context" "fmt" - "log" "github.com/aws/aws-sdk-go/aws" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-provider-aws/internal/conns" + "github.com/hashicorp/terraform-provider-aws/internal/errs" tftags "github.com/hashicorp/terraform-provider-aws/internal/tags" "github.com/hashicorp/terraform-provider-aws/internal/verify" ) @@ -29,10 +31,10 @@ func ResourceDefaultNetworkACL() *schema.Resource { } return &schema.Resource{ - Create: resourceDefaultNetworkACLCreate, - Read: resourceNetworkACLRead, - Update: resourceDefaultNetworkACLUpdate, - Delete: resourceDefaultNetworkACLDelete, + Create: resourceDefaultNetworkACLCreate, + Read: resourceNetworkACLRead, + Update: resourceDefaultNetworkACLUpdate, + DeleteContext: resourceDefaultNetworkACLDelete, // nosemgrep:ci.avoid-context-CRUD-handlers Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { @@ -96,7 +98,7 @@ func resourceDefaultNetworkACLCreate(d *schema.ResourceData, meta interface{}) e nacl, err := FindNetworkACLByID(conn, naclID) if err != nil { - return fmt.Errorf("error reading EC2 Network ACL (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Network ACL (%s): %w", naclID, err) } if !aws.BoolValue(nacl.IsDefault) { @@ -107,11 +109,11 @@ func resourceDefaultNetworkACLCreate(d *schema.ResourceData, meta interface{}) e // Revoke all default and pre-existing rules on the default network ACL. if err := deleteNetworkACLEntries(conn, d.Id(), nacl.Entries); err != nil { - return err + return err // nosemgrep:bare-error-returns } if err := modifyNetworkACLAttributesOnCreate(conn, d); err != nil { - return err + return err // nosemgrep:bare-error-returns } // Configure tags. @@ -141,14 +143,12 @@ func resourceDefaultNetworkACLUpdate(d *schema.ResourceData, meta interface{}) e // it must be destroyed, or assigned to different Network ACL. Those // operations are not handled here. if err := modifyNetworkACLAttributesOnUpdate(conn, d, false); err != nil { - return err + return fmt.Errorf("updating EC2 Default Network ACL (%s): %w", d.Id(), err) } return resourceNetworkACLRead(d, meta) } -func resourceDefaultNetworkACLDelete(d *schema.ResourceData, meta interface{}) error { - log.Printf("[WARN] EC2 Default Network ACL (%s) not deleted, removing from state", d.Id()) - - return nil +func resourceDefaultNetworkACLDelete(_ context.Context, d *schema.ResourceData, meta interface{}) (diags diag.Diagnostics) { + return errs.AppendWarningf(diags, "EC2 Default Network ACL (%s) not deleted, removing from state", d.Id()) } diff --git a/internal/service/ec2/vpc_default_route_table.go b/internal/service/ec2/vpc_default_route_table.go index 00e177e3669..656467e1f54 100644 --- a/internal/service/ec2/vpc_default_route_table.go +++ b/internal/service/ec2/vpc_default_route_table.go @@ -152,7 +152,7 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e routeTable, err := FindRouteTableByID(conn, routeTableID) if err != nil { - return fmt.Errorf("error reading EC2 Default Route Table (%s): %w", routeTableID, err) + return fmt.Errorf("reading EC2 Default Route Table (%s): %w", routeTableID, err) } d.SetId(aws.StringValue(routeTable.RouteTableId)) @@ -160,7 +160,7 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e // Remove all existing VGW associations. for _, v := range routeTable.PropagatingVgws { if err := routeTableDisableVGWRoutePropagation(conn, d.Id(), aws.StringValue(v.GatewayId)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -210,13 +210,13 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e } if err != nil { - return fmt.Errorf("error deleting Route in EC2 Default Route Table (%s) with destination (%s): %w", d.Id(), destination, err) + return fmt.Errorf("deleting Route in EC2 Default Route Table (%s) with destination (%s): %w", d.Id(), destination, err) } _, err = WaitRouteDeleted(conn, routeFinder, routeTableID, destination, d.Timeout(schema.TimeoutCreate)) if err != nil { - return fmt.Errorf("error waiting for Route in EC2 Default Route Table (%s) with destination (%s) to delete: %w", d.Id(), destination, err) + return fmt.Errorf("waiting for Route in EC2 Default Route Table (%s) with destination (%s) to delete: %w", d.Id(), destination, err) } } @@ -226,7 +226,7 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e v := v.(string) if err := routeTableEnableVGWRoutePropagation(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -237,14 +237,14 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e v := v.(map[string]interface{}) if err := routeTableAddRoute(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } if len(tags) > 0 { if err := CreateTags(conn, d.Id(), tags); err != nil { - return fmt.Errorf("error adding tags: %w", err) + return fmt.Errorf("adding tags: %w", err) } } diff --git a/internal/service/ec2/vpc_default_subnet.go b/internal/service/ec2/vpc_default_subnet.go index 776a8eac551..ae0ab323a43 100644 --- a/internal/service/ec2/vpc_default_subnet.go +++ b/internal/service/ec2/vpc_default_subnet.go @@ -222,7 +222,7 @@ func resourceDefaultSubnetCreate(d *schema.ResourceData, meta interface{}) error } if err := modifySubnetAttributesOnCreate(conn, d, subnet, computedIPv6CIDRBlock); err != nil { - return err + return err // nosemgrep:bare-error-returns } // Configure tags. diff --git a/internal/service/ec2/vpc_default_vpc.go b/internal/service/ec2/vpc_default_vpc.go index ff2ddd56a41..55b2ba922dc 100644 --- a/internal/service/ec2/vpc_default_vpc.go +++ b/internal/service/ec2/vpc_default_vpc.go @@ -220,7 +220,7 @@ func resourceDefaultVPCCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateDefaultVpc(input) if err != nil { - return fmt.Errorf("error creating EC2 Default VPC: %w", err) + return fmt.Errorf("creating EC2 Default VPC: %w", err) } vpc = output.Vpc @@ -245,7 +245,7 @@ func resourceDefaultVPCCreate(d *schema.ResourceData, meta interface{}) error { } if err := modifyVPCAttributesOnCreate(conn, d, vpcInfo); err != nil { - return err + return fmt.Errorf("creating EC2 Default VPC: %w", err) } // Configure IPv6. @@ -274,7 +274,7 @@ func resourceDefaultVPCCreate(d *schema.ResourceData, meta interface{}) error { newIPv6CIDRBlockNetworkBorderGroup) if err != nil { - return err + return fmt.Errorf("creating EC2 Default VPC: %w", err) } d.Set("ipv6_association_id", associationID) @@ -290,7 +290,7 @@ func resourceDefaultVPCCreate(d *schema.ResourceData, meta interface{}) error { "") if err != nil { - return err + return fmt.Errorf("creating EC2 Default VPC: %w", err) } d.Set("ipv6_association_id", associationID) diff --git a/internal/service/ec2/vpc_dhcp_options.go b/internal/service/ec2/vpc_dhcp_options.go index 166b5f1d745..a7785c11723 100644 --- a/internal/service/ec2/vpc_dhcp_options.go +++ b/internal/service/ec2/vpc_dhcp_options.go @@ -96,7 +96,7 @@ func resourceVPCDHCPOptionsCreate(d *schema.ResourceData, meta interface{}) erro dhcpConfigurations, err := optionsMap.resourceDataToDHCPConfigurations(d) if err != nil { - return err + return fmt.Errorf("creating EC2 DHCP Options: %w", err) } input := &ec2.CreateDhcpOptionsInput{ @@ -107,7 +107,7 @@ func resourceVPCDHCPOptionsCreate(d *schema.ResourceData, meta interface{}) erro output, err := conn.CreateDhcpOptions(input) if err != nil { - return fmt.Errorf("error creating EC2 DHCP Options Set: %w", err) + return fmt.Errorf("creating EC2 DHCP Options: %w", err) } d.SetId(aws.StringValue(output.DhcpOptions.DhcpOptionsId)) @@ -131,7 +131,7 @@ func resourceVPCDHCPOptionsRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading EC2 DHCP Options Set (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 DHCP Options (%s): %w", d.Id(), err) } opts := outputRaw.(*ec2.DhcpOptions) @@ -150,7 +150,7 @@ func resourceVPCDHCPOptionsRead(d *schema.ResourceData, meta interface{}) error err = optionsMap.dhcpConfigurationsToResourceData(opts.DhcpConfigurations, d) if err != nil { - return err + return fmt.Errorf("reading EC2 DHCP Options (%s): %w", d.Id(), err) } tags := KeyValueTags(opts.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) diff --git a/internal/service/ec2/vpc_dhcp_options_association.go b/internal/service/ec2/vpc_dhcp_options_association.go index 66675bd9735..6eac3d89597 100644 --- a/internal/service/ec2/vpc_dhcp_options_association.go +++ b/internal/service/ec2/vpc_dhcp_options_association.go @@ -67,7 +67,7 @@ func resourceVPCDHCPOptionsAssociationRead(d *schema.ResourceData, meta interfac dhcpOptionsID, vpcID, err := VPCDHCPOptionsAssociationParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 VPC DHCP Options Set Association (%s): %w", d.Id(), err) } _, err = tfresource.RetryWhenNewResourceNotFound(propagationTimeout, func() (interface{}, error) { @@ -81,7 +81,7 @@ func resourceVPCDHCPOptionsAssociationRead(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error reading EC2 VPC DHCP Options Set Association (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 VPC DHCP Options Set Association (%s): %w", d.Id(), err) } d.Set("dhcp_options_id", dhcpOptionsID) @@ -96,7 +96,7 @@ func resourceVPCDHCPOptionsAssociationDelete(d *schema.ResourceData, meta interf dhcpOptionsID, vpcID, err := VPCDHCPOptionsAssociationParseResourceID(d.Id()) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if dhcpOptionsID == DefaultDHCPOptionsID { @@ -117,10 +117,10 @@ func resourceVPCDHCPOptionsAssociationDelete(d *schema.ResourceData, meta interf } if err != nil { - return fmt.Errorf("error disassociating EC2 DHCP Options Set (%s) from VPC (%s): %w", dhcpOptionsID, vpcID, err) + return fmt.Errorf("disassociating EC2 DHCP Options Set (%s) from VPC (%s): %w", dhcpOptionsID, vpcID, err) } - return err + return nil } func resourceVPCDHCPOptionsAssociationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { diff --git a/internal/service/ec2/vpc_dhcp_options_data_source.go b/internal/service/ec2/vpc_dhcp_options_data_source.go index 3d18827f4a2..e9e61bae0a5 100644 --- a/internal/service/ec2/vpc_dhcp_options_data_source.go +++ b/internal/service/ec2/vpc_dhcp_options_data_source.go @@ -105,7 +105,7 @@ func dataSourceVPCDHCPOptionsRead(d *schema.ResourceData, meta interface{}) erro err = optionsMap.dhcpConfigurationsToResourceData(opts.DhcpConfigurations, d) if err != nil { - return err + return fmt.Errorf("reading EC2 DHCP Options: %w", err) } if err := d.Set("tags", KeyValueTags(opts.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { diff --git a/internal/service/ec2/vpc_endpoint.go b/internal/service/ec2/vpc_endpoint.go index 7f56f1a86d9..a88fda62612 100644 --- a/internal/service/ec2/vpc_endpoint.go +++ b/internal/service/ec2/vpc_endpoint.go @@ -232,12 +232,12 @@ func resourceVPCEndpointCreate(d *schema.ResourceData, meta interface{}) error { if d.Get("auto_accept").(bool) && aws.StringValue(vpce.State) == vpcEndpointStatePendingAcceptance { if err := vpcEndpointAccept(conn, d.Id(), aws.StringValue(vpce.ServiceName), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("creating EC2 VPC Endpoint (%s): %w", serviceName, err) } } if _, err = WaitVPCEndpointAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("waiting for EC2 VPC Endpoint (%s) create: %w", d.Id(), err) + return fmt.Errorf("creating EC2 VPC Endpoint (%s): waiting for completion: %w", serviceName, err) } return resourceVPCEndpointRead(d, meta) @@ -342,7 +342,7 @@ func resourceVPCEndpointUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("auto_accept") && d.Get("auto_accept").(bool) && d.Get("state").(string) == vpcEndpointStatePendingAcceptance { if err := vpcEndpointAccept(conn, d.Id(), d.Get("service_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating EC2 VPC Endpoint (%s): %w", d.Get("service_name").(string), err) } } diff --git a/internal/service/ec2/vpc_endpoint_connection_accepter.go b/internal/service/ec2/vpc_endpoint_connection_accepter.go index 5794ed5b99c..5533bf2f7e9 100644 --- a/internal/service/ec2/vpc_endpoint_connection_accepter.go +++ b/internal/service/ec2/vpc_endpoint_connection_accepter.go @@ -77,7 +77,7 @@ func resourceVPCEndpointConnectionAccepterRead(d *schema.ResourceData, meta inte serviceID, vpcEndpointID, err := VPCEndpointConnectionAccepterParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading VPC Endpoint Connection (%s): %w", d.Id(), err) } vpcEndpointConnection, err := FindVPCEndpointConnectionByServiceIDAndVPCEndpointID(conn, serviceID, vpcEndpointID) @@ -89,7 +89,7 @@ func resourceVPCEndpointConnectionAccepterRead(d *schema.ResourceData, meta inte } if err != nil { - return fmt.Errorf("error reading VPC Endpoint Connection (%s): %w", d.Id(), err) + return fmt.Errorf("reading VPC Endpoint Connection (%s): %w", d.Id(), err) } d.Set("vpc_endpoint_id", vpcEndpointConnection.VpcEndpointId) @@ -105,7 +105,7 @@ func resourceVPCEndpointConnectionAccepterDelete(d *schema.ResourceData, meta in serviceID, vpcEndpointID, err := VPCEndpointConnectionAccepterParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting VPC Endpoint Connection (%s): %w", d.Id(), err) } input := &ec2.RejectVpcEndpointConnectionsInput{ @@ -120,7 +120,7 @@ func resourceVPCEndpointConnectionAccepterDelete(d *schema.ResourceData, meta in } if err != nil { - return fmt.Errorf("error rejecting VPC Endpoint Connection (%s): %w", d.Id(), err) + return fmt.Errorf("rejecting VPC Endpoint Connection (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_endpoint_security_group_association.go b/internal/service/ec2/vpc_endpoint_security_group_association.go index 4ebc9487079..78fa0d72ab6 100644 --- a/internal/service/ec2/vpc_endpoint_security_group_association.go +++ b/internal/service/ec2/vpc_endpoint_security_group_association.go @@ -86,7 +86,7 @@ func resourceVPCEndpointSecurityGroupAssociationCreate(d *schema.ResourceData, m err := createVPCEndpointSecurityGroupAssociation(conn, vpcEndpointID, securityGroupID) if err != nil { - return err + return err // nosemgrep:bare-error-returns } d.SetId(VPCEndpointSecurityGroupAssociationCreateID(vpcEndpointID, securityGroupID)) @@ -94,7 +94,7 @@ func resourceVPCEndpointSecurityGroupAssociationCreate(d *schema.ResourceData, m if replaceDefaultAssociation { // Delete the existing VPC endpoint/default security group association. if err := deleteVPCEndpointSecurityGroupAssociation(conn, vpcEndpointID, defaultSecurityGroupID); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -150,7 +150,7 @@ func resourceVPCEndpointSecurityGroupAssociationDelete(d *schema.ResourceData, m err = createVPCEndpointSecurityGroupAssociation(conn, vpcEndpointID, aws.StringValue(defaultSecurityGroup.GroupId)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -168,7 +168,7 @@ func createVPCEndpointSecurityGroupAssociation(conn *ec2.EC2, vpcEndpointID, sec _, err := conn.ModifyVpcEndpoint(input) if err != nil { - return fmt.Errorf("error creating VPC Endpoint (%s) Security Group (%s) Association: %w", vpcEndpointID, securityGroupID, err) + return fmt.Errorf("creating VPC Endpoint (%s) Security Group (%s) Association: %w", vpcEndpointID, securityGroupID, err) } return nil @@ -189,7 +189,7 @@ func deleteVPCEndpointSecurityGroupAssociation(conn *ec2.EC2, vpcEndpointID, sec } if err != nil { - return fmt.Errorf("error deleting VPC Endpoint (%s) Security Group (%s) Association: %w", vpcEndpointID, securityGroupID, err) + return fmt.Errorf("deleting VPC Endpoint (%s) Security Group (%s) Association: %w", vpcEndpointID, securityGroupID, err) } return nil diff --git a/internal/service/ec2/vpc_internet_gateway.go b/internal/service/ec2/vpc_internet_gateway.go index 1ccf5858cdd..71be2647965 100644 --- a/internal/service/ec2/vpc_internet_gateway.go +++ b/internal/service/ec2/vpc_internet_gateway.go @@ -68,14 +68,14 @@ func resourceInternetGatewayCreate(d *schema.ResourceData, meta interface{}) err output, err := conn.CreateInternetGateway(input) if err != nil { - return fmt.Errorf("error creating EC2 Internet Gateway: %w", err) + return fmt.Errorf("creating EC2 Internet Gateway: %w", err) } d.SetId(aws.StringValue(output.InternetGateway.InternetGatewayId)) if v, ok := d.GetOk("vpc_id"); ok { if err := attachInternetGateway(conn, d.Id(), v.(string), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("creating EC2 Internet Gateway: %w", err) } } @@ -142,13 +142,13 @@ func resourceInternetGatewayUpdate(d *schema.ResourceData, meta interface{}) err if v := o.(string); v != "" { if err := detachInternetGateway(conn, d.Id(), v, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating EC2 Internet Gateway (%s): %w", d.Id(), err) } } if v := n.(string); v != "" { if err := attachInternetGateway(conn, d.Id(), v, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return fmt.Errorf("updating EC2 Internet Gateway (%s): %w", d.Id(), err) } } } @@ -157,7 +157,7 @@ func resourceInternetGatewayUpdate(d *schema.ResourceData, meta interface{}) err o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 Internet Gateway (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Internet Gateway (%s) tags: %w", d.Id(), err) } } @@ -170,7 +170,7 @@ func resourceInternetGatewayDelete(d *schema.ResourceData, meta interface{}) err // Detach if it is attached. if v, ok := d.GetOk("vpc_id"); ok { if err := detachInternetGateway(conn, d.Id(), v.(string), d.Timeout(schema.TimeoutDelete)); err != nil { - return err + return fmt.Errorf("deleting EC2 Internet Gateway (%s): %w", d.Id(), err) } } @@ -188,7 +188,7 @@ func resourceInternetGatewayDelete(d *schema.ResourceData, meta interface{}) err } if err != nil { - return fmt.Errorf("error deleting EC2 Internet Gateway (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Internet Gateway (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_internet_gateway_attachment.go b/internal/service/ec2/vpc_internet_gateway_attachment.go index c37dc1411c1..121552a967c 100644 --- a/internal/service/ec2/vpc_internet_gateway_attachment.go +++ b/internal/service/ec2/vpc_internet_gateway_attachment.go @@ -49,7 +49,7 @@ func resourceInternetGatewayAttachmentCreate(d *schema.ResourceData, meta interf vpcID := d.Get("vpc_id").(string) if err := attachInternetGateway(conn, igwID, vpcID, d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("creating EC2 Internet Gateway Attachment: %w", err) } d.SetId(InternetGatewayAttachmentCreateResourceID(igwID, vpcID)) @@ -63,7 +63,7 @@ func resourceInternetGatewayAttachmentRead(d *schema.ResourceData, meta interfac igwID, vpcID, err := InternetGatewayAttachmentParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Internet Gateway Attachment (%s): %w", d.Id(), err) } outputRaw, err := tfresource.RetryWhenNewResourceNotFound(propagationTimeout, func() (interface{}, error) { @@ -77,7 +77,7 @@ func resourceInternetGatewayAttachmentRead(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error reading EC2 Internet Gateway Attachment (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Internet Gateway Attachment (%s): %w", d.Id(), err) } igw := outputRaw.(*ec2.InternetGatewayAttachment) @@ -92,13 +92,12 @@ func resourceInternetGatewayAttachmentDelete(d *schema.ResourceData, meta interf conn := meta.(*conns.AWSClient).EC2Conn() igwID, vpcID, err := InternetGatewayAttachmentParseResourceID(d.Id()) - if err != nil { - return err + return fmt.Errorf("deleting EC2 Internet Gateway Attachment (%s): %w", d.Id(), err) } if err := detachInternetGateway(conn, igwID, vpcID, d.Timeout(schema.TimeoutDelete)); err != nil { - return err + return fmt.Errorf("deleting EC2 Internet Gateway Attachment (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_network_acl.go b/internal/service/ec2/vpc_network_acl.go index a396c1e1213..cfccd6fb37a 100644 --- a/internal/service/ec2/vpc_network_acl.go +++ b/internal/service/ec2/vpc_network_acl.go @@ -161,13 +161,13 @@ func resourceNetworkACLCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateNetworkAcl(input) if err != nil { - return fmt.Errorf("error creating EC2 Network ACL: %w", err) + return fmt.Errorf("creating EC2 Network ACL: %w", err) } d.SetId(aws.StringValue(output.NetworkAcl.NetworkAclId)) if err := modifyNetworkACLAttributesOnCreate(conn, d); err != nil { - return err + return fmt.Errorf("creating EC2 Network ACL: %w", err) } return resourceNetworkACLRead(d, meta) @@ -189,7 +189,7 @@ func resourceNetworkACLRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading EC2 Network ACL (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Network ACL (%s): %w", d.Id(), err) } nacl := outputRaw.(*ec2.NetworkAcl) @@ -229,21 +229,21 @@ func resourceNetworkACLRead(d *schema.ResourceData, meta interface{}) error { } } if err := d.Set("egress", flattenNetworkACLEntries(egressEntries)); err != nil { - return fmt.Errorf("error setting egress: %w", err) + return fmt.Errorf("setting egress: %w", err) } if err := d.Set("ingress", flattenNetworkACLEntries(ingressEntries)); err != nil { - return fmt.Errorf("error setting ingress: %w", err) + return fmt.Errorf("setting ingress: %w", err) } tags := KeyValueTags(nacl.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -253,7 +253,7 @@ func resourceNetworkACLUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).EC2Conn() if err := modifyNetworkACLAttributesOnUpdate(conn, d, true); err != nil { - return err + return fmt.Errorf("updating EC2 Network ACL (%s): %w", d.Id(), err) } return resourceNetworkACLRead(d, meta) @@ -266,7 +266,7 @@ func resourceNetworkACLDelete(d *schema.ResourceData, meta interface{}) error { nacl, err := FindNetworkACLByID(conn, d.Id()) if err != nil { - return fmt.Errorf("error reading EC2 Network ACL (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Network ACL (%s): %w", d.Id(), err) } var subnetIDs []interface{} @@ -275,7 +275,7 @@ func resourceNetworkACLDelete(d *schema.ResourceData, meta interface{}) error { } if len(subnetIDs) > 0 { if err := networkACLAssociationsDelete(conn, d.Get("vpc_id").(string), subnetIDs); err != nil { - return err + return fmt.Errorf("deleting EC2 Network ACL (%s): %w", d.Id(), err) } } @@ -293,7 +293,7 @@ func resourceNetworkACLDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting EC2 Network ACL (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Network ACL (%s): %w", d.Id(), err) } return nil @@ -369,7 +369,7 @@ func modifyNetworkACLAttributesOnUpdate(conn *ec2.EC2, d *schema.ResourceData, d o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 Network ACL (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Network ACL (%s) tags: %w", d.Id(), err) } } @@ -440,7 +440,7 @@ func createNetworkACLEntries(conn *ec2.EC2, naclID string, tfList []interface{}, _, err := conn.CreateNetworkAclEntry(input) if err != nil { - return fmt.Errorf("error creating EC2 Network ACL (%s) Entry: %w", naclID, err) + return fmt.Errorf("creating EC2 Network ACL (%s) Entry: %w", naclID, err) } } @@ -475,7 +475,7 @@ func deleteNetworkACLEntries(conn *ec2.EC2, naclID string, naclEntries []*ec2.Ne _, err := conn.DeleteNetworkAclEntry(input) if err != nil { - return fmt.Errorf("error deleting EC2 Network ACL (%s) Entry: %w", naclID, err) + return fmt.Errorf("deleting EC2 Network ACL (%s) Entry: %w", naclID, err) } } diff --git a/internal/service/ec2/vpc_network_acl_association.go b/internal/service/ec2/vpc_network_acl_association.go index dff08045b4d..1e8d9b96d25 100644 --- a/internal/service/ec2/vpc_network_acl_association.go +++ b/internal/service/ec2/vpc_network_acl_association.go @@ -42,7 +42,7 @@ func resourceNetworkACLAssociationCreate(d *schema.ResourceData, meta interface{ associationID, err := networkACLAssociationCreate(conn, d.Get("network_acl_id").(string), d.Get("subnet_id").(string)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } d.SetId(associationID) @@ -62,7 +62,7 @@ func resourceNetworkACLAssociationRead(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error reading EC2 Network ACL Association (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Network ACL Association (%s): %w", d.Id(), err) } d.Set("network_acl_id", association.NetworkAclId) @@ -83,18 +83,18 @@ func resourceNetworkACLAssociationDelete(d *schema.ResourceData, meta interface{ nacl, err := FindNetworkACL(conn, input) if err != nil { - return fmt.Errorf("error reading EC2 Network ACL for Association (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Network ACL for Association (%s): %w", d.Id(), err) } vpcID := aws.StringValue(nacl.VpcId) defaultNACL, err := FindVPCDefaultNetworkACL(conn, vpcID) if err != nil { - return fmt.Errorf("error reading EC2 VPC (%s) default NACL: %w", vpcID, err) + return fmt.Errorf("reading EC2 VPC (%s) default NACL: %w", vpcID, err) } if err := networkACLAssociationDelete(conn, d.Id(), aws.StringValue(defaultNACL.NetworkAclId)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return nil @@ -106,7 +106,7 @@ func networkACLAssociationCreate(conn *ec2.EC2, naclID, subnetID string) (string association, err := FindNetworkACLAssociationBySubnetID(conn, subnetID) if err != nil { - return "", fmt.Errorf("error reading EC2 Network ACL Association for EC2 Subnet (%s): %w", subnetID, err) + return "", fmt.Errorf("reading EC2 Network ACL Association for EC2 Subnet (%s): %w", subnetID, err) } input := &ec2.ReplaceNetworkAclAssociationInput{ @@ -120,7 +120,7 @@ func networkACLAssociationCreate(conn *ec2.EC2, naclID, subnetID string) (string }, errCodeInvalidAssociationIDNotFound) if err != nil { - return "", fmt.Errorf("error creating EC2 Network ACL (%s) Association: %w", naclID, err) + return "", fmt.Errorf("creating EC2 Network ACL (%s) Association: %w", naclID, err) } return aws.StringValue(outputRaw.(*ec2.ReplaceNetworkAclAssociationOutput).NewAssociationId), nil @@ -161,7 +161,7 @@ func networkACLAssociationDelete(conn *ec2.EC2, associationID, naclID string) er } if err != nil { - return fmt.Errorf("error deleting EC2 Network ACL Association (%s): %w", associationID, err) + return fmt.Errorf("deleting EC2 Network ACL Association (%s): %w", associationID, err) } return nil @@ -173,7 +173,7 @@ func networkACLAssociationsDelete(conn *ec2.EC2, vpcID string, subnetIDs []inter defaultNACL, err := FindVPCDefaultNetworkACL(conn, vpcID) if err != nil { - return fmt.Errorf("error reading EC2 VPC (%s) default NACL: %w", vpcID, err) + return fmt.Errorf("reading EC2 VPC (%s) default NACL: %w", vpcID, err) } for _, v := range subnetIDs { @@ -186,7 +186,7 @@ func networkACLAssociationsDelete(conn *ec2.EC2, vpcID string, subnetIDs []inter } if err != nil { - return fmt.Errorf("error reading EC2 Network ACL Association for EC2 Subnet (%s): %w", subnetID, err) + return fmt.Errorf("reading EC2 Network ACL Association for EC2 Subnet (%s): %w", subnetID, err) } if err := networkACLAssociationDelete(conn, aws.StringValue(association.NetworkAclAssociationId), aws.StringValue(defaultNACL.NetworkAclId)); err != nil { diff --git a/internal/service/ec2/vpc_network_acl_rule.go b/internal/service/ec2/vpc_network_acl_rule.go index c4c0a948f06..c7f3b28c881 100644 --- a/internal/service/ec2/vpc_network_acl_rule.go +++ b/internal/service/ec2/vpc_network_acl_rule.go @@ -120,7 +120,7 @@ func resourceNetworkACLRuleCreate(d *schema.ResourceData, meta interface{}) erro protocolNumber, err := networkACLProtocolNumber(protocol) if err != nil { - return err + return fmt.Errorf("creating EC2 Network ACL Rule: %w", err) } egress := d.Get("egress").(bool) @@ -160,7 +160,7 @@ func resourceNetworkACLRuleCreate(d *schema.ResourceData, meta interface{}) erro _, err = conn.CreateNetworkAclEntry(input) if err != nil { - return fmt.Errorf("error creating EC2 Network ACL (%s) Rule (egress:%t)(%d): %w", naclID, egress, ruleNumber, err) + return fmt.Errorf("creating EC2 Network ACL (%s) Rule (egress: %t)(%d): %w", naclID, egress, ruleNumber, err) } d.SetId(NetworkACLRuleCreateResourceID(naclID, ruleNumber, egress, protocol)) @@ -186,7 +186,7 @@ func resourceNetworkACLRuleRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading EC2 Network ACL Rule (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Network ACL Rule (%s): %w", d.Id(), err) } naclEntry := outputRaw.(*ec2.NetworkAclEntry) @@ -211,7 +211,7 @@ func resourceNetworkACLRuleRead(d *schema.ResourceData, meta interface{}) error protocolNumber, err := networkACLProtocolNumber(v) if err != nil { - return err + return fmt.Errorf("reading EC2 Network ACL Rule (%s): %w", d.Id(), err) } d.Set("protocol", strconv.Itoa(protocolNumber)) @@ -237,7 +237,7 @@ func resourceNetworkACLRuleDelete(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("error deleting EC2 Network ACL Rule (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Network ACL Rule (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_network_interface.go b/internal/service/ec2/vpc_network_interface.go index 7ec1f5a5495..71a3a70a7ae 100644 --- a/internal/service/ec2/vpc_network_interface.go +++ b/internal/service/ec2/vpc_network_interface.go @@ -471,7 +471,7 @@ func resourceNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) er _, err := attachNetworkInterface(conn, d.Id(), attachment["instance"].(string), attachment["device_index"].(int), networkInterfaceAttachedTimeout) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -577,7 +577,7 @@ func resourceNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) er err := DetachNetworkInterface(conn, d.Id(), attachment["attachment_id"].(string), NetworkInterfaceDetachedTimeout) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -587,7 +587,7 @@ func resourceNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) er _, err := attachNetworkInterface(conn, d.Id(), attachment["instance"].(string), attachment["device_index"].(int), networkInterfaceAttachedTimeout) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -1055,7 +1055,7 @@ func resourceNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) er err := DetachNetworkInterface(conn, d.Id(), attachment["attachment_id"].(string), NetworkInterfaceDetachedTimeout) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -1080,7 +1080,7 @@ func attachNetworkInterface(conn *ec2.EC2, networkInterfaceID, instanceID string _, err = WaitNetworkInterfaceAttached(context.TODO(), conn, attachmentID, timeout) if err != nil { - return attachmentID, fmt.Errorf("waiting for EC2 Network Interface (%s/%s) attach: %w", networkInterfaceID, attachmentID, err) + return "", fmt.Errorf("attaching EC2 Network Interface (%s/%s): waiting for completion: %w", networkInterfaceID, instanceID, err) } return attachmentID, nil @@ -1133,7 +1133,7 @@ func DetachNetworkInterfaceWithContext(ctx context.Context, conn *ec2.EC2, netwo } if err != nil { - return fmt.Errorf("waiting for EC2 Network Interface (%s/%s) detach: %w", networkInterfaceID, attachmentID, err) + return fmt.Errorf("detaching EC2 Network Interface (%s/%s): waiting for completion: %w", networkInterfaceID, attachmentID, err) } return nil diff --git a/internal/service/ec2/vpc_network_interface_attachment.go b/internal/service/ec2/vpc_network_interface_attachment.go index 68e704d9076..40ef02e17a0 100644 --- a/internal/service/ec2/vpc_network_interface_attachment.go +++ b/internal/service/ec2/vpc_network_interface_attachment.go @@ -58,12 +58,12 @@ func resourceNetworkInterfaceAttachmentCreate(d *schema.ResourceData, meta inter networkInterfaceAttachedTimeout, ) - if attachmentID != "" { - d.SetId(attachmentID) + if err != nil { + return err // nosemgrep:bare-error-returns } - if err != nil { - return err + if attachmentID != "" { + d.SetId(attachmentID) } return resourceNetworkInterfaceAttachmentRead(d, meta) diff --git a/internal/service/ec2/vpc_peering_connection.go b/internal/service/ec2/vpc_peering_connection.go index c95324efc11..53d5909af70 100644 --- a/internal/service/ec2/vpc_peering_connection.go +++ b/internal/service/ec2/vpc_peering_connection.go @@ -150,12 +150,12 @@ func resourceVPCPeeringConnectionCreate(d *schema.ResourceData, meta interface{} vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceVPCPeeringConnectionRead(d, meta) @@ -236,13 +236,13 @@ func resourceVPCPeeringConnectionUpdate(d *schema.ResourceData, meta interface{} vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChanges("accepter", "requester") { if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -292,14 +292,14 @@ func acceptVPCPeeringConnection(conn *ec2.EC2, vpcPeeringConnectionID string, ti }) if err != nil { - return nil, fmt.Errorf("error accepting EC2 VPC Peering Connection (%s): %w", vpcPeeringConnectionID, err) + return nil, fmt.Errorf("accepting EC2 VPC Peering Connection (%s): %w", vpcPeeringConnectionID, err) } // "OperationNotPermitted: Peering pcx-0000000000000000 is not active. Peering options can be added only to active peerings." vpcPeeringConnection, err := WaitVPCPeeringConnectionActive(conn, vpcPeeringConnectionID, timeout) if err != nil { - return nil, fmt.Errorf("error waiting for EC2 VPC Peering Connection (%s) update: %w", vpcPeeringConnectionID, err) + return nil, fmt.Errorf("accepting EC2 VPC Peering Connection (%s): waiting for completion: %w", vpcPeeringConnectionID, err) } return vpcPeeringConnection, nil @@ -344,7 +344,7 @@ func modifyVPCPeeringConnectionOptions(conn *ec2.EC2, d *schema.ResourceData, vp log.Printf("[DEBUG] Modifying VPC Peering Connection Options: %s", input) if _, err := conn.ModifyVpcPeeringConnectionOptions(input); err != nil { - return fmt.Errorf("error modifying EC2 VPC Peering Connection (%s) Options: %w", d.Id(), err) + return fmt.Errorf("modifying EC2 VPC Peering Connection (%s) Options: %w", d.Id(), err) } // Retry reading back the modified options to deal with eventual consistency. @@ -372,7 +372,7 @@ func modifyVPCPeeringConnectionOptions(conn *ec2.EC2, d *schema.ResourceData, vp }) if err != nil { - return fmt.Errorf("error waiting for EC2 VPC Peering Connection (%s) Options update: %w", d.Id(), err) + return fmt.Errorf("modifying EC2 VPC Peering Connection (%s) Options: waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpc_peering_connection_accepter.go b/internal/service/ec2/vpc_peering_connection_accepter.go index 2ae62ab510a..e61778376f4 100644 --- a/internal/service/ec2/vpc_peering_connection_accepter.go +++ b/internal/service/ec2/vpc_peering_connection_accepter.go @@ -103,12 +103,12 @@ func resourceVPCPeeringAccepterCreate(d *schema.ResourceData, meta interface{}) vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil { - return err + return err // nosemgrep:bare-error-returns } if len(tags) > 0 { diff --git a/internal/service/ec2/vpc_peering_connection_options.go b/internal/service/ec2/vpc_peering_connection_options.go index 6bce4c24bc2..5b1273f9f65 100644 --- a/internal/service/ec2/vpc_peering_connection_options.go +++ b/internal/service/ec2/vpc_peering_connection_options.go @@ -49,7 +49,7 @@ func resourceVPCPeeringConnectionOptionsCreate(d *schema.ResourceData, meta inte d.SetId(vpcPeeringConnectionID) if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, false); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceVPCPeeringConnectionOptionsRead(d, meta) @@ -101,7 +101,7 @@ func resourceVPCPeeringConnectionOptionsUpdate(d *schema.ResourceData, meta inte } if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, false); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceVPCPeeringConnectionOptionsRead(d, meta) diff --git a/internal/service/ec2/vpc_route_table.go b/internal/service/ec2/vpc_route_table.go index 23458da8850..16f63ba1fe7 100644 --- a/internal/service/ec2/vpc_route_table.go +++ b/internal/service/ec2/vpc_route_table.go @@ -180,13 +180,13 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateRouteTable(input) if err != nil { - return fmt.Errorf("error creating Route Table: %w", err) + return fmt.Errorf("creating Route Table: %w", err) } d.SetId(aws.StringValue(output.RouteTable.RouteTableId)) if _, err := WaitRouteTableReady(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return fmt.Errorf("error waiting for Route Table (%s) to become available: %w", d.Id(), err) + return fmt.Errorf("waiting for Route Table (%s) to become available: %w", d.Id(), err) } if v, ok := d.GetOk("propagating_vgws"); ok && v.(*schema.Set).Len() > 0 { @@ -194,7 +194,7 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { v := v.(string) if err := routeTableEnableVGWRoutePropagation(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -204,7 +204,7 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { v := v.(map[string]interface{}) if err := routeTableAddRoute(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -226,7 +226,7 @@ func resourceRouteTableRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Route Table (%s): %w", d.Id(), err) + return fmt.Errorf("reading Route Table (%s): %w", d.Id(), err) } d.Set("vpc_id", routeTable.VpcId) @@ -236,11 +236,11 @@ func resourceRouteTableRead(d *schema.ResourceData, meta interface{}) error { propagatingVGWs = append(propagatingVGWs, aws.StringValue(v.GatewayId)) } if err := d.Set("propagating_vgws", propagatingVGWs); err != nil { - return fmt.Errorf("error setting propagating_vgws: %w", err) + return fmt.Errorf("setting propagating_vgws: %w", err) } if err := d.Set("route", flattenRoutes(conn, routeTable.Routes)); err != nil { - return fmt.Errorf("error setting route: %w", err) + return fmt.Errorf("setting route: %w", err) } //Ignore the AmazonFSx service tag in addition to standard ignores @@ -248,11 +248,11 @@ func resourceRouteTableRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } ownerID := aws.StringValue(routeTable.OwnerId) @@ -283,7 +283,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { v := v.(string) if err := routeTableDisableVGWRoutePropagation(conn, d.Id(), v); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -291,7 +291,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { v := v.(string) if err := routeTableEnableVGWRoutePropagation(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -318,7 +318,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { if oldTarget != newTarget { if err := routeTableUpdateRoute(conn, d.Id(), vNew, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -326,7 +326,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { if addRoute { if err := routeTableAddRoute(conn, d.Id(), vNew, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -350,7 +350,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { if delRoute { if err := routeTableDeleteRoute(conn, d.Id(), vOld, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -360,7 +360,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 Route Table (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Route Table (%s) tags: %w", d.Id(), err) } } @@ -373,7 +373,7 @@ func resourceRouteTableDelete(d *schema.ResourceData, meta interface{}) error { routeTable, err := FindRouteTableByID(conn, d.Id()) if err != nil { - return fmt.Errorf("error reading Route Table (%s): %w", d.Id(), err) + return fmt.Errorf("reading Route Table (%s): %w", d.Id(), err) } // Do all the disassociations @@ -381,7 +381,7 @@ func resourceRouteTableDelete(d *schema.ResourceData, meta interface{}) error { v := aws.StringValue(v.RouteTableAssociationId) if err := routeTableAssociationDelete(conn, v); err != nil { - return err + return fmt.Errorf("deleting Route Table (%s): %w", d.Id(), err) } } @@ -395,13 +395,13 @@ func resourceRouteTableDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting Route Table (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Route Table (%s): %w", d.Id(), err) } // Wait for the route table to really destroy log.Printf("[DEBUG] Waiting for route table (%s) deletion", d.Id()) if _, err := WaitRouteTableDeleted(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for Route Table (%s) deletion: %w", d.Id(), err) + return fmt.Errorf("waiting for Route Table (%s) deletion: %w", d.Id(), err) } return nil @@ -480,10 +480,10 @@ func resourceRouteTableHash(v interface{}) int { // routeTableAddRoute adds a route to the specified route table. func routeTableAddRoute(conn *ec2.EC2, routeTableID string, tfMap map[string]interface{}, timeout time.Duration) error { if err := validNestedExactlyOneOf(tfMap, routeTableValidDestinations); err != nil { - return fmt.Errorf("error creating route: %w", err) + return fmt.Errorf("creating route: %w", err) } if err := validNestedExactlyOneOf(tfMap, routeTableValidTargets); err != nil { - return fmt.Errorf("error creating route: %w", err) + return fmt.Errorf("creating route: %w", err) } destinationAttributeKey, destination := routeTableRouteDestinationAttribute(tfMap) @@ -498,7 +498,7 @@ func routeTableAddRoute(conn *ec2.EC2, routeTableID string, tfMap map[string]int case "destination_prefix_list_id": routeFinder = FindRouteByPrefixListIDDestination default: - return fmt.Errorf("error creating Route: unexpected route destination attribute: %q", destinationAttributeKey) + return fmt.Errorf("creating Route: unexpected route destination attribute: %q", destinationAttributeKey) } input := expandCreateRouteInput(tfMap) @@ -520,13 +520,13 @@ func routeTableAddRoute(conn *ec2.EC2, routeTableID string, tfMap map[string]int ) if err != nil { - return fmt.Errorf("error creating Route in Route Table (%s) with destination (%s): %w", routeTableID, destination, err) + return fmt.Errorf("creating Route in Route Table (%s) with destination (%s): %w", routeTableID, destination, err) } _, err = WaitRouteReady(conn, routeFinder, routeTableID, destination, timeout) if err != nil { - return fmt.Errorf("error waiting for Route in Route Table (%s) with destination (%s) to become available: %w", routeTableID, destination, err) + return fmt.Errorf("waiting for Route in Route Table (%s) with destination (%s) to become available: %w", routeTableID, destination, err) } return nil @@ -553,7 +553,7 @@ func routeTableDeleteRoute(conn *ec2.EC2, routeTableID string, tfMap map[string] input.DestinationPrefixListId = destination routeFinder = FindRouteByPrefixListIDDestination default: - return fmt.Errorf("error deleting Route: unexpected route destination attribute: %q", destinationAttributeKey) + return fmt.Errorf("deleting Route: unexpected route destination attribute: %q", destinationAttributeKey) } log.Printf("[DEBUG] Deleting Route: %s", input) @@ -564,13 +564,13 @@ func routeTableDeleteRoute(conn *ec2.EC2, routeTableID string, tfMap map[string] } if err != nil { - return fmt.Errorf("error deleting Route in Route Table (%s) with destination (%s): %w", routeTableID, destination, err) + return fmt.Errorf("deleting Route in Route Table (%s) with destination (%s): %w", routeTableID, destination, err) } _, err = WaitRouteDeleted(conn, routeFinder, routeTableID, destination, timeout) if err != nil { - return fmt.Errorf("error waiting for Route in Route Table (%s) with destination (%s) to delete: %w", routeTableID, destination, err) + return fmt.Errorf("waiting for Route in Route Table (%s) with destination (%s) to delete: %w", routeTableID, destination, err) } return nil @@ -579,10 +579,10 @@ func routeTableDeleteRoute(conn *ec2.EC2, routeTableID string, tfMap map[string] // routeTableUpdateRoute updates a route in the specified route table. func routeTableUpdateRoute(conn *ec2.EC2, routeTableID string, tfMap map[string]interface{}, timeout time.Duration) error { if err := validNestedExactlyOneOf(tfMap, routeTableValidDestinations); err != nil { - return fmt.Errorf("error updating route: %w", err) + return fmt.Errorf("updating route: %w", err) } if err := validNestedExactlyOneOf(tfMap, routeTableValidTargets); err != nil { - return fmt.Errorf("error updating route: %w", err) + return fmt.Errorf("updating route: %w", err) } destinationAttributeKey, destination := routeTableRouteDestinationAttribute(tfMap) @@ -597,7 +597,7 @@ func routeTableUpdateRoute(conn *ec2.EC2, routeTableID string, tfMap map[string] case "destination_prefix_list_id": routeFinder = FindRouteByPrefixListIDDestination default: - return fmt.Errorf("error creating Route: unexpected route destination attribute: %q", destinationAttributeKey) + return fmt.Errorf("creating Route: unexpected route destination attribute: %q", destinationAttributeKey) } input := expandReplaceRouteInput(tfMap) @@ -612,13 +612,13 @@ func routeTableUpdateRoute(conn *ec2.EC2, routeTableID string, tfMap map[string] _, err := conn.ReplaceRoute(input) if err != nil { - return fmt.Errorf("error updating Route in Route Table (%s) with destination (%s): %w", routeTableID, destination, err) + return fmt.Errorf("updating Route in Route Table (%s) with destination (%s): %w", routeTableID, destination, err) } _, err = WaitRouteReady(conn, routeFinder, routeTableID, destination, timeout) if err != nil { - return fmt.Errorf("error waiting for Route in Route Table (%s) with destination (%s) to become available: %w", routeTableID, destination, err) + return fmt.Errorf("waiting for Route in Route Table (%s) with destination (%s) to become available: %w", routeTableID, destination, err) } return nil @@ -636,7 +636,7 @@ func routeTableDisableVGWRoutePropagation(conn *ec2.EC2, routeTableID, gatewayID _, err := conn.DisableVgwRoutePropagation(input) if err != nil { - return fmt.Errorf("error disabling Route Table (%s) VPN Gateway (%s) route propagation: %w", routeTableID, gatewayID, err) + return fmt.Errorf("disabling Route Table (%s) VPN Gateway (%s) route propagation: %w", routeTableID, gatewayID, err) } return nil @@ -661,7 +661,7 @@ func routeTableEnableVGWRoutePropagation(conn *ec2.EC2, routeTableID, gatewayID ) if err != nil { - return fmt.Errorf("error enabling Route Table (%s) VPN Gateway (%s) route propagation: %w", routeTableID, gatewayID, err) + return fmt.Errorf("enabling Route Table (%s) VPN Gateway (%s) route propagation: %w", routeTableID, gatewayID, err) } return nil diff --git a/internal/service/ec2/vpc_route_table_association.go b/internal/service/ec2/vpc_route_table_association.go index a5e8897c56f..88ade987b67 100644 --- a/internal/service/ec2/vpc_route_table_association.go +++ b/internal/service/ec2/vpc_route_table_association.go @@ -210,12 +210,12 @@ func routeTableAssociationDelete(conn *ec2.EC2, associationID string) error { } if err != nil { - return fmt.Errorf("error deleting Route Table Association (%s): %w", associationID, err) + return fmt.Errorf("deleting Route Table Association (%s): %w", associationID, err) } log.Printf("[DEBUG] Waiting for Route Table Association (%s) deletion", associationID) if _, err := WaitRouteTableAssociationDeleted(conn, associationID); err != nil { - return fmt.Errorf("error waiting for Route Table Association (%s) delete: %w", associationID, err) + return fmt.Errorf("deleting Route Table Association (%s): waiting for completion: %w", associationID, err) } return nil diff --git a/internal/service/ec2/vpc_route_table_data_source.go b/internal/service/ec2/vpc_route_table_data_source.go index 5a4bb15c376..d441ae28fdc 100644 --- a/internal/service/ec2/vpc_route_table_data_source.go +++ b/internal/service/ec2/vpc_route_table_data_source.go @@ -205,10 +205,9 @@ func dataSourceRouteTableRead(d *schema.ResourceData, meta interface{}) error { filter.(*schema.Set), )...) - log.Printf("[DEBUG] Reading Route Table: %s", req) resp, err := conn.DescribeRouteTables(req) if err != nil { - return err + return fmt.Errorf("reading EC2 VPC Route Table: %w", err) } if resp == nil || len(resp.RouteTables) == 0 { return fmt.Errorf("query returned no results. Please change your search criteria and try again") @@ -241,11 +240,11 @@ func dataSourceRouteTableRead(d *schema.ResourceData, meta interface{}) error { } if err := d.Set("routes", dataSourceRoutesRead(conn, rt.Routes)); err != nil { - return err + return fmt.Errorf("reading EC2 VPC Route Table: %w", err) } if err := d.Set("associations", dataSourceAssociationsRead(rt.Associations)); err != nil { - return err + return fmt.Errorf("reading EC2 VPC Route Table: %w", err) } return nil diff --git a/internal/service/ec2/vpc_subnet.go b/internal/service/ec2/vpc_subnet.go index ee710f77d60..102ee5407ef 100644 --- a/internal/service/ec2/vpc_subnet.go +++ b/internal/service/ec2/vpc_subnet.go @@ -180,7 +180,7 @@ func resourceSubnetCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateSubnet(input) if err != nil { - return fmt.Errorf("error creating EC2 Subnet: %w", err) + return fmt.Errorf("creating EC2 Subnet: %w", err) } d.SetId(aws.StringValue(output.Subnet.SubnetId)) @@ -188,7 +188,7 @@ func resourceSubnetCreate(d *schema.ResourceData, meta interface{}) error { subnet, err := WaitSubnetAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) create: %w", d.Id(), err) + return fmt.Errorf("waiting for EC2 Subnet (%s) create: %w", d.Id(), err) } for i, v := range subnet.Ipv6CidrBlockAssociationSet { @@ -198,7 +198,7 @@ func resourceSubnetCreate(d *schema.ResourceData, meta interface{}) error { subnetCidrBlockState, err := WaitSubnetIPv6CIDRBlockAssociationCreated(conn, associationID) if err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become associated: %w", d.Id(), associationID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become associated: %w", d.Id(), associationID, err) } subnet.Ipv6CidrBlockAssociationSet[i].Ipv6CidrBlockState = subnetCidrBlockState @@ -206,7 +206,7 @@ func resourceSubnetCreate(d *schema.ResourceData, meta interface{}) error { } if err := modifySubnetAttributesOnCreate(conn, d, subnet, false); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceSubnetRead(d, meta) @@ -228,7 +228,7 @@ func resourceSubnetRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading EC2 Subnet (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Subnet (%s): %w", d.Id(), err) } subnet := outputRaw.(*ec2.Subnet) @@ -273,11 +273,11 @@ func resourceSubnetRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -290,7 +290,7 @@ func resourceSubnetUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 Subnet (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 Subnet (%s) tags: %w", d.Id(), err) } } @@ -300,57 +300,57 @@ func resourceSubnetUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChanges("customer_owned_ipv4_pool", "map_customer_owned_ip_on_launch") { if err := modifySubnetOutpostRackAttributes(conn, d.Id(), d.Get("customer_owned_ipv4_pool").(string), d.Get("map_customer_owned_ip_on_launch").(bool)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("enable_dns64") { if err := modifySubnetEnableDNS64(conn, d.Id(), d.Get("enable_dns64").(bool)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("enable_resource_name_dns_aaaa_record_on_launch") { if err := modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(conn, d.Id(), d.Get("enable_resource_name_dns_aaaa_record_on_launch").(bool)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("enable_resource_name_dns_a_record_on_launch") { if err := modifySubnetEnableResourceNameDNSARecordOnLaunch(conn, d.Id(), d.Get("enable_resource_name_dns_a_record_on_launch").(bool)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("map_public_ip_on_launch") { if err := modifySubnetMapPublicIPOnLaunch(conn, d.Id(), d.Get("map_public_ip_on_launch").(bool)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("private_dns_hostname_type_on_launch") { if err := modifySubnetPrivateDNSHostnameTypeOnLaunch(conn, d.Id(), d.Get("private_dns_hostname_type_on_launch").(string)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } // If we're disabling IPv6 assignment for new ENIs, do that before modifying the IPv6 CIDR block. if d.HasChange("assign_ipv6_address_on_creation") && !d.Get("assign_ipv6_address_on_creation").(bool) { if err := modifySubnetAssignIPv6AddressOnCreation(conn, d.Id(), false); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("ipv6_cidr_block") { if err := modifySubnetIPv6CIDRBlockAssociation(conn, d.Id(), d.Get("ipv6_cidr_block_association_id").(string), d.Get("ipv6_cidr_block").(string)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } // If we're enabling IPv6 assignment for new ENIs, do that after modifying the IPv6 CIDR block. if d.HasChange("assign_ipv6_address_on_creation") && d.Get("assign_ipv6_address_on_creation").(bool) { if err := modifySubnetAssignIPv6AddressOnCreation(conn, d.Id(), true); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -479,11 +479,11 @@ func modifySubnetAssignIPv6AddressOnCreation(conn *ec2.EC2, subnetID string, v b } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error setting EC2 Subnet (%s) AssignIpv6AddressOnCreation: %w", subnetID, err) + return fmt.Errorf("setting EC2 Subnet (%s) AssignIpv6AddressOnCreation: %w", subnetID, err) } if _, err := waitSubnetAssignIPv6AddressOnCreationUpdated(conn, subnetID, v); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) AssignIpv6AddressOnCreation update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) AssignIpv6AddressOnCreation update: %w", subnetID, err) } return nil @@ -498,11 +498,11 @@ func modifySubnetEnableDNS64(conn *ec2.EC2, subnetID string, v bool) error { } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 Subnet (%s) EnableDns64: %w", subnetID, err) + return fmt.Errorf("modifying EC2 Subnet (%s) EnableDns64: %w", subnetID, err) } if _, err := waitSubnetEnableDNS64Updated(conn, subnetID, v); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) EnableDns64 update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) EnableDns64 update: %w", subnetID, err) } return nil @@ -517,11 +517,11 @@ func modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(conn *ec2.EC2, subnetID } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 Subnet (%s) EnableResourceNameDnsAAAARecordOnLaunch: %w", subnetID, err) + return fmt.Errorf("modifying EC2 Subnet (%s) EnableResourceNameDnsAAAARecordOnLaunch: %w", subnetID, err) } if _, err := waitSubnetEnableResourceNameDNSAAAARecordOnLaunchUpdated(conn, subnetID, v); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) EnableResourceNameDnsAAAARecordOnLaunch update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) EnableResourceNameDnsAAAARecordOnLaunch update: %w", subnetID, err) } return nil @@ -536,11 +536,11 @@ func modifySubnetEnableResourceNameDNSARecordOnLaunch(conn *ec2.EC2, subnetID st } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 Subnet (%s) EnableResourceNameDnsARecordOnLaunch: %w", subnetID, err) + return fmt.Errorf("modifying EC2 Subnet (%s) EnableResourceNameDnsARecordOnLaunch: %w", subnetID, err) } if _, err := waitSubnetEnableResourceNameDNSARecordOnLaunchUpdated(conn, subnetID, v); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) EnableResourceNameDnsARecordOnLaunch update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) EnableResourceNameDnsARecordOnLaunch update: %w", subnetID, err) } return nil @@ -558,13 +558,13 @@ func modifySubnetIPv6CIDRBlockAssociation(conn *ec2.EC2, subnetID, associationID _, err := conn.DisassociateSubnetCidrBlock(input) if err != nil { - return fmt.Errorf("error disassociating EC2 Subnet (%s) IPv6 CIDR block (%s): %w", subnetID, associationID, err) + return fmt.Errorf("disassociating EC2 Subnet (%s) IPv6 CIDR block (%s): %w", subnetID, associationID, err) } _, err = WaitSubnetIPv6CIDRBlockAssociationDeleted(conn, associationID) if err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become disassociated: %w", subnetID, associationID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become disassociated: %w", subnetID, associationID, err) } } @@ -579,7 +579,7 @@ func modifySubnetIPv6CIDRBlockAssociation(conn *ec2.EC2, subnetID, associationID if err != nil { //The big question here is, do we want to try to reassociate the old one?? //If we have a failure here, then we may be in a situation that we have nothing associated - return fmt.Errorf("error associating EC2 Subnet (%s) IPv6 CIDR block (%s): %w", subnetID, cidrBlock, err) + return fmt.Errorf("associating EC2 Subnet (%s) IPv6 CIDR block (%s): %w", subnetID, cidrBlock, err) } associationID := aws.StringValue(output.Ipv6CidrBlockAssociation.AssociationId) @@ -587,7 +587,7 @@ func modifySubnetIPv6CIDRBlockAssociation(conn *ec2.EC2, subnetID, associationID _, err = WaitSubnetIPv6CIDRBlockAssociationCreated(conn, associationID) if err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become associated: %w", subnetID, associationID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) IPv6 CIDR block (%s) to become associated: %w", subnetID, associationID, err) } } @@ -603,11 +603,11 @@ func modifySubnetMapPublicIPOnLaunch(conn *ec2.EC2, subnetID string, v bool) err } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 Subnet (%s) MapPublicIpOnLaunch: %w", subnetID, err) + return fmt.Errorf("modifying EC2 Subnet (%s) MapPublicIpOnLaunch: %w", subnetID, err) } if _, err := WaitSubnetMapPublicIPOnLaunchUpdated(conn, subnetID, v); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) MapPublicIpOnLaunch update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) MapPublicIpOnLaunch update: %w", subnetID, err) } return nil @@ -626,11 +626,11 @@ func modifySubnetOutpostRackAttributes(conn *ec2.EC2, subnetID string, customerO } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 Subnet (%s) CustomerOwnedIpv4Pool/MapCustomerOwnedIpOnLaunch: %w", subnetID, err) + return fmt.Errorf("modifying EC2 Subnet (%s) CustomerOwnedIpv4Pool/MapCustomerOwnedIpOnLaunch: %w", subnetID, err) } if _, err := WaitSubnetMapCustomerOwnedIPOnLaunchUpdated(conn, subnetID, mapCustomerOwnedIPOnLaunch); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) MapCustomerOwnedIpOnLaunch update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) MapCustomerOwnedIpOnLaunch update: %w", subnetID, err) } return nil @@ -643,11 +643,11 @@ func modifySubnetPrivateDNSHostnameTypeOnLaunch(conn *ec2.EC2, subnetID string, } if _, err := conn.ModifySubnetAttribute(input); err != nil { - return fmt.Errorf("error modifying EC2 Subnet (%s) PrivateDnsHostnameTypeOnLaunch: %w", subnetID, err) + return fmt.Errorf("modifying EC2 Subnet (%s) PrivateDnsHostnameTypeOnLaunch: %w", subnetID, err) } if _, err := WaitSubnetPrivateDNSHostnameTypeOnLaunchUpdated(conn, subnetID, v); err != nil { - return fmt.Errorf("error waiting for EC2 Subnet (%s) PrivateDnsHostnameTypeOnLaunch update: %w", subnetID, err) + return fmt.Errorf("waiting for EC2 Subnet (%s) PrivateDnsHostnameTypeOnLaunch update: %w", subnetID, err) } return nil diff --git a/internal/service/ec2/vpc_subnet_cidr_reservation.go b/internal/service/ec2/vpc_subnet_cidr_reservation.go index 15fa39e4657..7bb2d9bb9d9 100644 --- a/internal/service/ec2/vpc_subnet_cidr_reservation.go +++ b/internal/service/ec2/vpc_subnet_cidr_reservation.go @@ -129,8 +129,8 @@ func resourceSubnetCIDRReservationDelete(d *schema.ResourceData, meta interface{ } if err != nil { - return fmt.Errorf("error deleting EC2 Subnet CIDR Reservation (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Subnet CIDR Reservation (%s): %w", d.Id(), err) } - return err + return nil } diff --git a/internal/service/ec2/vpnclient_authorization_rule.go b/internal/service/ec2/vpnclient_authorization_rule.go index 2ea8bdff114..13e72654c79 100644 --- a/internal/service/ec2/vpnclient_authorization_rule.go +++ b/internal/service/ec2/vpnclient_authorization_rule.go @@ -112,7 +112,7 @@ func resourceClientVPNAuthorizationRuleRead(d *schema.ResourceData, meta interfa endpointID, targetNetworkCIDR, accessGroupID, err := ClientVPNAuthorizationRuleParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Client VPN Authorization Rule (%s): %w", d.Id(), err) } rule, err := FindClientVPNAuthorizationRuleByThreePartKey(conn, endpointID, targetNetworkCIDR, accessGroupID) @@ -124,7 +124,7 @@ func resourceClientVPNAuthorizationRuleRead(d *schema.ResourceData, meta interfa } if err != nil { - return fmt.Errorf("error reading EC2 Client VPN Authorization Rule (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Client VPN Authorization Rule (%s): %w", d.Id(), err) } d.Set("access_group_id", rule.GroupId) @@ -142,7 +142,7 @@ func resourceClientVPNAuthorizationRuleDelete(d *schema.ResourceData, meta inter endpointID, targetNetworkCIDR, accessGroupID, err := ClientVPNAuthorizationRuleParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Client VPN Authorization Rule (%s): %w", d.Id(), err) } input := &ec2.RevokeClientVpnIngressInput{ @@ -162,11 +162,11 @@ func resourceClientVPNAuthorizationRuleDelete(d *schema.ResourceData, meta inter } if err != nil { - return fmt.Errorf("error revoking EC2 Client VPN Authorization Rule (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Client VPN Authorization Rule (%s): %w", d.Id(), err) } if _, err := WaitClientVPNAuthorizationRuleDeleted(conn, endpointID, targetNetworkCIDR, accessGroupID, d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for EC2 Client VPN Authorization Rule (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Client VPN Authorization Rule (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpnclient_route.go b/internal/service/ec2/vpnclient_route.go index bc251dbdc7d..fccbb25be5c 100644 --- a/internal/service/ec2/vpnclient_route.go +++ b/internal/service/ec2/vpnclient_route.go @@ -103,7 +103,7 @@ func resourceClientVPNRouteRead(d *schema.ResourceData, meta interface{}) error endpointID, targetSubnetID, destinationCIDR, err := ClientVPNRouteParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 Client VPN Route (%s): %w", d.Id(), err) } route, err := FindClientVPNRouteByThreePartKey(conn, endpointID, targetSubnetID, destinationCIDR) @@ -115,7 +115,7 @@ func resourceClientVPNRouteRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading EC2 Client VPN Route (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 Client VPN Route (%s): %w", d.Id(), err) } d.Set("client_vpn_endpoint_id", route.ClientVpnEndpointId) @@ -134,7 +134,7 @@ func resourceClientVPNRouteDelete(d *schema.ResourceData, meta interface{}) erro endpointID, targetSubnetID, destinationCIDR, err := ClientVPNRouteParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 Client VPN Route (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting EC2 Client VPN Route: %s", d.Id()) @@ -149,11 +149,11 @@ func resourceClientVPNRouteDelete(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("error deleting EC2 Client VPN Route (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Client VPN Route (%s): %w", d.Id(), err) } if _, err := WaitClientVPNRouteDeleted(conn, endpointID, targetSubnetID, destinationCIDR, d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for EC2 Client VPN Route (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting EC2 Client VPN Route (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpnsite_connection.go b/internal/service/ec2/vpnsite_connection.go index ed4f308e48e..8b2ba8f073d 100644 --- a/internal/service/ec2/vpnsite_connection.go +++ b/internal/service/ec2/vpnsite_connection.go @@ -711,7 +711,7 @@ func resourceVPNConnectionRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading EC2 VPN Connection (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 VPN Connection (%s): %w", d.Id(), err) } arn := arn.ARN{ @@ -783,7 +783,7 @@ func resourceVPNConnectionRead(d *schema.ResourceData, meta interface{}) error { for i, prefix := range []string{"tunnel1_", "tunnel2_"} { if len(v.TunnelOptions) > i { if err := flattenTunnelOption(d, prefix, v.TunnelOptions[i]); err != nil { - return err + return fmt.Errorf("reading EC2 VPN Connection (%s): %w", d.Id(), err) } } } diff --git a/internal/service/ec2/vpnsite_connection_route.go b/internal/service/ec2/vpnsite_connection_route.go index 8628f880ca2..01a127c36e7 100644 --- a/internal/service/ec2/vpnsite_connection_route.go +++ b/internal/service/ec2/vpnsite_connection_route.go @@ -67,7 +67,7 @@ func resourceVPNConnectionRouteRead(d *schema.ResourceData, meta interface{}) er cidrBlock, vpnConnectionID, err := VPNConnectionRouteParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading EC2 VPN Connection Route (%s): %w", d.Id(), err) } _, err = FindVPNConnectionRouteByVPNConnectionIDAndCIDR(conn, vpnConnectionID, cidrBlock) @@ -79,7 +79,7 @@ func resourceVPNConnectionRouteRead(d *schema.ResourceData, meta interface{}) er } if err != nil { - return fmt.Errorf("error reading EC2 VPN Connection Route (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 VPN Connection Route (%s): %w", d.Id(), err) } d.Set("destination_cidr_block", cidrBlock) @@ -94,7 +94,7 @@ func resourceVPNConnectionRouteDelete(d *schema.ResourceData, meta interface{}) cidrBlock, vpnConnectionID, err := VPNConnectionRouteParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting EC2 VPN Connection Route (%s): %w", d.Id(), err) } log.Printf("[INFO] Deleting EC2 VPN Connection Route: %s", d.Id()) @@ -108,11 +108,11 @@ func resourceVPNConnectionRouteDelete(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error deleting EC2 VPN Connection Route (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 VPN Connection Route (%s): %w", d.Id(), err) } if _, err := WaitVPNConnectionRouteDeleted(conn, vpnConnectionID, cidrBlock); err != nil { - return fmt.Errorf("error waiting for EC2 VPN Connection Route (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting EC2 VPN Connection Route (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/ec2/vpnsite_gateway.go b/internal/service/ec2/vpnsite_gateway.go index c9b6eed4cfc..f2755a519cc 100644 --- a/internal/service/ec2/vpnsite_gateway.go +++ b/internal/service/ec2/vpnsite_gateway.go @@ -72,7 +72,7 @@ func resourceVPNGatewayCreate(d *schema.ResourceData, meta interface{}) error { v, err := strconv.ParseInt(v.(string), 10, 64) if err != nil { - return err + return fmt.Errorf("creating EC2 VPN Gateway: %w", err) } input.AmazonSideAsn = aws.Int64(v) @@ -82,14 +82,14 @@ func resourceVPNGatewayCreate(d *schema.ResourceData, meta interface{}) error { output, err := conn.CreateVpnGateway(input) if err != nil { - return fmt.Errorf("error creating EC2 VPN Gateway: %w", err) + return fmt.Errorf("creating EC2 VPN Gateway: %w", err) } d.SetId(aws.StringValue(output.VpnGateway.VpnGatewayId)) if v, ok := d.GetOk("vpc_id"); ok { if err := attachVPNGatewayToVPC(conn, d.Id(), v.(string)); err != nil { - return err + return fmt.Errorf("creating EC2 VPN Gateway: %w", err) } } @@ -112,7 +112,7 @@ func resourceVPNGatewayRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading EC2 VPN Gateway (%s): %w", d.Id(), err) + return fmt.Errorf("reading EC2 VPN Gateway (%s): %w", d.Id(), err) } vpnGateway := outputRaw.(*ec2.VpnGateway) @@ -141,11 +141,11 @@ func resourceVPNGatewayRead(d *schema.ResourceData, meta interface{}) error { //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } return nil @@ -159,13 +159,13 @@ func resourceVPNGatewayUpdate(d *schema.ResourceData, meta interface{}) error { if vpcID, ok := o.(string); ok && vpcID != "" { if err := detachVPNGatewayFromVPC(conn, d.Id(), vpcID); err != nil { - return err + return fmt.Errorf("updating EC2 VPN Gateway (%s): %w", d.Id(), err) } } if vpcID, ok := n.(string); ok && vpcID != "" { if err := attachVPNGatewayToVPC(conn, d.Id(), vpcID); err != nil { - return err + return fmt.Errorf("updating EC2 VPN Gateway (%s): %w", d.Id(), err) } } } @@ -174,7 +174,7 @@ func resourceVPNGatewayUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating EC2 VPN Gateway (%s) tags: %w", d.Id(), err) + return fmt.Errorf("updating EC2 VPN Gateway (%s) tags: %w", d.Id(), err) } } @@ -186,7 +186,7 @@ func resourceVPNGatewayDelete(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("vpc_id"); ok { if err := detachVPNGatewayFromVPC(conn, d.Id(), v.(string)); err != nil { - return err + return fmt.Errorf("deleting EC2 VPN Gateway (%s): %w", d.Id(), err) } } @@ -202,7 +202,7 @@ func resourceVPNGatewayDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting EC2 VPN Gateway (%s): %w", d.Id(), err) + return fmt.Errorf("deleting EC2 VPN Gateway (%s): %w", d.Id(), err) } return nil @@ -220,13 +220,13 @@ func attachVPNGatewayToVPC(conn *ec2.EC2, vpnGatewayID, vpcID string) error { }, errCodeInvalidVPNGatewayIDNotFound) if err != nil { - return fmt.Errorf("error attaching EC2 VPN Gateway (%s) to VPC (%s): %w", vpnGatewayID, vpcID, err) + return fmt.Errorf("attaching to VPC (%s): %w", vpcID, err) } _, err = WaitVPNGatewayVPCAttachmentAttached(conn, vpnGatewayID, vpcID) if err != nil { - return fmt.Errorf("error waiting for EC2 VPN Gateway (%s) to attach to VPC (%s): %w", vpnGatewayID, vpcID, err) + return fmt.Errorf("attaching to VPC (%s): waiting for completion: %w", vpcID, err) } return nil @@ -246,13 +246,13 @@ func detachVPNGatewayFromVPC(conn *ec2.EC2, vpnGatewayID, vpcID string) error { } if err != nil { - return fmt.Errorf("error detaching EC2 VPN Gateway (%s) from VPC (%s): %w", vpnGatewayID, vpcID, err) + return fmt.Errorf("detaching from VPC (%s): %w", vpcID, err) } _, err = WaitVPNGatewayVPCAttachmentDetached(conn, vpnGatewayID, vpcID) if err != nil { - return fmt.Errorf("error waiting for EC2 VPN Gateway (%s) to detach from VPC (%s): %w", vpnGatewayID, vpcID, err) + return fmt.Errorf("detaching from VPC (%s): waiting for completion: %w", vpcID, err) } return nil diff --git a/internal/service/ec2/vpnsite_gateway_route_propagation.go b/internal/service/ec2/vpnsite_gateway_route_propagation.go index 73bec3c0fd9..221f92129bf 100644 --- a/internal/service/ec2/vpnsite_gateway_route_propagation.go +++ b/internal/service/ec2/vpnsite_gateway_route_propagation.go @@ -45,7 +45,7 @@ func resourceVPNGatewayRoutePropagationEnable(d *schema.ResourceData, meta inter err := routeTableEnableVGWRoutePropagation(conn, routeTableID, gatewayID, d.Timeout(schema.TimeoutCreate)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } d.SetId(VPNGatewayRoutePropagationCreateID(routeTableID, gatewayID)) @@ -59,7 +59,7 @@ func resourceVPNGatewayRoutePropagationDisable(d *schema.ResourceData, meta inte routeTableID, gatewayID, err := VPNGatewayRoutePropagationParseID(d.Id()) if err != nil { - return err + return err // nosemgrep:bare-error-returns } err = routeTableDisableVGWRoutePropagation(conn, routeTableID, gatewayID) @@ -68,7 +68,7 @@ func resourceVPNGatewayRoutePropagationDisable(d *schema.ResourceData, meta inte return nil } - return err + return err // nosemgrep:bare-error-returns } func resourceVPNGatewayRoutePropagationRead(d *schema.ResourceData, meta interface{}) error { @@ -77,7 +77,7 @@ func resourceVPNGatewayRoutePropagationRead(d *schema.ResourceData, meta interfa routeTableID, gatewayID, err := VPNGatewayRoutePropagationParseID(d.Id()) if err != nil { - return err + return err // nosemgrep:bare-error-returns } err = FindVPNGatewayRoutePropagationExists(conn, routeTableID, gatewayID) @@ -89,7 +89,7 @@ func resourceVPNGatewayRoutePropagationRead(d *schema.ResourceData, meta interfa } if err != nil { - return fmt.Errorf("error reading Route Table (%s) VPN Gateway (%s) route propagation: %w", routeTableID, gatewayID, err) + return fmt.Errorf("reading Route Table (%s) VPN Gateway (%s) route propagation: %w", routeTableID, gatewayID, err) } return nil diff --git a/internal/service/ecs/task_definition.go b/internal/service/ecs/task_definition.go index bdfdadbc20a..fabeedb652c 100644 --- a/internal/service/ecs/task_definition.go +++ b/internal/service/ecs/task_definition.go @@ -760,8 +760,6 @@ func resourceTaskDefinitionDelete(d *schema.ResourceData, meta interface{}) erro return fmt.Errorf("deleting ECS Task Definition (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] Task definition %q deregistered.", d.Get("arn").(string)) - return nil } diff --git a/internal/tfresource/not_found_error.go b/internal/tfresource/not_found_error.go index a270d77d225..9ff6708730b 100644 --- a/internal/tfresource/not_found_error.go +++ b/internal/tfresource/not_found_error.go @@ -89,5 +89,5 @@ func SingularDataSourceFindError(resourceType string, err error) error { return fmt.Errorf("no matching %[1]s found", resourceType) } - return fmt.Errorf("error reading %s: %w", resourceType, err) + return fmt.Errorf("reading %s: %w", resourceType, err) } From d5faebcc447f743ccbf3851971b9df0aa2ae7027 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:29:02 -0800 Subject: [PATCH 066/106] Fixes bare errors in `dynamodb` --- internal/service/dynamodb/global_table.go | 27 ++++++++--------------- internal/service/dynamodb/table_item.go | 22 +++++++++--------- 2 files changed, 20 insertions(+), 29 deletions(-) diff --git a/internal/service/dynamodb/global_table.go b/internal/service/dynamodb/global_table.go index 5fa5b88c358..d5ca8ac984b 100644 --- a/internal/service/dynamodb/global_table.go +++ b/internal/service/dynamodb/global_table.go @@ -68,10 +68,9 @@ func resourceGlobalTableCreate(d *schema.ResourceData, meta interface{}) error { ReplicationGroup: expandReplicas(d.Get("replica").(*schema.Set).List()), } - log.Printf("[DEBUG] Creating DynamoDB Global Table: %#v", input) _, err := conn.CreateGlobalTable(input) if err != nil { - return err + return fmt.Errorf("creating DynamoDB Global Table (%s): %w", globalTableName, err) } d.SetId(globalTableName) @@ -92,7 +91,7 @@ func resourceGlobalTableCreate(d *schema.ResourceData, meta interface{}) error { } _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("creating DynamoDB Global Table (%s): waiting for completion: %w", globalTableName, err) } return resourceGlobalTableRead(d, meta) @@ -102,7 +101,7 @@ func resourceGlobalTableRead(d *schema.ResourceData, meta interface{}) error { globalTableDescription, err := resourceGlobalTableRetrieve(d, meta) if err != nil { - return err + return fmt.Errorf("reading DynamoDB Global Table (%s): %w", d.Id(), err) } if globalTableDescription == nil { log.Printf("[WARN] DynamoDB Global Table %q not found, removing from state", d.Id()) @@ -140,7 +139,7 @@ func resourceGlobalTableUpdate(d *schema.ResourceData, meta interface{}) error { } log.Printf("[DEBUG] Updating DynamoDB Global Table: %#v", input) if _, err := conn.UpdateGlobalTable(input); err != nil { - return err + return fmt.Errorf("updating DynamoDB Global Table (%s): %w", d.Id(), err) } log.Println("[INFO] Waiting for DynamoDB Global Table to be updated") @@ -159,7 +158,7 @@ func resourceGlobalTableUpdate(d *schema.ResourceData, meta interface{}) error { } _, err := stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("updating DynamoDB Global Table (%s): waiting for completion: %w", d.Id(), err) } } @@ -176,7 +175,7 @@ func resourceGlobalTableDelete(d *schema.ResourceData, meta interface{}) error { } log.Printf("[DEBUG] Deleting DynamoDB Global Table: %#v", input) if _, err := conn.UpdateGlobalTable(input); err != nil { - return err + return fmt.Errorf("deleting DynamoDB Global Table (%s): %w", d.Id(), err) } log.Println("[INFO] Waiting for DynamoDB Global Table to be destroyed") @@ -193,7 +192,7 @@ func resourceGlobalTableDelete(d *schema.ResourceData, meta interface{}) error { MinTimeout: 10 * time.Second, } _, err := stateConf.WaitForState() - return err + return fmt.Errorf("deleting DynamoDB Global Table (%s): waiting for completion: %w", d.Id(), err) } func resourceGlobalTableRetrieve(d *schema.ResourceData, meta interface{}) (*dynamodb.GlobalTableDescription, error) { @@ -210,7 +209,7 @@ func resourceGlobalTableRetrieve(d *schema.ResourceData, meta interface{}) (*dyn if tfawserr.ErrCodeEquals(err, dynamodb.ErrCodeGlobalTableNotFoundException) { return nil, nil } - return nil, fmt.Errorf("Error retrieving DynamoDB Global Table: %s", err) + return nil, err } return output.GlobalTableDescription, nil @@ -222,7 +221,6 @@ func resourceGlobalTableStateRefreshFunc( gtd, err := resourceGlobalTableRetrieve(d, meta) if err != nil { - log.Printf("Error on retrieving DynamoDB Global Table when waiting: %s", err) return nil, "", err } @@ -230,22 +228,15 @@ func resourceGlobalTableStateRefreshFunc( return nil, "", nil } - if gtd.GlobalTableStatus != nil { - log.Printf("[DEBUG] Status for DynamoDB Global Table %s: %s", d.Id(), *gtd.GlobalTableStatus) - } - return gtd, *gtd.GlobalTableStatus, nil } } func flattenGlobalTable(d *schema.ResourceData, globalTableDescription *dynamodb.GlobalTableDescription) error { - var err error - d.Set("arn", globalTableDescription.GlobalTableArn) d.Set("name", globalTableDescription.GlobalTableName) - err = d.Set("replica", flattenReplicas(globalTableDescription.ReplicationGroup)) - return err + return d.Set("replica", flattenReplicas(globalTableDescription.ReplicationGroup)) } func expandReplicaUpdateCreateReplicas(configuredReplicas []interface{}) []*dynamodb.ReplicaUpdate { diff --git a/internal/service/dynamodb/table_item.go b/internal/service/dynamodb/table_item.go index 3224e8345a2..c2dafcc24da 100644 --- a/internal/service/dynamodb/table_item.go +++ b/internal/service/dynamodb/table_item.go @@ -65,7 +65,7 @@ func resourceTableItemCreate(d *schema.ResourceData, meta interface{}) error { item := d.Get("item").(string) attributes, err := ExpandTableItemAttributes(item) if err != nil { - return err + return fmt.Errorf("creating DynamoDB Table Item: %w", err) } log.Printf("[DEBUG] DynamoDB item create: %s", tableName) @@ -78,7 +78,7 @@ func resourceTableItemCreate(d *schema.ResourceData, meta interface{}) error { TableName: aws.String(tableName), }) if err != nil { - return err + return fmt.Errorf("creating DynamoDB Table Item: %w", err) } rangeKey := d.Get("range_key").(string) @@ -102,7 +102,7 @@ func resourceTableItemUpdate(d *schema.ResourceData, meta interface{}) error { attributes, err := ExpandTableItemAttributes(newItem.(string)) if err != nil { - return err + return fmt.Errorf("updating DynamoDB Table Item (%s): %w", d.Id(), err) } newQueryKey := BuildTableItemqueryKey(attributes, hashKey, rangeKey) @@ -121,7 +121,7 @@ func resourceTableItemUpdate(d *schema.ResourceData, meta interface{}) error { oldAttributes, err := ExpandTableItemAttributes(oldItem.(string)) if err != nil { - return err + return fmt.Errorf("updating DynamoDB Table Item (%s): %w", d.Id(), err) } for k := range oldAttributes { @@ -141,7 +141,7 @@ func resourceTableItemUpdate(d *schema.ResourceData, meta interface{}) error { Key: newQueryKey, }) if err != nil { - return fmt.Errorf("error updating DynamoDB Table Item (%s): %w", d.Id(), err) + return fmt.Errorf("updating DynamoDB Table Item (%s): %w", d.Id(), err) } // New record is created via UpdateItem in case we're changing hash key @@ -154,7 +154,7 @@ func resourceTableItemUpdate(d *schema.ResourceData, meta interface{}) error { TableName: aws.String(tableName), }) if err != nil { - return err + return fmt.Errorf("updating DynamoDB Table Item (%s): removing old record: %w", d.Id(), err) } } @@ -175,7 +175,7 @@ func resourceTableItemRead(d *schema.ResourceData, meta interface{}) error { rangeKey := d.Get("range_key").(string) attributes, err := ExpandTableItemAttributes(d.Get("item").(string)) if err != nil { - return err + return fmt.Errorf("reading DynamoDB Table Item (%s): %w", d.Id(), err) } key := BuildTableItemqueryKey(attributes, hashKey, rangeKey) @@ -188,14 +188,14 @@ func resourceTableItemRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DynamoDB Table Item (%s): %w", d.Id(), err) + return fmt.Errorf("reading DynamoDB Table Item (%s): %w", d.Id(), err) } // The record exists, now test if it differs from what is desired if !reflect.DeepEqual(result.Item, attributes) { itemAttrs, err := flattenTableItemAttributes(result.Item) if err != nil { - return err + return fmt.Errorf("reading DynamoDB Table Item (%s): %w", d.Id(), err) } d.Set("item", itemAttrs) id := buildTableItemID(tableName, hashKey, rangeKey, result.Item) @@ -210,7 +210,7 @@ func resourceTableItemDelete(d *schema.ResourceData, meta interface{}) error { attributes, err := ExpandTableItemAttributes(d.Get("item").(string)) if err != nil { - return err + return fmt.Errorf("deleting DynamoDB Table Item (%s): %w", d.Id(), err) } hashKey := d.Get("hash_key").(string) rangeKey := d.Get("range_key").(string) @@ -222,7 +222,7 @@ func resourceTableItemDelete(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return fmt.Errorf("error deleting DynamoDB Table Item (%s): %w", d.Id(), err) + return fmt.Errorf("deleting DynamoDB Table Item (%s): %w", d.Id(), err) } return nil From 288949454d7073790b48cb0e9c11101de6d8512f Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:29:15 -0800 Subject: [PATCH 067/106] Fixes bare errors in `ds` --- internal/service/ds/conditional_forwarder.go | 14 +++++++------- internal/service/ds/directory.go | 12 ++++++------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/internal/service/ds/conditional_forwarder.go b/internal/service/ds/conditional_forwarder.go index e34a3a527f2..b09bb63e1ba 100644 --- a/internal/service/ds/conditional_forwarder.go +++ b/internal/service/ds/conditional_forwarder.go @@ -67,7 +67,7 @@ func resourceConditionalForwarderCreate(d *schema.ResourceData, meta interface{} }) if err != nil { - return err + return fmt.Errorf("creating Directory Service Conditional Forwarder: %w", err) } d.SetId(fmt.Sprintf("%s:%s", directoryId, domainName)) @@ -80,7 +80,7 @@ func resourceConditionalForwarderRead(d *schema.ResourceData, meta interface{}) directoryId, domainName, err := ParseConditionalForwarderID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Directory Service Conditional Forwarder (%s): %w", d.Id(), err) } res, err := conn.DescribeConditionalForwarders(&directoryservice.DescribeConditionalForwardersInput{ @@ -94,7 +94,7 @@ func resourceConditionalForwarderRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return err + return fmt.Errorf("reading Directory Service Conditional Forwarder (%s): %w", d.Id(), err) } if len(res.ConditionalForwarders) == 0 { @@ -117,7 +117,7 @@ func resourceConditionalForwarderUpdate(d *schema.ResourceData, meta interface{} directoryId, domainName, err := ParseConditionalForwarderID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Directory Service Conditional Forwarder (%s): %w", d.Id(), err) } dnsIps := flex.ExpandStringList(d.Get("dns_ips").([]interface{})) @@ -129,7 +129,7 @@ func resourceConditionalForwarderUpdate(d *schema.ResourceData, meta interface{} }) if err != nil { - return err + return fmt.Errorf("updating Directory Service Conditional Forwarder (%s): %w", d.Id(), err) } return resourceConditionalForwarderRead(d, meta) @@ -140,7 +140,7 @@ func resourceConditionalForwarderDelete(d *schema.ResourceData, meta interface{} directoryId, domainName, err := ParseConditionalForwarderID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Directory Service Conditional Forwarder (%s): %w", d.Id(), err) } _, err = conn.DeleteConditionalForwarder(&directoryservice.DeleteConditionalForwarderInput{ @@ -149,7 +149,7 @@ func resourceConditionalForwarderDelete(d *schema.ResourceData, meta interface{} }) if err != nil && !tfawserr.ErrCodeEquals(err, directoryservice.ErrCodeEntityDoesNotExistException) { - return err + return fmt.Errorf("deleting Directory Service Conditional Forwarder (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/ds/directory.go b/internal/service/ds/directory.go index 89a541d166e..6b1dc5e80dd 100644 --- a/internal/service/ds/directory.go +++ b/internal/service/ds/directory.go @@ -304,19 +304,19 @@ func resourceDirectoryCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("alias"); ok { if err := createAlias(conn, d.Id(), v.(string)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if v, ok := d.GetOk("desired_number_of_domain_controllers"); ok { if err := updateNumberOfDomainControllers(conn, d.Id(), v.(int), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if _, ok := d.GetOk("enable_sso"); ok { if err := enableSSO(conn, d.Id()); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -400,18 +400,18 @@ func resourceDirectoryUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("desired_number_of_domain_controllers") { if err := updateNumberOfDomainControllers(conn, d.Id(), d.Get("desired_number_of_domain_controllers").(int), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if d.HasChange("enable_sso") { if _, ok := d.GetOk("enable_sso"); ok { if err := enableSSO(conn, d.Id()); err != nil { - return err + return err // nosemgrep:bare-error-returns } } else { if err := disableSSO(conn, d.Id()); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } From 1eecb3ab29e0bb231b0ac383fa5f5e05b115ffb3 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:29:28 -0800 Subject: [PATCH 068/106] Fixes bare errors in `docdb` --- internal/service/docdb/cluster_parameter_group.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/docdb/cluster_parameter_group.go b/internal/service/docdb/cluster_parameter_group.go index ee1e3bf2f93..db23aa82d5b 100644 --- a/internal/service/docdb/cluster_parameter_group.go +++ b/internal/service/docdb/cluster_parameter_group.go @@ -256,7 +256,7 @@ func resourceClusterParameterGroupDelete(d *schema.ResourceData, meta interface{ if tfawserr.ErrCodeEquals(err, docdb.ErrCodeDBParameterGroupNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting DocumentDB Cluster Parameter Group (%s): %w", d.Id(), err) } return WaitForClusterParameterGroupDeletion(conn, d.Id()) From 0e73f6cd30266edb95d55233af9a88d4f6c51605 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:30:03 -0800 Subject: [PATCH 069/106] Fixes bare errors in `dms` --- internal/service/dms/certificate.go | 11 +++----- internal/service/dms/endpoint.go | 4 +-- internal/service/dms/replication_task.go | 34 ++++++++++++------------ internal/service/dms/s3_endpoint.go | 2 +- 4 files changed, 23 insertions(+), 28 deletions(-) diff --git a/internal/service/dms/certificate.go b/internal/service/dms/certificate.go index e8766b249d4..cb9d5298e1f 100644 --- a/internal/service/dms/certificate.go +++ b/internal/service/dms/certificate.go @@ -125,7 +125,7 @@ func resourceCertificateRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DMS Certificate (%s): %w", d.Id(), err) + return fmt.Errorf("reading DMS Certificate (%s): %w", d.Id(), err) } if response == nil || len(response.Certificates) == 0 || response.Certificates[0] == nil { @@ -137,10 +137,7 @@ func resourceCertificateRead(d *schema.ResourceData, meta interface{}) error { return nil } - err = resourceCertificateSetState(d, response.Certificates[0]) - if err != nil { - return err - } + resourceCertificateSetState(d, response.Certificates[0]) tags, err := ListTags(conn, d.Get("certificate_arn").(string)) @@ -196,7 +193,7 @@ func resourceCertificateDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceCertificateSetState(d *schema.ResourceData, cert *dms.Certificate) error { +func resourceCertificateSetState(d *schema.ResourceData, cert *dms.Certificate) { d.SetId(aws.StringValue(cert.CertificateIdentifier)) d.Set("certificate_id", cert.CertificateIdentifier) @@ -208,6 +205,4 @@ func resourceCertificateSetState(d *schema.ResourceData, cert *dms.Certificate) if cert.CertificateWallet != nil && len(cert.CertificateWallet) != 0 { d.Set("certificate_wallet", verify.Base64Encode(cert.CertificateWallet)) } - - return nil } diff --git a/internal/service/dms/endpoint.go b/internal/service/dms/endpoint.go index c02211e3539..77d270d68a0 100644 --- a/internal/service/dms/endpoint.go +++ b/internal/service/dms/endpoint.go @@ -935,7 +935,7 @@ func resourceEndpointRead(d *schema.ResourceData, meta interface{}) error { err = resourceEndpointSetState(d, endpoint) if err != nil { - return err + return fmt.Errorf("reading DMS Endpoint (%s): %w", d.Id(), err) } tags, err := ListTags(conn, d.Get("endpoint_arn").(string)) @@ -1304,7 +1304,7 @@ func resourceEndpointDelete(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("waiting for DMS Endpoint (%s) delete: %w", d.Id(), err) } - return err + return nil } func resourceEndpointCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { diff --git a/internal/service/dms/replication_task.go b/internal/service/dms/replication_task.go index 54fce456adc..7c32d6028ae 100644 --- a/internal/service/dms/replication_task.go +++ b/internal/service/dms/replication_task.go @@ -156,7 +156,7 @@ func resourceReplicationTaskCreate(d *schema.ResourceData, meta interface{}) err if d.Get("start_replication_task").(bool) { if err := startReplicationTask(d.Id(), conn); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -177,11 +177,11 @@ func resourceReplicationTaskRead(d *schema.ResourceData, meta interface{}) error } if err != nil { - return fmt.Errorf("error reading DMS Replication Task (%s): %w", d.Id(), err) + return fmt.Errorf("reading DMS Replication Task (%s): %w", d.Id(), err) } if task == nil { - return fmt.Errorf("error reading DMS Replication Task (%s): empty output", d.Id()) + return fmt.Errorf("reading DMS Replication Task (%s): empty output", d.Id()) } d.Set("cdc_start_position", task.CdcStartPosition) @@ -196,7 +196,7 @@ func resourceReplicationTaskRead(d *schema.ResourceData, meta interface{}) error settings, err := replicationTaskRemoveReadOnlySettings(aws.StringValue(task.ReplicationTaskSettings)) if err != nil { - return err + return fmt.Errorf("reading DMS Replication Task (%s): %w", d.Id(), err) } d.Set("replication_task_settings", settings) @@ -251,7 +251,7 @@ func resourceReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) err if status == replicationTaskStatusRunning { log.Println("[DEBUG] stopping DMS replication task:", input) if err := stopReplicationTask(d.Id(), conn); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -268,7 +268,7 @@ func resourceReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) err if d.Get("start_replication_task").(bool) { err := startReplicationTask(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -278,13 +278,13 @@ func resourceReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) err if d.Get("start_replication_task").(bool) { if status != replicationTaskStatusRunning { if err := startReplicationTask(d.Id(), conn); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } else { if status == replicationTaskStatusRunning { if err := stopReplicationTask(d.Id(), conn); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -307,7 +307,7 @@ func resourceReplicationTaskDelete(d *schema.ResourceData, meta interface{}) err if status := d.Get("status").(string); status == replicationTaskStatusRunning { if err := stopReplicationTask(d.Id(), conn); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -368,11 +368,11 @@ func startReplicationTask(id string, conn *dms.DatabaseMigrationService) error { task, err := FindReplicationTaskByID(conn, id) if err != nil { - return fmt.Errorf("error reading DMS Replication Task (%s): %w", id, err) + return fmt.Errorf("reading DMS Replication Task (%s): %w", id, err) } if task == nil { - return fmt.Errorf("error reading DMS Replication Task (%s): empty output", id) + return fmt.Errorf("reading DMS Replication Task (%s): empty output", id) } startReplicationTaskType := dms.StartReplicationTaskTypeValueStartReplication @@ -386,12 +386,12 @@ func startReplicationTask(id string, conn *dms.DatabaseMigrationService) error { }) if err != nil { - return fmt.Errorf("error starting DMS Replication Task (%s): %w", id, err) + return fmt.Errorf("starting DMS Replication Task (%s): %w", id, err) } err = waitReplicationTaskRunning(conn, id) if err != nil { - return fmt.Errorf("error waiting for DMS Replication Task (%s) start: %w", id, err) + return fmt.Errorf("waiting for DMS Replication Task (%s) start: %w", id, err) } return nil @@ -402,11 +402,11 @@ func stopReplicationTask(id string, conn *dms.DatabaseMigrationService) error { task, err := FindReplicationTaskByID(conn, id) if err != nil { - return fmt.Errorf("error reading DMS Replication Task (%s): %w", id, err) + return fmt.Errorf("reading DMS Replication Task (%s): %w", id, err) } if task == nil { - return fmt.Errorf("error reading DMS Replication Task (%s): empty output", id) + return fmt.Errorf("reading DMS Replication Task (%s): empty output", id) } _, err = conn.StopReplicationTask(&dms.StopReplicationTaskInput{ @@ -414,12 +414,12 @@ func stopReplicationTask(id string, conn *dms.DatabaseMigrationService) error { }) if err != nil { - return fmt.Errorf("error stopping DMS Replication Task (%s): %w", id, err) + return fmt.Errorf("stopping DMS Replication Task (%s): %w", id, err) } err = waitReplicationTaskStopped(conn, id) if err != nil { - return fmt.Errorf("error waiting for DMS Replication Task (%s) stop: %w", id, err) + return fmt.Errorf("waiting for DMS Replication Task (%s) stop: %w", id, err) } return nil diff --git a/internal/service/dms/s3_endpoint.go b/internal/service/dms/s3_endpoint.go index 75c96eb7664..8f54ca0ef76 100644 --- a/internal/service/dms/s3_endpoint.go +++ b/internal/service/dms/s3_endpoint.go @@ -572,7 +572,7 @@ func resourceS3EndpointDelete(d *schema.ResourceData, meta interface{}) error { return create.Error(names.DMS, create.ErrActionWaitingForDeletion, ResNameS3Endpoint, d.Id(), err) } - return err + return nil } func s3Settings(d *schema.ResourceData, target bool) *dms.S3Settings { From 985a44ca6b73dfb9205a0d039d6c0cdfc88ca9bc Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:30:15 -0800 Subject: [PATCH 070/106] Fixes bare errors in `directconnect` --- internal/service/directconnect/bgp_peer.go | 4 ++-- internal/service/directconnect/connection.go | 4 ++-- .../hosted_private_virtual_interface.go | 4 ++-- .../hosted_private_virtual_interface_accepter.go | 6 +++--- .../hosted_public_virtual_interface.go | 4 ++-- .../hosted_public_virtual_interface_accepter.go | 6 +++--- .../hosted_transit_virtual_interface.go | 4 ++-- .../hosted_transit_virtual_interface_accepter.go | 6 +++--- internal/service/directconnect/lag.go | 6 +++--- .../directconnect/private_virtual_interface.go | 8 ++++---- .../directconnect/public_virtual_interface.go | 6 +++--- .../directconnect/transit_virtual_interface.go | 8 ++++---- internal/service/directconnect/vif.go | 14 +++++++------- 13 files changed, 40 insertions(+), 40 deletions(-) diff --git a/internal/service/directconnect/bgp_peer.go b/internal/service/directconnect/bgp_peer.go index a4557ca3ddf..5326747ba2e 100644 --- a/internal/service/directconnect/bgp_peer.go +++ b/internal/service/directconnect/bgp_peer.go @@ -175,7 +175,7 @@ func resourceBGPPeerDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrMessageContains(err, "DirectConnectClientException", "The last BGP Peer on a Virtual Interface cannot be deleted") { return nil } - return err + return fmt.Errorf("deleting Direct Connect BGP Peer (%s): %w", d.Id(), err) } stateConf := &resource.StateChangeConf{ @@ -195,7 +195,7 @@ func resourceBGPPeerDelete(d *schema.ResourceData, meta interface{}) error { } _, err = stateConf.WaitForState() if err != nil { - return fmt.Errorf("Error waiting for Direct Connect BGP peer (%s) to be deleted: %s", d.Id(), err) + return fmt.Errorf("deleting Direct Connect BGP Peer (%s): waiting for completion: %w", d.Id(), err) } return nil diff --git a/internal/service/directconnect/connection.go b/internal/service/directconnect/connection.go index 217d456ddff..a1dd1820a70 100644 --- a/internal/service/directconnect/connection.go +++ b/internal/service/directconnect/connection.go @@ -261,13 +261,13 @@ func deleteConnection(conn *directconnect.DirectConnect, connectionID string, wa } if err != nil { - return fmt.Errorf("error deleting Direct Connect Connection (%s): %w", connectionID, err) + return fmt.Errorf("deleting Direct Connect Connection (%s): %w", connectionID, err) } _, err = waiter(conn, connectionID) if err != nil { - return fmt.Errorf("error waiting for Direct Connect Connection (%s) delete: %w", connectionID, err) + return fmt.Errorf("waiting for Direct Connect Connection (%s) delete: %w", connectionID, err) } return nil diff --git a/internal/service/directconnect/hosted_private_virtual_interface.go b/internal/service/directconnect/hosted_private_virtual_interface.go index df62e2b0b64..6e3a39cf1ca 100644 --- a/internal/service/directconnect/hosted_private_virtual_interface.go +++ b/internal/service/directconnect/hosted_private_virtual_interface.go @@ -147,7 +147,7 @@ func resourceHostedPrivateVirtualInterfaceCreate(d *schema.ResourceData, meta in d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := hostedPrivateVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedPrivateVirtualInterfaceRead(d, meta) @@ -158,7 +158,7 @@ func resourceHostedPrivateVirtualInterfaceRead(d *schema.ResourceData, meta inte vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted private virtual interface (%s) not found, removing from state", d.Id()) diff --git a/internal/service/directconnect/hosted_private_virtual_interface_accepter.go b/internal/service/directconnect/hosted_private_virtual_interface_accepter.go index 205982c0cd8..ad693ef0028 100644 --- a/internal/service/directconnect/hosted_private_virtual_interface_accepter.go +++ b/internal/service/directconnect/hosted_private_virtual_interface_accepter.go @@ -97,7 +97,7 @@ func resourceHostedPrivateVirtualInterfaceAccepterCreate(d *schema.ResourceData, d.Set("arn", arn) if err := hostedPrivateVirtualInterfaceAccepterWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedPrivateVirtualInterfaceAccepterUpdate(d, meta) @@ -110,7 +110,7 @@ func resourceHostedPrivateVirtualInterfaceAccepterRead(d *schema.ResourceData, m vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted private virtual interface (%s) not found, removing from state", d.Id()) @@ -152,7 +152,7 @@ func resourceHostedPrivateVirtualInterfaceAccepterRead(d *schema.ResourceData, m func resourceHostedPrivateVirtualInterfaceAccepterUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedPrivateVirtualInterfaceAccepterRead(d, meta) diff --git a/internal/service/directconnect/hosted_public_virtual_interface.go b/internal/service/directconnect/hosted_public_virtual_interface.go index 53bb7d0c29a..0c77253c370 100644 --- a/internal/service/directconnect/hosted_public_virtual_interface.go +++ b/internal/service/directconnect/hosted_public_virtual_interface.go @@ -144,7 +144,7 @@ func resourceHostedPublicVirtualInterfaceCreate(d *schema.ResourceData, meta int d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := hostedPublicVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedPublicVirtualInterfaceRead(d, meta) @@ -155,7 +155,7 @@ func resourceHostedPublicVirtualInterfaceRead(d *schema.ResourceData, meta inter vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect virtual interface (%s) not found, removing from state", d.Id()) diff --git a/internal/service/directconnect/hosted_public_virtual_interface_accepter.go b/internal/service/directconnect/hosted_public_virtual_interface_accepter.go index e40263bae22..a3aea455f57 100644 --- a/internal/service/directconnect/hosted_public_virtual_interface_accepter.go +++ b/internal/service/directconnect/hosted_public_virtual_interface_accepter.go @@ -72,7 +72,7 @@ func resourceHostedPublicVirtualInterfaceAccepterCreate(d *schema.ResourceData, d.Set("arn", arn) if err := hostedPublicVirtualInterfaceAccepterWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedPublicVirtualInterfaceAccepterUpdate(d, meta) @@ -85,7 +85,7 @@ func resourceHostedPublicVirtualInterfaceAccepterRead(d *schema.ResourceData, me vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted public virtual interface (%s) not found, removing from state", d.Id()) @@ -126,7 +126,7 @@ func resourceHostedPublicVirtualInterfaceAccepterRead(d *schema.ResourceData, me func resourceHostedPublicVirtualInterfaceAccepterUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedPublicVirtualInterfaceAccepterRead(d, meta) diff --git a/internal/service/directconnect/hosted_transit_virtual_interface.go b/internal/service/directconnect/hosted_transit_virtual_interface.go index 6601d61a9bc..5c4cf6fa76e 100644 --- a/internal/service/directconnect/hosted_transit_virtual_interface.go +++ b/internal/service/directconnect/hosted_transit_virtual_interface.go @@ -144,7 +144,7 @@ func resourceHostedTransitVirtualInterfaceCreate(d *schema.ResourceData, meta in d.SetId(aws.StringValue(resp.VirtualInterface.VirtualInterfaceId)) if err := hostedTransitVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedTransitVirtualInterfaceRead(d, meta) @@ -155,7 +155,7 @@ func resourceHostedTransitVirtualInterfaceRead(d *schema.ResourceData, meta inte vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted transit virtual interface (%s) not found, removing from state", d.Id()) diff --git a/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go b/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go index a5e5de2175f..5711ee50416 100644 --- a/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go +++ b/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go @@ -78,7 +78,7 @@ func resourceHostedTransitVirtualInterfaceAccepterCreate(d *schema.ResourceData, d.Set("arn", arn) if err := hostedTransitVirtualInterfaceAccepterWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedTransitVirtualInterfaceAccepterUpdate(d, meta) @@ -91,7 +91,7 @@ func resourceHostedTransitVirtualInterfaceAccepterRead(d *schema.ResourceData, m vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect transit virtual interface (%s) not found, removing from state", d.Id()) @@ -131,7 +131,7 @@ func resourceHostedTransitVirtualInterfaceAccepterRead(d *schema.ResourceData, m func resourceHostedTransitVirtualInterfaceAccepterUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceHostedTransitVirtualInterfaceAccepterRead(d, meta) diff --git a/internal/service/directconnect/lag.go b/internal/service/directconnect/lag.go index fddb691e0db..6b5b32a6a40 100644 --- a/internal/service/directconnect/lag.go +++ b/internal/service/directconnect/lag.go @@ -124,7 +124,7 @@ func resourceLagCreate(d *schema.ResourceData, meta interface{}) error { err = deleteConnection(conn, aws.StringValue(output.Connections[0].ConnectionId), waitConnectionDeleted) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -227,12 +227,12 @@ func resourceLagDelete(d *schema.ResourceData, meta interface{}) error { err = deleteConnection(conn, aws.StringValue(connection.ConnectionId), waitConnectionDeleted) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } } else if v, ok := d.GetOk("connection_id"); ok { if err := deleteConnectionLAGAssociation(conn, v.(string), d.Id()); err != nil { - return err + return err // nosemgrep:bare-error-returns } } diff --git a/internal/service/directconnect/private_virtual_interface.go b/internal/service/directconnect/private_virtual_interface.go index 8f211e88109..d8694000a10 100644 --- a/internal/service/directconnect/private_virtual_interface.go +++ b/internal/service/directconnect/private_virtual_interface.go @@ -178,7 +178,7 @@ func resourcePrivateVirtualInterfaceCreate(d *schema.ResourceData, meta interfac d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := privateVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourcePrivateVirtualInterfaceRead(d, meta) @@ -191,7 +191,7 @@ func resourcePrivateVirtualInterfaceRead(d *schema.ResourceData, meta interface{ vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect private virtual interface (%s) not found, removing from state", d.Id()) @@ -245,11 +245,11 @@ func resourcePrivateVirtualInterfaceRead(d *schema.ResourceData, meta interface{ func resourcePrivateVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err + return err // nosemgrep:bare-error-returns } if err := privateVirtualInterfaceWaitUntilAvailable(meta.(*conns.AWSClient).DirectConnectConn(), d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourcePrivateVirtualInterfaceRead(d, meta) diff --git a/internal/service/directconnect/public_virtual_interface.go b/internal/service/directconnect/public_virtual_interface.go index 78421a0db83..b805c3f5c8e 100644 --- a/internal/service/directconnect/public_virtual_interface.go +++ b/internal/service/directconnect/public_virtual_interface.go @@ -150,7 +150,7 @@ func resourcePublicVirtualInterfaceCreate(d *schema.ResourceData, meta interface d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := publicVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourcePublicVirtualInterfaceRead(d, meta) @@ -163,7 +163,7 @@ func resourcePublicVirtualInterfaceRead(d *schema.ResourceData, meta interface{} vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect virtual interface (%s) not found, removing from state", d.Id()) @@ -215,7 +215,7 @@ func resourcePublicVirtualInterfaceRead(d *schema.ResourceData, meta interface{} func resourcePublicVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourcePublicVirtualInterfaceRead(d, meta) diff --git a/internal/service/directconnect/transit_virtual_interface.go b/internal/service/directconnect/transit_virtual_interface.go index ee2c63b58a7..e88f4512051 100644 --- a/internal/service/directconnect/transit_virtual_interface.go +++ b/internal/service/directconnect/transit_virtual_interface.go @@ -159,7 +159,7 @@ func resourceTransitVirtualInterfaceCreate(d *schema.ResourceData, meta interfac d.SetId(aws.StringValue(resp.VirtualInterface.VirtualInterfaceId)) if err := transitVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceTransitVirtualInterfaceRead(d, meta) @@ -172,7 +172,7 @@ func resourceTransitVirtualInterfaceRead(d *schema.ResourceData, meta interface{ vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect transit virtual interface (%s) not found, removing from state", d.Id()) @@ -225,11 +225,11 @@ func resourceTransitVirtualInterfaceRead(d *schema.ResourceData, meta interface{ func resourceTransitVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err + return err // nosemgrep:bare-error-returns } if err := transitVirtualInterfaceWaitUntilAvailable(meta.(*conns.AWSClient).DirectConnectConn(), d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } return resourceTransitVirtualInterfaceRead(d, meta) diff --git a/internal/service/directconnect/vif.go b/internal/service/directconnect/vif.go index 88efd1521e2..ffbbe267742 100644 --- a/internal/service/directconnect/vif.go +++ b/internal/service/directconnect/vif.go @@ -16,7 +16,7 @@ import ( func virtualInterfaceRead(id string, conn *directconnect.DirectConnect) (*directconnect.VirtualInterface, error) { resp, state, err := virtualInterfaceStateRefresh(conn, id)() if err != nil { - return nil, fmt.Errorf("error reading Direct Connect virtual interface (%s): %s", id, err) + return nil, fmt.Errorf("reading Direct Connect virtual interface (%s): %s", id, err) } if state == directconnect.VirtualInterfaceStateDeleted { return nil, nil @@ -36,7 +36,7 @@ func virtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Modifying Direct Connect virtual interface attributes: %s", req) _, err := conn.UpdateVirtualInterfaceAttributes(req) if err != nil { - return fmt.Errorf("error modifying Direct Connect virtual interface (%s) attributes: %s", d.Id(), err) + return fmt.Errorf("modifying Direct Connect virtual interface (%s) attributes: %s", d.Id(), err) } } if d.HasChange("sitelink_enabled") { @@ -47,7 +47,7 @@ func virtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Modifying Direct Connect virtual interface attributes: %s", req) _, err := conn.UpdateVirtualInterfaceAttributes(req) if err != nil { - return fmt.Errorf("error modifying Direct Connect virtual interface (%s) attributes: %s", d.Id(), err) + return fmt.Errorf("modifying Direct Connect virtual interface (%s) attributes: %s", d.Id(), err) } } @@ -56,7 +56,7 @@ func virtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, arn, o, n); err != nil { - return fmt.Errorf("error updating Direct Connect virtual interface (%s) tags: %s", arn, err) + return fmt.Errorf("updating Direct Connect virtual interface (%s) tags: %s", arn, err) } } @@ -74,7 +74,7 @@ func virtualInterfaceDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrMessageContains(err, directconnect.ErrCodeClientException, "does not exist") { return nil } - return fmt.Errorf("error deleting Direct Connect virtual interface (%s): %s", d.Id(), err) + return fmt.Errorf("deleting Direct Connect virtual interface (%s): %s", d.Id(), err) } deleteStateConf := &resource.StateChangeConf{ @@ -97,7 +97,7 @@ func virtualInterfaceDelete(d *schema.ResourceData, meta interface{}) error { } _, err = deleteStateConf.WaitForState() if err != nil { - return fmt.Errorf("error waiting for Direct Connect virtual interface (%s) to be deleted: %s", d.Id(), err) + return fmt.Errorf("waiting for Direct Connect virtual interface (%s) to be deleted: %s", d.Id(), err) } return nil @@ -137,7 +137,7 @@ func virtualInterfaceWaitUntilAvailable(conn *directconnect.DirectConnect, vifId MinTimeout: 5 * time.Second, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("error waiting for Direct Connect virtual interface (%s) to become available: %s", vifId, err) + return fmt.Errorf("waiting for Direct Connect virtual interface (%s) to become available: %s", vifId, err) } return nil From 2b19b4a1333e480719166793e3fdbdd2cb8f5798 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:51:18 -0800 Subject: [PATCH 071/106] Fixes bare errors in `deploy` --- internal/service/deploy/app.go | 6 ++---- internal/service/deploy/deployment_config.go | 16 +++++++++------- internal/service/deploy/deployment_group.go | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/internal/service/deploy/app.go b/internal/service/deploy/app.go index be43764e067..1b84406e326 100644 --- a/internal/service/deploy/app.go +++ b/internal/service/deploy/app.go @@ -108,9 +108,8 @@ func resourceAppCreate(d *schema.ResourceData, meta interface{}) error { Tags: Tags(tags.IgnoreAWS()), }) if err != nil { - return err + return fmt.Errorf("creating CodeDeploy Application (%s): %w", application, err) } - log.Printf("[DEBUG] CodeDeploy application %s created", *resp.ApplicationId) // Despite giving the application a unique ID, AWS doesn't actually use // it in API calls. Use it and the app name to identify the resource in @@ -227,8 +226,7 @@ func resourceAppDelete(d *schema.ResourceData, meta interface{}) error { return nil } - log.Printf("[ERROR] Error deleting CodeDeploy application: %s", err) - return err + return fmt.Errorf("deleting CodeDeploy Application (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/deploy/deployment_config.go b/internal/service/deploy/deployment_config.go index 65891736433..b8781a23361 100644 --- a/internal/service/deploy/deployment_config.go +++ b/internal/service/deploy/deployment_config.go @@ -151,7 +151,7 @@ func resourceDeploymentConfigCreate(d *schema.ResourceData, meta interface{}) er _, err := conn.CreateDeploymentConfig(input) if err != nil { - return err + return fmt.Errorf("creating CodeDeploy Deployment Config (%s): %w", d.Get("deployment_config_name").(string), err) } d.SetId(d.Get("deployment_config_name").(string)) @@ -175,19 +175,19 @@ func resourceDeploymentConfigRead(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("finding CodeDeploy Deployment Config (%s): %w", d.Id(), err) + return fmt.Errorf("reading CodeDeploy Deployment Config (%s): %w", d.Id(), err) } if resp.DeploymentConfigInfo == nil { - return fmt.Errorf("Cannot find DeploymentConfig %q", d.Id()) + return fmt.Errorf("reading CodeDeploy Deployment Config (%s): empty result", d.Id()) } if err := d.Set("minimum_healthy_hosts", flattenMinimumHealthHostsConfig(resp.DeploymentConfigInfo.MinimumHealthyHosts)); err != nil { - return err + return fmt.Errorf("reading CodeDeploy Deployment Config (%s): %w", d.Id(), err) } if err := d.Set("traffic_routing_config", flattenTrafficRoutingConfig(resp.DeploymentConfigInfo.TrafficRoutingConfig)); err != nil { - return err + return fmt.Errorf("reading CodeDeploy Deployment Config (%s): %w", d.Id(), err) } d.Set("deployment_config_id", resp.DeploymentConfigInfo.DeploymentConfigId) @@ -204,8 +204,10 @@ func resourceDeploymentConfigDelete(d *schema.ResourceData, meta interface{}) er DeploymentConfigName: aws.String(d.Id()), } - _, err := conn.DeleteDeploymentConfig(input) - return err + if _, err := conn.DeleteDeploymentConfig(input); err != nil { + return fmt.Errorf("deleting CodeDeploy Deployment Config (%s): %w", d.Id(), err) + } + return nil } func expandMinimumHealthHostsConfig(d *schema.ResourceData) *codedeploy.MinimumHealthyHosts { diff --git a/internal/service/deploy/deployment_group.go b/internal/service/deploy/deployment_group.go index 141caeff867..5f528145cc7 100644 --- a/internal/service/deploy/deployment_group.go +++ b/internal/service/deploy/deployment_group.go @@ -833,7 +833,7 @@ func resourceDeploymentGroupDelete(d *schema.ResourceData, meta interface{}) err if tfawserr.ErrCodeEquals(err, codedeploy.ErrCodeDeploymentGroupDoesNotExistException) { return nil } - return err + return fmt.Errorf("deleting CodeDeploy Deployment Group (%s): %w", d.Id(), err) } return nil From ec0296c44dcdcc0028ec70afb258ebd49c4ad41d Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:51:31 -0800 Subject: [PATCH 072/106] Fixes bare errors in `dax` --- internal/service/dax/cluster.go | 10 +++++----- internal/service/dax/parameter_group.go | 11 ++++++----- internal/service/dax/subnet_group.go | 11 ++++++----- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/internal/service/dax/cluster.go b/internal/service/dax/cluster.go index 7a96e1af779..b7d6c615f35 100644 --- a/internal/service/dax/cluster.go +++ b/internal/service/dax/cluster.go @@ -312,7 +312,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { return nil } - return err + return fmt.Errorf("reading DAX cluster (%s): %s", d.Id(), err) } if len(res.Clusters) == 0 { @@ -352,7 +352,7 @@ func resourceClusterRead(d *schema.ResourceData, meta interface{}) error { } if err := setClusterNodeData(d, c); err != nil { - return err + return fmt.Errorf("reading DAX cluster (%s): %s", d.Id(), err) } if err := d.Set("server_side_encryption", flattenEncryptAtRestOptions(c.SSEDescription)); err != nil { @@ -491,13 +491,13 @@ func setClusterNodeData(d *schema.ResourceData, c *dax.Cluster) error { copy(sortedNodes, c.Nodes) sort.Sort(byNodeId(sortedNodes)) - nodeDate := make([]map[string]interface{}, 0, len(sortedNodes)) + nodeData := make([]map[string]interface{}, 0, len(sortedNodes)) for _, node := range sortedNodes { if node.NodeId == nil || node.Endpoint == nil || node.Endpoint.Address == nil || node.Endpoint.Port == nil || node.AvailabilityZone == nil { return fmt.Errorf("Unexpected nil pointer in: %s", node) } - nodeDate = append(nodeDate, map[string]interface{}{ + nodeData = append(nodeData, map[string]interface{}{ "id": aws.StringValue(node.NodeId), "address": aws.StringValue(node.Endpoint.Address), "port": aws.Int64Value(node.Endpoint.Port), @@ -505,7 +505,7 @@ func setClusterNodeData(d *schema.ResourceData, c *dax.Cluster) error { }) } - return d.Set("nodes", nodeDate) + return d.Set("nodes", nodeData) } type byNodeId []*dax.Node diff --git a/internal/service/dax/parameter_group.go b/internal/service/dax/parameter_group.go index ca15d7ee4e5..28c98db1851 100644 --- a/internal/service/dax/parameter_group.go +++ b/internal/service/dax/parameter_group.go @@ -1,6 +1,7 @@ package dax import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" @@ -65,7 +66,7 @@ func resourceParameterGroupCreate(d *schema.ResourceData, meta interface{}) erro _, err := conn.CreateParameterGroup(input) if err != nil { - return err + return fmt.Errorf("creating DAX Parameter Group (%s): %w", d.Get("name").(string), err) } d.SetId(d.Get("name").(string)) @@ -88,7 +89,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error d.SetId("") return nil } - return err + return fmt.Errorf("reading DAX Parameter Group (%s): %w", d.Id(), err) } if len(resp.ParameterGroups) == 0 { @@ -108,7 +109,7 @@ func resourceParameterGroupRead(d *schema.ResourceData, meta interface{}) error d.SetId("") return nil } - return err + return fmt.Errorf("reading DAX Parameter Group (%s): %w", d.Id(), err) } d.Set("name", pg.ParameterGroupName) @@ -137,7 +138,7 @@ func resourceParameterGroupUpdate(d *schema.ResourceData, meta interface{}) erro _, err := conn.UpdateParameterGroup(input) if err != nil { - return err + return fmt.Errorf("updating DAX Parameter Group (%s): %w", d.Id(), err) } return resourceParameterGroupRead(d, meta) @@ -155,7 +156,7 @@ func resourceParameterGroupDelete(d *schema.ResourceData, meta interface{}) erro if tfawserr.ErrCodeEquals(err, dax.ErrCodeParameterGroupNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting DAX Parameter Group (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/dax/subnet_group.go b/internal/service/dax/subnet_group.go index f97e273729b..8b846841511 100644 --- a/internal/service/dax/subnet_group.go +++ b/internal/service/dax/subnet_group.go @@ -1,6 +1,7 @@ package dax import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" @@ -59,7 +60,7 @@ func resourceSubnetGroupCreate(d *schema.ResourceData, meta interface{}) error { _, err := conn.CreateSubnetGroup(input) if err != nil { - return err + return fmt.Errorf("creating DAX Subnet Group (%s): %w", d.Get("name").(string), err) } d.SetId(d.Get("name").(string)) @@ -74,11 +75,11 @@ func resourceSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { if tfawserr.ErrCodeEquals(err, dax.ErrCodeSubnetGroupNotFoundFault) { - log.Printf("[WARN] DAX SubnetGroup %q not found, removing from state", d.Id()) + log.Printf("[WARN] DAX Subnet Group %q not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading DAX Subnet Group (%s): %w", d.Id(), err) } sg := resp.SubnetGroups[0] @@ -110,7 +111,7 @@ func resourceSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.UpdateSubnetGroup(input) if err != nil { - return err + return fmt.Errorf("updating DAX Subnet Group (%s): %w", d.Id(), err) } return resourceSubnetGroupRead(d, meta) @@ -128,7 +129,7 @@ func resourceSubnetGroupDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, dax.ErrCodeSubnetGroupNotFoundFault) { return nil } - return err + return fmt.Errorf("deleting DAX Subnet Group (%s): %w", d.Id(), err) } return nil From 4d9340ee5f41df6daf3e9261861063bd89097197 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:51:47 -0800 Subject: [PATCH 073/106] Fixes bare errors in `datasync` --- internal/service/datasync/location_efs.go | 4 ++-- internal/service/datasync/location_fsx_lustre_file_system.go | 4 ++-- internal/service/datasync/location_fsx_openzfs_file_system.go | 4 ++-- internal/service/datasync/location_fsx_windows_file_system.go | 4 ++-- internal/service/datasync/location_hdfs.go | 4 ++-- internal/service/datasync/location_nfs.go | 4 ++-- internal/service/datasync/location_s3.go | 4 ++-- internal/service/datasync/location_smb.go | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/internal/service/datasync/location_efs.go b/internal/service/datasync/location_efs.go index b6e0bbea828..2a48bd5b22b 100644 --- a/internal/service/datasync/location_efs.go +++ b/internal/service/datasync/location_efs.go @@ -162,13 +162,13 @@ func resourceLocationEFSRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DataSync Location EFS (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location EFS (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location EFS (%s): %w", d.Id(), err) } d.Set("arn", output.LocationArn) diff --git a/internal/service/datasync/location_fsx_lustre_file_system.go b/internal/service/datasync/location_fsx_lustre_file_system.go index 6586ef53714..94eb0204631 100644 --- a/internal/service/datasync/location_fsx_lustre_file_system.go +++ b/internal/service/datasync/location_fsx_lustre_file_system.go @@ -127,13 +127,13 @@ func resourceLocationFSxLustreFileSystemRead(d *schema.ResourceData, meta interf } if err != nil { - return fmt.Errorf("error reading DataSync Location Fsx Lustre (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location Fsx Lustre (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location Fsx Lustre (%s): %w", d.Id(), err) } d.Set("arn", output.LocationArn) diff --git a/internal/service/datasync/location_fsx_openzfs_file_system.go b/internal/service/datasync/location_fsx_openzfs_file_system.go index c554733730c..8cd892508a3 100644 --- a/internal/service/datasync/location_fsx_openzfs_file_system.go +++ b/internal/service/datasync/location_fsx_openzfs_file_system.go @@ -165,13 +165,13 @@ func resourceLocationFSxOpenZFSFileSystemRead(d *schema.ResourceData, meta inter } if err != nil { - return fmt.Errorf("error reading DataSync Location Fsx OpenZfs (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location Fsx OpenZfs (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location Fsx OpenZfs (%s): %w", d.Id(), err) } d.Set("arn", output.LocationArn) diff --git a/internal/service/datasync/location_fsx_windows_file_system.go b/internal/service/datasync/location_fsx_windows_file_system.go index 974936ed239..3ce9923e15f 100644 --- a/internal/service/datasync/location_fsx_windows_file_system.go +++ b/internal/service/datasync/location_fsx_windows_file_system.go @@ -155,13 +155,13 @@ func resourceLocationFSxWindowsFileSystemRead(d *schema.ResourceData, meta inter } if err != nil { - return fmt.Errorf("error reading DataSync Location Fsx Windows (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location Fsx Windows (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location Fsx Windows (%s): %w", d.Id(), err) } d.Set("arn", output.LocationArn) diff --git a/internal/service/datasync/location_hdfs.go b/internal/service/datasync/location_hdfs.go index a5604aa227a..344d400e753 100644 --- a/internal/service/datasync/location_hdfs.go +++ b/internal/service/datasync/location_hdfs.go @@ -218,13 +218,13 @@ func resourceLocationHDFSRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DataSync Location HDFS (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location HDFS (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location HDFS (%s): %w", d.Id(), err) } d.Set("agent_arns", flex.FlattenStringSet(output.AgentArns)) diff --git a/internal/service/datasync/location_nfs.go b/internal/service/datasync/location_nfs.go index fcbc34caf1b..e3d8b550c79 100644 --- a/internal/service/datasync/location_nfs.go +++ b/internal/service/datasync/location_nfs.go @@ -145,13 +145,13 @@ func resourceLocationNFSRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DataSync Location NFS (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location NFS (%s): %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location NFS (%s): %w", d.Id(), err) } d.Set("arn", output.LocationArn) diff --git a/internal/service/datasync/location_s3.go b/internal/service/datasync/location_s3.go index 90448be696c..71b872cf55c 100644 --- a/internal/service/datasync/location_s3.go +++ b/internal/service/datasync/location_s3.go @@ -176,13 +176,13 @@ func resourceLocationS3Read(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DataSync Location S3 (%s): %s", d.Id(), err) + return fmt.Errorf("reading DataSync Location S3 (%s): %s", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location S3 (%s): %s", d.Id(), err) } d.Set("agent_arns", flex.FlattenStringSet(output.AgentArns)) diff --git a/internal/service/datasync/location_smb.go b/internal/service/datasync/location_smb.go index a1dbde158cc..75f6aba1656 100644 --- a/internal/service/datasync/location_smb.go +++ b/internal/service/datasync/location_smb.go @@ -164,13 +164,13 @@ func resourceLocationSMBRead(d *schema.ResourceData, meta interface{}) error { tagsOutput, err := conn.ListTagsForResource(tagsInput) if err != nil { - return fmt.Errorf("error reading DataSync Location SMB (%s) tags: %w", d.Id(), err) + return fmt.Errorf("reading DataSync Location SMB (%s) tags: %w", d.Id(), err) } subdirectory, err := SubdirectoryFromLocationURI(aws.StringValue(output.LocationUri)) if err != nil { - return err + return fmt.Errorf("reading DataSync Location SMB (%s) tags: %w", d.Id(), err) } d.Set("agent_arns", flex.FlattenStringSet(output.AgentArns)) From 3d981583eaeb599a3c40f83db43d261c7dc54a68 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:52:00 -0800 Subject: [PATCH 074/106] Fixes bare errors in `dataexchange` --- internal/service/dataexchange/revision.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/dataexchange/revision.go b/internal/service/dataexchange/revision.go index 62a01eeddd7..ab52bf21275 100644 --- a/internal/service/dataexchange/revision.go +++ b/internal/service/dataexchange/revision.go @@ -83,7 +83,7 @@ func resourceRevisionRead(d *schema.ResourceData, meta interface{}) error { dataSetId, revisionId, err := RevisionParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading DataExchange Revision (%s): %w", d.Id(), err) } revision, err := FindRevisionById(conn, dataSetId, revisionId) @@ -95,7 +95,7 @@ func resourceRevisionRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading DataExchange Revision (%s): %w", d.Id(), err) + return fmt.Errorf("reading DataExchange Revision (%s): %w", d.Id(), err) } d.Set("data_set_id", revision.DataSetId) From 8990c49af0c537b169c2cffb6e2ea5342dcb43f9 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:52:15 -0800 Subject: [PATCH 075/106] Fixes bare errors in `cur` --- internal/service/cur/report_definition.go | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/internal/service/cur/report_definition.go b/internal/service/cur/report_definition.go index f0ad9f5b683..23d124416dd 100644 --- a/internal/service/cur/report_definition.go +++ b/internal/service/cur/report_definition.go @@ -103,6 +103,7 @@ func ResourceReportDefinition() *schema.Resource { func resourceReportDefinitionCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).CURConn() + reportName := d.Get("report_name").(string) additionalArtifacts := flex.ExpandStringSet(d.Get("additional_artifacts").(*schema.Set)) compression := d.Get("compression").(string) format := d.Get("format").(string) @@ -123,11 +124,9 @@ func resourceReportDefinitionCreate(d *schema.ResourceData, meta interface{}) er ) if err != nil { - return err + return fmt.Errorf("creating Cost And Usage Report Definition (%s): %w", reportName, err) } - reportName := d.Get("report_name").(string) - reportDefinition := &cur.ReportDefinition{ ReportName: aws.String(reportName), TimeUnit: aws.String(d.Get("time_unit").(string)), @@ -145,12 +144,11 @@ func resourceReportDefinitionCreate(d *schema.ResourceData, meta interface{}) er reportDefinitionInput := &cur.PutReportDefinitionInput{ ReportDefinition: reportDefinition, } - log.Printf("[DEBUG] Creating AWS Cost and Usage Report Definition : %v", reportDefinitionInput) _, err = conn.PutReportDefinition(reportDefinitionInput) if err != nil { - return fmt.Errorf("error creating Cost And Usage Report Definition (%s): %w", reportName, err) + return fmt.Errorf("creating Cost And Usage Report Definition (%s): %w", reportName, err) } d.SetId(reportName) @@ -226,7 +224,7 @@ func resourceReportDefinitionUpdate(d *schema.ResourceData, meta interface{}) er ) if err != nil { - return err + return fmt.Errorf("updating Cost And Usage Report Definition (%s): %w", d.Id(), err) } reportName := d.Get("report_name").(string) @@ -245,10 +243,6 @@ func resourceReportDefinitionUpdate(d *schema.ResourceData, meta interface{}) er ReportVersioning: aws.String(reportVersioning), } - if err != nil { - return err - } - reportDefinitionInput := &cur.ModifyReportDefinitionInput{ ReportDefinition: reportDefinition, ReportName: aws.String(reportName), @@ -257,7 +251,7 @@ func resourceReportDefinitionUpdate(d *schema.ResourceData, meta interface{}) er _, err = conn.ModifyReportDefinition(reportDefinitionInput) if err != nil { - return fmt.Errorf("error updating Cost And Usage Report Definition (%s): %w", d.Id(), err) + return fmt.Errorf("updating Cost And Usage Report Definition (%s): %w", d.Id(), err) } return resourceReportDefinitionRead(d, meta) From 7fcf2983786afd89cd711a048e60aa0d7bc8aaac Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:52:27 -0800 Subject: [PATCH 076/106] Fixes bare errors in `connect` --- internal/service/connect/hours_of_operation.go | 2 +- internal/service/connect/queue.go | 14 +++++++------- internal/service/connect/quick_connect.go | 4 ++-- internal/service/connect/routing_profile.go | 10 +++++----- internal/service/connect/security_profile.go | 2 +- internal/service/connect/user.go | 10 +++++----- internal/service/connect/user_hierarchy_group.go | 2 +- 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/internal/service/connect/hours_of_operation.go b/internal/service/connect/hours_of_operation.go index d1d5b4faf4b..88988cb8984 100644 --- a/internal/service/connect/hours_of_operation.go +++ b/internal/service/connect/hours_of_operation.go @@ -239,7 +239,7 @@ func resourceHoursOfOperationUpdate(ctx context.Context, d *schema.ResourceData, TimeZone: aws.String(d.Get("time_zone").(string)), }) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating HoursOfOperation (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating HoursOfOperation (%s): %w", d.Id(), err)) } } diff --git a/internal/service/connect/queue.go b/internal/service/connect/queue.go index 1b035d88c99..575bf8b097c 100644 --- a/internal/service/connect/queue.go +++ b/internal/service/connect/queue.go @@ -259,7 +259,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter _, err = conn.UpdateQueueHoursOfOperationWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queue Hours of Operation (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queue Hours of Operation (%s): %w", d.Id(), err)) } } @@ -273,7 +273,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter _, err = conn.UpdateQueueMaxContactsWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queue Max Contacts (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queue Max Contacts (%s): %w", d.Id(), err)) } } @@ -288,7 +288,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter _, err = conn.UpdateQueueNameWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queue Name and/or Description (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queue Name and/or Description (%s): %w", d.Id(), err)) } } @@ -302,7 +302,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter _, err = conn.UpdateQueueOutboundCallerConfigWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queue Outbound Caller Config (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queue Outbound Caller Config (%s): %w", d.Id(), err)) } } @@ -316,7 +316,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter _, err = conn.UpdateQueueStatusWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queue Status (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queue Status (%s): %w", d.Id(), err)) } } @@ -331,7 +331,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter input.QuickConnectIds = flex.ExpandStringSet(v.(*schema.Set)) _, err = conn.DisassociateQueueQuickConnectsWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queues Quick Connect IDs, specifically disassociating quick connects from queue (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queues Quick Connect IDs, specifically disassociating quick connects from queue (%s): %w", d.Id(), err)) } } @@ -344,7 +344,7 @@ func resourceQueueUpdate(ctx context.Context, d *schema.ResourceData, meta inter input.QuickConnectIds = flex.ExpandStringSet(v.(*schema.Set)) _, err = conn.AssociateQueueQuickConnectsWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating Queues Quick Connect IDs, specifically associating quick connects to queue (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating Queues Quick Connect IDs, specifically associating quick connects to queue (%s): %w", d.Id(), err)) } } } diff --git a/internal/service/connect/quick_connect.go b/internal/service/connect/quick_connect.go index 1dbbd9628a2..5a5ae43ade5 100644 --- a/internal/service/connect/quick_connect.go +++ b/internal/service/connect/quick_connect.go @@ -252,7 +252,7 @@ func resourceQuickConnectUpdate(ctx context.Context, d *schema.ResourceData, met _, err = conn.UpdateQuickConnectNameWithContext(ctx, inputNameDesc) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating QuickConnect Name (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating QuickConnect Name (%s): %w", d.Id(), err)) } } @@ -268,7 +268,7 @@ func resourceQuickConnectUpdate(ctx context.Context, d *schema.ResourceData, met inputConfig.QuickConnectConfig = quickConnectConfig _, err = conn.UpdateQuickConnectConfigWithContext(ctx, inputConfig) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating QuickConnect (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating QuickConnect (%s): %w", d.Id(), err)) } } diff --git a/internal/service/connect/routing_profile.go b/internal/service/connect/routing_profile.go index 835cba6576c..6810fcda44b 100644 --- a/internal/service/connect/routing_profile.go +++ b/internal/service/connect/routing_profile.go @@ -286,7 +286,7 @@ func resourceRoutingProfileUpdate(ctx context.Context, d *schema.ResourceData, m inputConcurrency.MediaConcurrencies = mediaConcurrencies _, err = conn.UpdateRoutingProfileConcurrencyWithContext(ctx, inputConcurrency) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating RoutingProfile Media Concurrency (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating RoutingProfile Media Concurrency (%s): %w", d.Id(), err)) } } @@ -301,7 +301,7 @@ func resourceRoutingProfileUpdate(ctx context.Context, d *schema.ResourceData, m _, err = conn.UpdateRoutingProfileDefaultOutboundQueueWithContext(ctx, inputDefaultOutboundQueue) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating RoutingProfile Default Outbound Queue ID (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating RoutingProfile Default Outbound Queue ID (%s): %w", d.Id(), err)) } } @@ -317,7 +317,7 @@ func resourceRoutingProfileUpdate(ctx context.Context, d *schema.ResourceData, m _, err = conn.UpdateRoutingProfileNameWithContext(ctx, inputNameDesc) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating RoutingProfile Name (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating RoutingProfile Name (%s): %w", d.Id(), err)) } } @@ -345,7 +345,7 @@ func resourceRoutingProfileUpdate(ctx context.Context, d *schema.ResourceData, m inputQueueDisassociate.QueueReferences = currentAssociatedQueueReferences _, err = conn.DisassociateRoutingProfileQueuesWithContext(ctx, inputQueueDisassociate) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating RoutingProfile Queue Configs, specifically disassociating queues from routing profile (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating RoutingProfile Queue Configs, specifically disassociating queues from routing profile (%s): %w", d.Id(), err)) } } // re-associate the queues @@ -354,7 +354,7 @@ func resourceRoutingProfileUpdate(ctx context.Context, d *schema.ResourceData, m inputQueueAssociate.QueueConfigs = updatedQueueConfigs _, err = conn.AssociateRoutingProfileQueuesWithContext(ctx, inputQueueAssociate) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating RoutingProfile Queue Configs, specifically associating queues to routing profile (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating RoutingProfile Queue Configs, specifically associating queues to routing profile (%s): %w", d.Id(), err)) } } } diff --git a/internal/service/connect/security_profile.go b/internal/service/connect/security_profile.go index e4452bce0cf..bdc8fcdf93d 100644 --- a/internal/service/connect/security_profile.go +++ b/internal/service/connect/security_profile.go @@ -199,7 +199,7 @@ func resourceSecurityProfileUpdate(ctx context.Context, d *schema.ResourceData, _, err = conn.UpdateSecurityProfileWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating SecurityProfile (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating SecurityProfile (%s): %w", d.Id(), err)) } if d.HasChange("tags_all") { diff --git a/internal/service/connect/user.go b/internal/service/connect/user.go index 41f6d5fa729..17e24fe6ec1 100644 --- a/internal/service/connect/user.go +++ b/internal/service/connect/user.go @@ -284,7 +284,7 @@ func resourceUserUpdate(ctx context.Context, d *schema.ResourceData, meta interf _, err = conn.UpdateUserHierarchyWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating User hierarchy_group_id (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating User hierarchy_group_id (%s): %w", d.Id(), err)) } } @@ -299,7 +299,7 @@ func resourceUserUpdate(ctx context.Context, d *schema.ResourceData, meta interf _, err = conn.UpdateUserIdentityInfoWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating User identity_info (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating User identity_info (%s): %w", d.Id(), err)) } } @@ -314,7 +314,7 @@ func resourceUserUpdate(ctx context.Context, d *schema.ResourceData, meta interf _, err = conn.UpdateUserPhoneConfigWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating User phone_config (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating User phone_config (%s): %w", d.Id(), err)) } } @@ -329,7 +329,7 @@ func resourceUserUpdate(ctx context.Context, d *schema.ResourceData, meta interf _, err = conn.UpdateUserRoutingProfileWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating User routing_profile_id (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating User routing_profile_id (%s): %w", d.Id(), err)) } } @@ -344,7 +344,7 @@ func resourceUserUpdate(ctx context.Context, d *schema.ResourceData, meta interf _, err = conn.UpdateUserSecurityProfilesWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating User security_profile_ids (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating User security_profile_ids (%s): %w", d.Id(), err)) } } diff --git a/internal/service/connect/user_hierarchy_group.go b/internal/service/connect/user_hierarchy_group.go index f4935e6d239..7c8af7d1720 100644 --- a/internal/service/connect/user_hierarchy_group.go +++ b/internal/service/connect/user_hierarchy_group.go @@ -220,7 +220,7 @@ func resourceUserHierarchyGroupUpdate(ctx context.Context, d *schema.ResourceDat Name: aws.String(d.Get("name").(string)), }) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating User Hierarchy Group (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating User Hierarchy Group (%s): %w", d.Id(), err)) } } From c1ab28095c7d05e001e3a8687067fa74ea58e426 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:52:43 -0800 Subject: [PATCH 077/106] Fixes bare errors in `configservice` --- internal/service/configservice/aggregate_authorization.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/configservice/aggregate_authorization.go b/internal/service/configservice/aggregate_authorization.go index 56d3fce1fd8..54cb6e1f76d 100644 --- a/internal/service/configservice/aggregate_authorization.go +++ b/internal/service/configservice/aggregate_authorization.go @@ -82,7 +82,7 @@ func resourceAggregateAuthorizationRead(d *schema.ResourceData, meta interface{} accountId, region, err := AggregateAuthorizationParseID(d.Id()) if err != nil { - return err + return create.Error(names.ConfigService, create.ErrActionReading, ResNameAggregateAuthorization, d.Id(), err) } d.Set("account_id", accountId) @@ -158,7 +158,7 @@ func resourceAggregateAuthorizationDelete(d *schema.ResourceData, meta interface accountId, region, err := AggregateAuthorizationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Config Aggregate Authorization (%s): %s", d.Id(), err) } req := &configservice.DeleteAggregationAuthorizationInput{ @@ -168,7 +168,7 @@ func resourceAggregateAuthorizationDelete(d *schema.ResourceData, meta interface _, err = conn.DeleteAggregationAuthorization(req) if err != nil { - return fmt.Errorf("Error deleting aggregate authorization: %s", err) + return fmt.Errorf("deleting Config Aggregate Authorization (%s): %s", d.Id(), err) } return nil From ef2610cdbf94f6b96f521b41e16c8fb1d9bd278e Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 10:53:01 -0800 Subject: [PATCH 078/106] Fixes bare errors in `cognitoidp` --- internal/service/cognitoidp/identity_provider.go | 10 +++++----- internal/service/cognitoidp/resource_server.go | 12 +++++------- internal/service/cognitoidp/risk_configuration.go | 13 ++++++++----- internal/service/cognitoidp/user_in_group.go | 2 +- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/internal/service/cognitoidp/identity_provider.go b/internal/service/cognitoidp/identity_provider.go index 8cbd62cdc07..770fe5c8857 100644 --- a/internal/service/cognitoidp/identity_provider.go +++ b/internal/service/cognitoidp/identity_provider.go @@ -124,7 +124,7 @@ func resourceIdentityProviderRead(d *schema.ResourceData, meta interface{}) erro userPoolID, providerName, err := DecodeIdentityProviderID(d.Id()) if err != nil { - return err + return create.Error(names.CognitoIDP, create.ErrActionReading, ResNameIdentityProvider, d.Id(), err) } ret, err := conn.DescribeIdentityProvider(&cognitoidentityprovider.DescribeIdentityProviderInput{ @@ -178,7 +178,7 @@ func resourceIdentityProviderUpdate(d *schema.ResourceData, meta interface{}) er userPoolID, providerName, err := DecodeIdentityProviderID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Cognito Identity Provider (%s): %w", d.Id(), err) } params := &cognitoidentityprovider.UpdateIdentityProviderInput{ @@ -200,7 +200,7 @@ func resourceIdentityProviderUpdate(d *schema.ResourceData, meta interface{}) er _, err = conn.UpdateIdentityProvider(params) if err != nil { - return fmt.Errorf("Error updating Cognito Identity Provider: %w", err) + return fmt.Errorf("updating Cognito Identity Provider (%s): %w", d.Id(), err) } return resourceIdentityProviderRead(d, meta) @@ -212,7 +212,7 @@ func resourceIdentityProviderDelete(d *schema.ResourceData, meta interface{}) er userPoolID, providerName, err := DecodeIdentityProviderID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Cognito Identity Provider (%s): %w", d.Id(), err) } _, err = conn.DeleteIdentityProvider(&cognitoidentityprovider.DeleteIdentityProviderInput{ @@ -224,7 +224,7 @@ func resourceIdentityProviderDelete(d *schema.ResourceData, meta interface{}) er if tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { return nil } - return err + return fmt.Errorf("deleting Cognito Identity Provider (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/cognitoidp/resource_server.go b/internal/service/cognitoidp/resource_server.go index d7e81160a3c..a2e94662de9 100644 --- a/internal/service/cognitoidp/resource_server.go +++ b/internal/service/cognitoidp/resource_server.go @@ -109,7 +109,7 @@ func resourceResourceServerRead(d *schema.ResourceData, meta interface{}) error userPoolID, identifier, err := DecodeResourceServerID(d.Id()) if err != nil { - return err + return create.Error(names.CognitoIDP, create.ErrActionReading, ResNameResourceServer, d.Id(), err) } params := &cognitoidentityprovider.DescribeResourceServerInput{ @@ -166,7 +166,7 @@ func resourceResourceServerUpdate(d *schema.ResourceData, meta interface{}) erro userPoolID, identifier, err := DecodeResourceServerID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Cognito Resource Server (%s): %s", d.Id(), err) } params := &cognitoidentityprovider.UpdateResourceServerInput{ @@ -180,7 +180,7 @@ func resourceResourceServerUpdate(d *schema.ResourceData, meta interface{}) erro _, err = conn.UpdateResourceServer(params) if err != nil { - return fmt.Errorf("Error updating Cognito Resource Server: %s", err) + return fmt.Errorf("updating Cognito Resource Server (%s): %s", d.Id(), err) } return resourceResourceServerRead(d, meta) @@ -191,7 +191,7 @@ func resourceResourceServerDelete(d *schema.ResourceData, meta interface{}) erro userPoolID, identifier, err := DecodeResourceServerID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Cognito Resource Server (%s): %s", d.Id(), err) } params := &cognitoidentityprovider.DeleteResourceServerInput{ @@ -199,15 +199,13 @@ func resourceResourceServerDelete(d *schema.ResourceData, meta interface{}) erro UserPoolId: aws.String(userPoolID), } - log.Printf("[DEBUG] Deleting Resource Server: %s", params) - _, err = conn.DeleteResourceServer(params) if err != nil { if tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { return nil } - return fmt.Errorf("Error deleting Resource Server: %s", err) + return fmt.Errorf("deleting Cognito Resource Server (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/cognitoidp/risk_configuration.go b/internal/service/cognitoidp/risk_configuration.go index 02f41033f05..ccc7007636c 100644 --- a/internal/service/cognitoidp/risk_configuration.go +++ b/internal/service/cognitoidp/risk_configuration.go @@ -310,6 +310,11 @@ func resourceRiskConfigurationPut(d *schema.ResourceData, meta interface{}) erro func resourceRiskConfigurationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).CognitoIDPConn() + userPoolId, clientId, err := RiskConfigurationParseID(d.Id()) + if err != nil { + return fmt.Errorf("reading Cognito Risk Configuration (%s): %w", d.Id(), err) + } + riskConfig, err := FindRiskConfigurationById(conn, d.Id()) if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, cognitoidentityprovider.ErrCodeResourceNotFoundException) { @@ -317,10 +322,8 @@ func resourceRiskConfigurationRead(d *schema.ResourceData, meta interface{}) err d.SetId("") return nil } - - userPoolId, clientId, err := RiskConfigurationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Cognito Risk Configuration (%s): %w", d.Id(), err) } d.Set("user_pool_id", userPoolId) @@ -351,7 +354,7 @@ func resourceRiskConfigurationDelete(d *schema.ResourceData, meta interface{}) e userPoolId, clientId, err := RiskConfigurationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Cognito Risk Configuration (%s): %w", d.Id(), err) } input := &cognitoidentityprovider.SetRiskConfigurationInput{ @@ -365,7 +368,7 @@ func resourceRiskConfigurationDelete(d *schema.ResourceData, meta interface{}) e _, err = conn.SetRiskConfiguration(input) if err != nil { - return fmt.Errorf("removing risk configuration: %w", err) + return fmt.Errorf("deleting Cognito Risk Configuration (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/cognitoidp/user_in_group.go b/internal/service/cognitoidp/user_in_group.go index 295549b9c9a..f38fbd75dee 100644 --- a/internal/service/cognitoidp/user_in_group.go +++ b/internal/service/cognitoidp/user_in_group.go @@ -78,7 +78,7 @@ func resourceUserInGroupRead(d *schema.ResourceData, meta interface{}) error { found, err := FindCognitoUserInGroup(conn, groupName, userPoolId, username) if err != nil { - return err + return fmt.Errorf("reading Cognito User Group Membership: %w", err) } if !found { From 107f231b4712915b03ead6b9ce80f7c4c6a21442 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:47:39 -0800 Subject: [PATCH 079/106] Fixes bare errors in `cognitoidentity` --- .../cognitoidentity/pool_provider_principal_tag.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/service/cognitoidentity/pool_provider_principal_tag.go b/internal/service/cognitoidentity/pool_provider_principal_tag.go index 692c088a63c..122ba3b9ff7 100644 --- a/internal/service/cognitoidentity/pool_provider_principal_tag.go +++ b/internal/service/cognitoidentity/pool_provider_principal_tag.go @@ -78,7 +78,7 @@ func resourcePoolProviderPrincipalTagCreate(d *schema.ResourceData, meta interfa _, err := conn.SetPrincipalTagAttributeMap(params) if err != nil { - return fmt.Errorf("Error creating Cognito Identity Provider Principal Tags: %w", err) + return fmt.Errorf("creating Cognito Identity Provider Principal Tags: %w", err) } d.SetId(fmt.Sprintf("%s:%s", poolId, providerName)) @@ -93,7 +93,7 @@ func resourcePoolProviderPrincipalTagRead(d *schema.ResourceData, meta interface poolId, providerName, err := DecodePoolProviderPrincipalTagsID(d.Id()) if err != nil { - return err + return create.Error(names.CognitoIdentity, create.ErrActionReading, ResNamePoolProviderPrincipalTag, d.Id(), err) } ret, err := conn.GetPrincipalTagAttributeMap(&cognitoidentity.GetPrincipalTagAttributeMapInput{ @@ -116,7 +116,7 @@ func resourcePoolProviderPrincipalTagRead(d *schema.ResourceData, meta interface d.Set("use_defaults", ret.UseDefaults) if err := d.Set("principal_tags", aws.StringValueMap(ret.PrincipalTags)); err != nil { - return fmt.Errorf("error setting attribute_mapping error: %w", err) + return fmt.Errorf("setting principal_tags: %w", err) } return nil @@ -128,7 +128,7 @@ func resourcePoolProviderPrincipalTagUpdate(d *schema.ResourceData, meta interfa poolId, providerName, err := DecodePoolProviderPrincipalTagsID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Cognito Identity Provider Principal Tags (%s): %w", d.Id(), err) } params := &cognitoidentity.SetPrincipalTagAttributeMapInput{ @@ -142,7 +142,7 @@ func resourcePoolProviderPrincipalTagUpdate(d *schema.ResourceData, meta interfa _, err = conn.SetPrincipalTagAttributeMap(params) if err != nil { - return fmt.Errorf("Error updating Cognito Identity Provider: %w", err) + return fmt.Errorf("updating Cognito Identity Provider Principal Tags (%s): %w", d.Id(), err) } } @@ -155,7 +155,7 @@ func resourcePoolProviderPrincipalTagDelete(d *schema.ResourceData, meta interfa poolId, providerName, err := DecodePoolProviderPrincipalTagsID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Cognito Identity Provider Principal Tags (%s): %w", d.Id(), err) } emptyList := make(map[string]string) params := &cognitoidentity.SetPrincipalTagAttributeMapInput{ @@ -171,7 +171,7 @@ func resourcePoolProviderPrincipalTagDelete(d *schema.ResourceData, meta interfa if tfawserr.ErrCodeEquals(err, cognitoidentity.ErrCodeResourceNotFoundException) { return nil } - return err + return fmt.Errorf("deleting Cognito Identity Provider Principal Tags (%s): %w", d.Id(), err) } return nil } From 2a0759142b25700c653c38e4cc276eedbd0b3dd4 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:48:03 -0800 Subject: [PATCH 080/106] Fixes bare errors in `codestarnotifications` --- .../notification_rule.go | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/service/codestarnotifications/notification_rule.go b/internal/service/codestarnotifications/notification_rule.go index cf5c250b667..cbbbe8d8525 100644 --- a/internal/service/codestarnotifications/notification_rule.go +++ b/internal/service/codestarnotifications/notification_rule.go @@ -148,7 +148,7 @@ func resourceNotificationRuleCreate(d *schema.ResourceData, meta interface{}) er res, err := conn.CreateNotificationRule(params) if err != nil { - return fmt.Errorf("error creating codestar notification rule: %s", err) + return fmt.Errorf("creating CodeStar Notification Rule: %s", err) } d.SetId(aws.StringValue(res.Arn)) @@ -182,7 +182,7 @@ func resourceNotificationRuleRead(d *schema.ResourceData, meta interface{}) erro eventTypeIds = append(eventTypeIds, aws.StringValue(et.EventTypeId)) } if err := d.Set("event_type_ids", eventTypeIds); err != nil { - return fmt.Errorf("error setting event_type_ids: %s", err) + return fmt.Errorf("setting event_type_ids: %s", err) } d.Set("name", rule.Name) d.Set("status", rule.Status) @@ -191,11 +191,11 @@ func resourceNotificationRuleRead(d *schema.ResourceData, meta interface{}) erro //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } targets := make([]map[string]interface{}, 0, len(rule.Targets)) @@ -207,7 +207,7 @@ func resourceNotificationRuleRead(d *schema.ResourceData, meta interface{}) erro }) } if err = d.Set("target", targets); err != nil { - return fmt.Errorf("error setting codestar notification target: %s", err) + return fmt.Errorf("setting CodeStar notification target: %s", err) } return nil @@ -280,20 +280,20 @@ func resourceNotificationRuleUpdate(d *schema.ResourceData, meta interface{}) er } if _, err := conn.UpdateNotificationRule(params); err != nil { - return fmt.Errorf("error updating codestar notification rule: %s", err) + return fmt.Errorf("updating CodeStar Notification Rule (%s): %s", d.Id(), err) } if d.HasChange("tags_all") { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating codestar notification rule tags: %s", err) + return fmt.Errorf("updating CodeStar Notification Rule (%s): %s", d.Id(), err) } } if d.HasChange("target") { o, n := d.GetChange("target") if err := cleanupNotificationRuleTargets(conn, o.(*schema.Set), n.(*schema.Set)); err != nil { - return err + return fmt.Errorf("updating CodeStar Notification Rule (%s): cleaning targets: %s", d.Id(), err) } } @@ -308,11 +308,11 @@ func resourceNotificationRuleDelete(d *schema.ResourceData, meta interface{}) er }) if err != nil { - return fmt.Errorf("error deleting codestar notification rule: %s", err) + return fmt.Errorf("deleting CodeStar Notification Rule: %s", err) } if err = cleanupNotificationRuleTargets(conn, d.Get("target").(*schema.Set), nil); err != nil { - return fmt.Errorf("error deleting codestar notification targets: %s", err) + return fmt.Errorf("deleting CodeStar notification targets: %s", err) } return nil From 53a425db3b8c605816669bb20546fc821ad7b8d0 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:48:19 -0800 Subject: [PATCH 081/106] Fixes bare errors in `codecommit` --- .../codecommit/approval_rule_template_association.go | 8 ++++---- internal/service/codecommit/trigger.go | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/internal/service/codecommit/approval_rule_template_association.go b/internal/service/codecommit/approval_rule_template_association.go index 20b14469612..350b805168e 100644 --- a/internal/service/codecommit/approval_rule_template_association.go +++ b/internal/service/codecommit/approval_rule_template_association.go @@ -72,7 +72,7 @@ func resourceApprovalRuleTemplateAssociationRead(d *schema.ResourceData, meta in approvalRuleTemplateName, repositoryName, err := ApprovalRuleTemplateAssociationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading CodeCommit Approval Rule Template Association (%s): %w", d.Id(), err) } err = FindApprovalRuleTemplateAssociation(conn, approvalRuleTemplateName, repositoryName) @@ -84,7 +84,7 @@ func resourceApprovalRuleTemplateAssociationRead(d *schema.ResourceData, meta in } if err != nil { - return fmt.Errorf("error reading CodeCommit Approval Rule Template Association (%s): %w", d.Id(), err) + return fmt.Errorf("reading CodeCommit Approval Rule Template Association (%s): %w", d.Id(), err) } d.Set("approval_rule_template_name", approvalRuleTemplateName) @@ -99,7 +99,7 @@ func resourceApprovalRuleTemplateAssociationDelete(d *schema.ResourceData, meta approvalRuleTemplateName, repositoryName, err := ApprovalRuleTemplateAssociationParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting CodeCommit Approval Rule Template (%s) from repository (%s): %w", approvalRuleTemplateName, repositoryName, err) } input := &codecommit.DisassociateApprovalRuleTemplateFromRepositoryInput{ @@ -114,7 +114,7 @@ func resourceApprovalRuleTemplateAssociationDelete(d *schema.ResourceData, meta } if err != nil { - return fmt.Errorf("error disassociating CodeCommit Approval Rule Template (%s) from repository (%s): %w", approvalRuleTemplateName, repositoryName, err) + return fmt.Errorf("deleting CodeCommit Approval Rule Template (%s) from repository (%s): %w", approvalRuleTemplateName, repositoryName, err) } return nil diff --git a/internal/service/codecommit/trigger.go b/internal/service/codecommit/trigger.go index 1d440c055c1..5fbf3f5dc5d 100644 --- a/internal/service/codecommit/trigger.go +++ b/internal/service/codecommit/trigger.go @@ -122,9 +122,11 @@ func resourceTriggerDelete(d *schema.ResourceData, meta interface{}) error { Triggers: []*codecommit.RepositoryTrigger{}, } - _, err := conn.PutRepositoryTriggers(input) + if _, err := conn.PutRepositoryTriggers(input); err != nil { + return fmt.Errorf("deleting CodeCommit Trigger (%s): %w", d.Id(), err) + } - return err + return nil } func expandTriggers(configured []interface{}) []*codecommit.RepositoryTrigger { From 29dfadb35926348b46c2ff51c9a8dc93d9a308ac Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:48:34 -0800 Subject: [PATCH 082/106] Fixes bare errors in `codebuild` --- internal/service/codebuild/project.go | 4 ++-- internal/service/codebuild/webhook.go | 7 ++----- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/internal/service/codebuild/project.go b/internal/service/codebuild/project.go index eba8cd2886a..40ff4a1f19e 100644 --- a/internal/service/codebuild/project.go +++ b/internal/service/codebuild/project.go @@ -1589,7 +1589,7 @@ func resourceProjectUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateProject(params) } if err != nil { - return fmt.Errorf("[ERROR] Error updating CodeBuild project (%s): %w", d.Id(), err) + return fmt.Errorf("updating CodeBuild project (%s): %w", d.Id(), err) } } @@ -1602,7 +1602,7 @@ func resourceProjectDelete(d *schema.ResourceData, meta interface{}) error { _, err := conn.DeleteProject(&codebuild.DeleteProjectInput{ Name: aws.String(d.Id()), }) - return err + return fmt.Errorf("deleting CodeBuild project (%s): %w", d.Id(), err) } func flattenProjectFileSystemLocations(apiObjects []*codebuild.ProjectFileSystemLocation) []interface{} { diff --git a/internal/service/codebuild/webhook.go b/internal/service/codebuild/webhook.go index b35bed83d34..cc788445feb 100644 --- a/internal/service/codebuild/webhook.go +++ b/internal/service/codebuild/webhook.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/codebuild" @@ -109,9 +108,7 @@ func resourceWebhookCreate(d *schema.ResourceData, meta interface{}) error { input.BranchFilter = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating CodeBuild Webhook: %s", input) resp, err := conn.CreateWebhook(input) - if err != nil { return fmt.Errorf("error creating CodeBuild Webhook: %s", err) } @@ -239,7 +236,7 @@ func resourceWebhookUpdate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return err + return fmt.Errorf("updating CodeBuild Webhook (%s): %s", d.Id(), err) } return resourceWebhookRead(d, meta) @@ -256,7 +253,7 @@ func resourceWebhookDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, codebuild.ErrCodeResourceNotFoundException) { return nil } - return err + return fmt.Errorf("deleting CodeBuild Webhook (%s): %s", d.Id(), err) } return nil From 8a7d372009f25f131505cf1ad9f5e85c132c8cc7 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:48:47 -0800 Subject: [PATCH 083/106] Fixes bare errors in `codeartifact` --- internal/service/codeartifact/domain.go | 6 +++--- internal/service/codeartifact/domain_permissions_policy.go | 6 +++--- internal/service/codeartifact/repository.go | 6 +++--- .../service/codeartifact/repository_permissions_policy.go | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/internal/service/codeartifact/domain.go b/internal/service/codeartifact/domain.go index 277467c335c..3a26124743b 100644 --- a/internal/service/codeartifact/domain.go +++ b/internal/service/codeartifact/domain.go @@ -103,7 +103,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { domainOwner, domainName, err := DecodeDomainID(d.Id()) if err != nil { - return err + return create.Error(names.CodeArtifact, create.ErrActionReading, ResNameDomain, d.Id(), err) } sm, err := conn.DescribeDomain(&codeartifact.DescribeDomainInput{ @@ -168,7 +168,7 @@ func resourceDomainDelete(d *schema.ResourceData, meta interface{}) error { domainOwner, domainName, err := DecodeDomainID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting CodeArtifact Domain (%s): %w", d.Id(), err) } input := &codeartifact.DeleteDomainInput{ @@ -183,7 +183,7 @@ func resourceDomainDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting CodeArtifact Domain (%s): %w", d.Id(), err) + return fmt.Errorf("deleting CodeArtifact Domain (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/codeartifact/domain_permissions_policy.go b/internal/service/codeartifact/domain_permissions_policy.go index c685505ee71..303ff9583b7 100644 --- a/internal/service/codeartifact/domain_permissions_policy.go +++ b/internal/service/codeartifact/domain_permissions_policy.go @@ -101,7 +101,7 @@ func resourceDomainPermissionsPolicyRead(d *schema.ResourceData, meta interface{ domainOwner, domainName, err := DecodeDomainID(d.Id()) if err != nil { - return err + return create.Error(names.CodeArtifact, create.ErrActionReading, ResNameDomainPermissionsPolicy, d.Id(), err) } dm, err := conn.GetDomainPermissionsPolicy(&codeartifact.GetDomainPermissionsPolicyInput{ @@ -146,7 +146,7 @@ func resourceDomainPermissionsPolicyDelete(d *schema.ResourceData, meta interfac domainOwner, domainName, err := DecodeDomainID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting CodeArtifact Domain Permissions Policy (%s): %w", d.Id(), err) } input := &codeartifact.DeleteDomainPermissionsPolicyInput{ @@ -161,7 +161,7 @@ func resourceDomainPermissionsPolicyDelete(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error deleting CodeArtifact Domain Permissions Policy (%s): %w", d.Id(), err) + return fmt.Errorf("deleting CodeArtifact Domain Permissions Policy (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/codeartifact/repository.go b/internal/service/codeartifact/repository.go index 1ccccbd6c60..4ace9a98a36 100644 --- a/internal/service/codeartifact/repository.go +++ b/internal/service/codeartifact/repository.go @@ -231,7 +231,7 @@ func resourceRepositoryRead(d *schema.ResourceData, meta interface{}) error { owner, domain, repo, err := DecodeRepositoryID(d.Id()) if err != nil { - return err + return create.Error(names.CodeArtifact, create.ErrActionReading, ResNameRepository, d.Id(), err) } sm, err := conn.DescribeRepository(&codeartifact.DescribeRepositoryInput{ Repository: aws.String(repo), @@ -294,7 +294,7 @@ func resourceRepositoryDelete(d *schema.ResourceData, meta interface{}) error { owner, domain, repo, err := DecodeRepositoryID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting CodeArtifact Repository (%s): %w", d.Id(), err) } input := &codeartifact.DeleteRepositoryInput{ Repository: aws.String(repo), @@ -309,7 +309,7 @@ func resourceRepositoryDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting CodeArtifact Repository (%s): %w", d.Id(), err) + return fmt.Errorf("deleting CodeArtifact Repository (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/codeartifact/repository_permissions_policy.go b/internal/service/codeartifact/repository_permissions_policy.go index f909a2b786e..1632bd71a4d 100644 --- a/internal/service/codeartifact/repository_permissions_policy.go +++ b/internal/service/codeartifact/repository_permissions_policy.go @@ -107,7 +107,7 @@ func resourceRepositoryPermissionsPolicyRead(d *schema.ResourceData, meta interf domainOwner, domainName, repoName, err := DecodeRepositoryID(d.Id()) if err != nil { - return err + return create.Error(names.CodeArtifact, create.ErrActionReading, ResNameRepositoryPermissionsPolicy, d.Id(), err) } dm, err := conn.GetRepositoryPermissionsPolicy(&codeartifact.GetRepositoryPermissionsPolicyInput{ @@ -154,7 +154,7 @@ func resourceRepositoryPermissionsPolicyDelete(d *schema.ResourceData, meta inte domainOwner, domainName, repoName, err := DecodeRepositoryID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting CodeArtifact Repository Permissions Policy (%s): %w", d.Id(), err) } input := &codeartifact.DeleteRepositoryPermissionsPolicyInput{ @@ -170,7 +170,7 @@ func resourceRepositoryPermissionsPolicyDelete(d *schema.ResourceData, meta inte } if err != nil { - return fmt.Errorf("error deleting CodeArtifact Repository Permissions Policy (%s): %w", d.Id(), err) + return fmt.Errorf("deleting CodeArtifact Repository Permissions Policy (%s): %w", d.Id(), err) } return nil From 3757dd079cc2e8ab491129888f8211e18f445fbc Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:49:03 -0800 Subject: [PATCH 084/106] Fixes bare errors in `cloudwatch` --- internal/service/cloudwatch/metric_alarm.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/cloudwatch/metric_alarm.go b/internal/service/cloudwatch/metric_alarm.go index 441d424bbdd..7b4efd6046f 100644 --- a/internal/service/cloudwatch/metric_alarm.go +++ b/internal/service/cloudwatch/metric_alarm.go @@ -300,7 +300,7 @@ func resourceMetricAlarmCreate(d *schema.ResourceData, meta interface{}) error { err := validMetricAlarm(d) if err != nil { - return err + return fmt.Errorf("creating CloudWatch Metric Alarm (%s): %w", d.Get("alarm_name").(string), err) } params := getPutMetricAlarmInput(d, meta) @@ -316,7 +316,7 @@ func resourceMetricAlarmCreate(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("failed creating CloudWatch Metric Alarm (%s): %w", d.Get("alarm_name").(string), err) + return fmt.Errorf("creating CloudWatch Metric Alarm (%s): %w", d.Get("alarm_name").(string), err) } d.SetId(d.Get("alarm_name").(string)) From 6790f9a9fbdab4af7cf311f985d12c3f256a22b2 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:49:17 -0800 Subject: [PATCH 085/106] Fixes bare errors in `cloudtrail` --- internal/service/cloudtrail/cloudtrail.go | 66 +++++++++++------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/internal/service/cloudtrail/cloudtrail.go b/internal/service/cloudtrail/cloudtrail.go index b4802ded933..e4641a4bb7e 100644 --- a/internal/service/cloudtrail/cloudtrail.go +++ b/internal/service/cloudtrail/cloudtrail.go @@ -308,7 +308,7 @@ func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { t, err = conn.CreateTrail(&input) } if err != nil { - return fmt.Errorf("Error creating CloudTrail: %w", err) + return fmt.Errorf("creating CloudTrail: %w", err) } log.Printf("[DEBUG] CloudTrail created: %s", t) @@ -319,26 +319,26 @@ func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("enable_logging"); ok && v.(bool) { err := setLogging(conn, v.(bool), d.Id()) if err != nil { - return err + return fmt.Errorf("creating CloudTrail: %w", err) } } // Event Selectors if _, ok := d.GetOk("event_selector"); ok { if err := setEventSelectors(conn, d); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if _, ok := d.GetOk("advanced_event_selector"); ok { if err := setAdvancedEventSelectors(conn, d); err != nil { - return err + return err // nosemgrep:bare-error-returns } } if _, ok := d.GetOk("insight_selector"); ok { if err := setInsightSelectors(conn, d); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -357,7 +357,7 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { // } resp, err := conn.DescribeTrails(&input) if err != nil { - return err + return create.Error(names.CloudTrail, create.ErrActionReading, ResNameTrail, d.Id(), errors.New("not found after creation")) } // CloudTrail does not return a NotFound error in the event that the Trail @@ -404,23 +404,23 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { // tags, err := ListTags(conn, arn) if err != nil { - return fmt.Errorf("error listing tags for Cloudtrail (%s): %w", arn, err) + return fmt.Errorf("listing tags for Cloudtrail (%s): %w", arn, err) } tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig) //lintignore:AWSR002 if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %w", err) + return fmt.Errorf("setting tags: %w", err) } if err := d.Set("tags_all", tags.Map()); err != nil { - return fmt.Errorf("error setting tags_all: %w", err) + return fmt.Errorf("setting tags_all: %w", err) } logstatus, err := getLoggingStatus(conn, trail.Name) if err != nil { - return err + return create.Error(names.CloudTrail, create.ErrActionReading, ResNameTrail, d.Id(), err) } d.Set("enable_logging", logstatus) @@ -429,16 +429,16 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { // TrailName: aws.String(d.Id()), }) if err != nil { - return err + return create.Error(names.CloudTrail, create.ErrActionReading, ResNameTrail, d.Id(), err) } if aws.BoolValue(trail.HasCustomEventSelectors) { if err := d.Set("event_selector", flattenEventSelector(eventSelectorsOut.EventSelectors)); err != nil { - return err + return create.Error(names.CloudTrail, create.ErrActionReading, ResNameTrail, d.Id(), err) } if err := d.Set("advanced_event_selector", flattenAdvancedEventSelector(eventSelectorsOut.AdvancedEventSelectors)); err != nil { - return err + return create.Error(names.CloudTrail, create.ErrActionReading, ResNameTrail, d.Id(), err) } } @@ -449,12 +449,12 @@ func resourceCloudTrailRead(d *schema.ResourceData, meta interface{}) error { // }) if err != nil { if !tfawserr.ErrCodeEquals(err, cloudtrail.ErrCodeInsightNotEnabledException) { - return fmt.Errorf("error getting Cloud Trail (%s) Insight Selectors: %w", d.Id(), err) + return fmt.Errorf("getting Cloud Trail (%s) Insight Selectors: %w", d.Id(), err) } } if insightSelectors != nil { if err := d.Set("insight_selector", flattenInsightSelector(insightSelectors.InsightSelectors)); err != nil { - return err + return create.Error(names.CloudTrail, create.ErrActionReading, ResNameTrail, d.Id(), err) } } } @@ -520,7 +520,7 @@ func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateTrail(&input) } if err != nil { - return fmt.Errorf("Error updating CloudTrail: %w", err) + return fmt.Errorf("updating CloudTrail Trail (%s): %w", d.Id(), err) } } @@ -528,7 +528,7 @@ func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("tags_all") if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating ECR Repository (%s) tags: %s", d.Get("arn").(string), err) + return fmt.Errorf("updating ECR Repository (%s) tags: %s", d.Get("arn").(string), err) } } @@ -536,28 +536,28 @@ func resourceCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] Updating logging on CloudTrail: %s", d.Id()) err := setLogging(conn, d.Get("enable_logging").(bool), d.Id()) if err != nil { - return err + return fmt.Errorf("updating CloudTrail Trail (%s): %w", d.Id(), err) } } if !d.IsNewResource() && d.HasChange("event_selector") { log.Printf("[DEBUG] Updating event selector on CloudTrail: %s", d.Id()) if err := setEventSelectors(conn, d); err != nil { - return err + return fmt.Errorf("updating CloudTrail Trail (%s): %w", d.Id(), err) } } if !d.IsNewResource() && d.HasChange("advanced_event_selector") { log.Printf("[DEBUG] Updating advanced event selector on CloudTrail: %s", d.Id()) if err := setAdvancedEventSelectors(conn, d); err != nil { - return err + return fmt.Errorf("updating CloudTrail Trail (%s): %w", d.Id(), err) } } if !d.IsNewResource() && d.HasChange("insight_selector") { log.Printf("[DEBUG] Updating insight selector on CloudTrail: %s", d.Id()) if err := setInsightSelectors(conn, d); err != nil { - return err + return fmt.Errorf("updating CloudTrail Trail (%s): %w", d.Id(), err) } } @@ -577,19 +577,19 @@ func resourceCloudTrailDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting CloudTrail (%s): %w", d.Id(), err) + return fmt.Errorf("deleting CloudTrail (%s): %w", d.Id(), err) } return nil } func getLoggingStatus(conn *cloudtrail.CloudTrail, id *string) (bool, error) { - GetTrailStatusOpts := &cloudtrail.GetTrailStatusInput{ + input := &cloudtrail.GetTrailStatusInput{ Name: id, } - resp, err := conn.GetTrailStatus(GetTrailStatusOpts) + resp, err := conn.GetTrailStatus(input) if err != nil { - return false, fmt.Errorf("Error retrieving logging status of CloudTrail (%s): %w", *id, err) + return false, fmt.Errorf("retrieving logging status: %w", err) } return aws.BoolValue(resp.IsLogging), err @@ -602,7 +602,7 @@ func setLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) error { Name: aws.String(id), } if _, err := conn.StartLogging(StartLoggingOpts); err != nil { - return fmt.Errorf("Error starting logging on CloudTrail (%s): %w", id, err) + return fmt.Errorf("starting logging: %w", err) } } else { log.Printf("[DEBUG] Stopping logging on CloudTrail (%s)", id) @@ -610,7 +610,7 @@ func setLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) error { Name: aws.String(id), } if _, err := conn.StopLogging(StopLoggingOpts); err != nil { - return fmt.Errorf("Error stopping logging on CloudTrail (%s): %w", id, err) + return fmt.Errorf("stopping logging: %w", err) } } @@ -635,12 +635,12 @@ func setEventSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) erro input.EventSelectors = eventSelectors if err := input.Validate(); err != nil { - return fmt.Errorf("Error validate CloudTrail (%s): %s", d.Id(), err) + return fmt.Errorf("validate CloudTrail (%s): %s", d.Id(), err) } _, err := conn.PutEventSelectors(input) if err != nil { - return fmt.Errorf("Error set event selector on CloudTrail (%s): %s", d.Id(), err) + return fmt.Errorf("set event selector on CloudTrail (%s): %s", d.Id(), err) } return nil @@ -729,12 +729,12 @@ func setAdvancedEventSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceDa input.AdvancedEventSelectors = expandAdvancedEventSelector(d.Get("advanced_event_selector").([]interface{})) if err := input.Validate(); err != nil { - return fmt.Errorf("Error validate CloudTrail (%s): %w", d.Id(), err) + return fmt.Errorf("validate CloudTrail (%s): %w", d.Id(), err) } _, err := conn.PutEventSelectors(input) if err != nil { - return fmt.Errorf("Error set advanced event selector on CloudTrail (%s): %w", d.Id(), err) + return fmt.Errorf("set advanced event selector on CloudTrail (%s): %w", d.Id(), err) } return nil @@ -851,12 +851,12 @@ func setInsightSelectors(conn *cloudtrail.CloudTrail, d *schema.ResourceData) er input.InsightSelectors = insightSelector if err := input.Validate(); err != nil { - return fmt.Errorf("Error validate CloudTrail (%s): %w", d.Id(), err) + return fmt.Errorf("validate CloudTrail (%s): %w", d.Id(), err) } _, err := conn.PutInsightSelectors(input) if err != nil { - return fmt.Errorf("Error set insight selector on CloudTrail (%s): %w", d.Id(), err) + return fmt.Errorf("set insight selector on CloudTrail (%s): %w", d.Id(), err) } return nil From 8eab28c1ee2bacee91973ca912274e30ad18de26 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:49:31 -0800 Subject: [PATCH 086/106] Fixes bare errors in `cloudsearch` --- internal/service/cloudsearch/domain.go | 10 +++++----- .../cloudsearch/domain_service_access_policy.go | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/service/cloudsearch/domain.go b/internal/service/cloudsearch/domain.go index 69d3f54434e..73a4f5bd348 100644 --- a/internal/service/cloudsearch/domain.go +++ b/internal/service/cloudsearch/domain.go @@ -181,7 +181,7 @@ func resourceDomainCreate(d *schema.ResourceData, meta interface{}) error { _, err := conn.CreateDomain(&input) if err != nil { - return fmt.Errorf("error creating CloudSearch Domain (%s): %w", name, err) + return fmt.Errorf("creating CloudSearch Domain (%s): %w", name, err) } d.SetId(name) @@ -232,7 +232,7 @@ func resourceDomainCreate(d *schema.ResourceData, meta interface{}) error { err := defineIndexFields(conn, d.Id(), v.(*schema.Set).List()) if err != nil { - return err + return fmt.Errorf("creating CloudSearch Domain (%s): %w", name, err) } log.Printf("[DEBUG] Indexing CloudSearch Domain documents: %s", d.Id()) @@ -268,7 +268,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading CloudSearch Domain (%s): %w", d.Id(), err) + return fmt.Errorf("reading CloudSearch Domain (%s): %w", d.Id(), err) } d.Set("arn", domainStatus.ARN) @@ -323,7 +323,7 @@ func resourceDomainRead(d *schema.ResourceData, meta interface{}) error { } if tfList, err := flattenIndexFieldStatuses(indexResults.IndexFields); err != nil { - return err + return fmt.Errorf("reading CloudSearch Domain (%s): %w", d.Id(), err) } else if err := d.Set("index_field", tfList); err != nil { return fmt.Errorf("error setting index_field: %w", err) } @@ -434,7 +434,7 @@ func resourceDomainUpdate(d *schema.ResourceData, meta interface{}) error { if v := new.Difference(old); v.Len() > 0 { if err := defineIndexFields(conn, d.Id(), v.List()); err != nil { - return err + return fmt.Errorf("updating CloudSearch Domain (%s): %w", d.Id(), err) } requiresIndexDocuments = true diff --git a/internal/service/cloudsearch/domain_service_access_policy.go b/internal/service/cloudsearch/domain_service_access_policy.go index f330ec63ffb..a3872e1ab92 100644 --- a/internal/service/cloudsearch/domain_service_access_policy.go +++ b/internal/service/cloudsearch/domain_service_access_policy.go @@ -99,13 +99,13 @@ func resourceDomainServiceAccessPolicyRead(d *schema.ResourceData, meta interfac } if err != nil { - return fmt.Errorf("error reading CloudSearch Domain Service Access Policy (%s): %w", d.Id(), err) + return fmt.Errorf("reading CloudSearch Domain Service Access Policy (%s): %w", d.Id(), err) } policyToSet, err := verify.PolicyToSet(d.Get("access_policy").(string), accessPolicy) if err != nil { - return err + return fmt.Errorf("reading CloudSearch Domain Service Access Policy (%s): %w", d.Id(), err) } d.Set("access_policy", policyToSet) From 85555e5d77ce96ccd01a7047a593c5545e5c1560 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:49:44 -0800 Subject: [PATCH 087/106] Fixes bare errors in `cloudfront` --- internal/service/cloudfront/distribution.go | 2 +- .../distribution_configuration_structure.go | 18 +++++++++--------- .../cloudfront/origin_access_identity.go | 11 ++++++----- .../origin_access_identity_data_source.go | 2 +- internal/service/cloudfront/public_key.go | 2 +- 5 files changed, 18 insertions(+), 17 deletions(-) diff --git a/internal/service/cloudfront/distribution.go b/internal/service/cloudfront/distribution.go index 1d904d0c96a..6d41cbe695e 100644 --- a/internal/service/cloudfront/distribution.go +++ b/internal/service/cloudfront/distribution.go @@ -900,7 +900,7 @@ func resourceDistributionRead(d *schema.ResourceData, meta interface{}) error { // Update attributes from DistributionConfig err = flattenDistributionConfig(d, resp.Distribution.DistributionConfig) if err != nil { - return err + return fmt.Errorf("reading CloudFront Distribution (%s): %w", d.Id(), err) } // Update other attributes outside of DistributionConfig diff --git a/internal/service/cloudfront/distribution_configuration_structure.go b/internal/service/cloudfront/distribution_configuration_structure.go index 09718ad4f6e..bb1320714d9 100644 --- a/internal/service/cloudfront/distribution_configuration_structure.go +++ b/internal/service/cloudfront/distribution_configuration_structure.go @@ -94,11 +94,11 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud err = d.Set("default_cache_behavior", []interface{}{flattenDefaultCacheBehavior(distributionConfig.DefaultCacheBehavior)}) if err != nil { - return err + return err // nosemgrep:bare-error-returns } err = d.Set("viewer_certificate", flattenViewerCertificate(distributionConfig.ViewerCertificate)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } if distributionConfig.CallerReference != nil { @@ -122,12 +122,12 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud if distributionConfig.CustomErrorResponses != nil { err = d.Set("custom_error_response", FlattenCustomErrorResponses(distributionConfig.CustomErrorResponses)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if distributionConfig.CacheBehaviors != nil { if err := d.Set("ordered_cache_behavior", flattenCacheBehaviors(distributionConfig.CacheBehaviors)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -137,31 +137,31 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud err = d.Set("logging_config", []interface{}{}) } if err != nil { - return err + return err // nosemgrep:bare-error-returns } if distributionConfig.Aliases != nil { err = d.Set("aliases", FlattenAliases(distributionConfig.Aliases)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if distributionConfig.Restrictions != nil { err = d.Set("restrictions", flattenRestrictions(distributionConfig.Restrictions)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if aws.Int64Value(distributionConfig.Origins.Quantity) > 0 { err = d.Set("origin", FlattenOrigins(distributionConfig.Origins)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } if aws.Int64Value(distributionConfig.OriginGroups.Quantity) > 0 { err = d.Set("origin_group", FlattenOriginGroups(distributionConfig.OriginGroups)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } diff --git a/internal/service/cloudfront/origin_access_identity.go b/internal/service/cloudfront/origin_access_identity.go index 25e335dd83f..3077e5dc436 100644 --- a/internal/service/cloudfront/origin_access_identity.go +++ b/internal/service/cloudfront/origin_access_identity.go @@ -62,7 +62,7 @@ func resourceOriginAccessIdentityCreate(d *schema.ResourceData, meta interface{} resp, err := conn.CreateCloudFrontOriginAccessIdentity(params) if err != nil { - return err + return create.Error(names.CloudFront, create.ErrActionReading, ResNameOriginAccessIdentity, d.Id(), err) } d.SetId(aws.StringValue(resp.CloudFrontOriginAccessIdentity.Id)) return resourceOriginAccessIdentityRead(d, meta) @@ -111,7 +111,7 @@ func resourceOriginAccessIdentityUpdate(d *schema.ResourceData, meta interface{} } _, err := conn.UpdateCloudFrontOriginAccessIdentity(params) if err != nil { - return err + return create.Error(names.CloudFront, create.ErrActionUpdating, ResNameOriginAccessIdentity, d.Id(), err) } return resourceOriginAccessIdentityRead(d, meta) @@ -124,9 +124,10 @@ func resourceOriginAccessIdentityDelete(d *schema.ResourceData, meta interface{} IfMatch: aws.String(d.Get("etag").(string)), } - _, err := conn.DeleteCloudFrontOriginAccessIdentity(params) - - return err + if _, err := conn.DeleteCloudFrontOriginAccessIdentity(params); err != nil { + return create.Error(names.CloudFront, create.ErrActionDeleting, ResNameOriginAccessIdentity, d.Id(), err) + } + return nil } func expandOriginAccessIdentityConfig(d *schema.ResourceData) *cloudfront.OriginAccessIdentityConfig { diff --git a/internal/service/cloudfront/origin_access_identity_data_source.go b/internal/service/cloudfront/origin_access_identity_data_source.go index 31ecc14cbb4..49f1f1efa4d 100644 --- a/internal/service/cloudfront/origin_access_identity_data_source.go +++ b/internal/service/cloudfront/origin_access_identity_data_source.go @@ -57,7 +57,7 @@ func dataSourceOriginAccessIdentityRead(d *schema.ResourceData, meta interface{} resp, err := conn.GetCloudFrontOriginAccessIdentity(params) if err != nil { - return err + return fmt.Errorf("reading CloudFront Origin Access Identity (%s): %w", id, err) } // Update attributes from DistributionConfig diff --git a/internal/service/cloudfront/public_key.go b/internal/service/cloudfront/public_key.go index 754c08e0e3c..16fc78b0c10 100644 --- a/internal/service/cloudfront/public_key.go +++ b/internal/service/cloudfront/public_key.go @@ -156,7 +156,7 @@ func resourcePublicKeyDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, cloudfront.ErrCodeNoSuchPublicKey) { return nil } - return err + return fmt.Errorf("deleting CloudFront PublicKey (%s): %s", d.Id(), err) } return nil From 909319cf73df30a3c241074ee3d5ec1a6a638ac9 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:49:56 -0800 Subject: [PATCH 088/106] Fixes bare errors in `cloudformation` --- internal/service/cloudformation/stack.go | 17 +++++------- .../cloudformation/stack_data_source.go | 2 +- .../cloudformation/stack_set_instance.go | 26 +++++++++++-------- internal/service/cloudformation/wait.go | 2 +- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/internal/service/cloudformation/stack.go b/internal/service/cloudformation/stack.go index 0a70ab25558..3f4595b9689 100644 --- a/internal/service/cloudformation/stack.go +++ b/internal/service/cloudformation/stack.go @@ -258,7 +258,7 @@ func resourceStackRead(d *schema.ResourceData, meta interface{}) error { } out, err := conn.GetTemplate(&tInput) if err != nil { - return err + return fmt.Errorf("reading CloudFormation Stack (%s): reading template: %w", d.Id(), err) } template, err := verify.NormalizeJSONOrYAMLString(*out.TemplateBody) @@ -285,14 +285,14 @@ func resourceStackRead(d *schema.ResourceData, meta interface{}) error { if len(stack.NotificationARNs) > 0 { err = d.Set("notification_arns", flex.FlattenStringSet(stack.NotificationARNs)) if err != nil { - return err + return fmt.Errorf("reading CloudFormation Stack (%s): %w", d.Id(), err) } } originalParams := d.Get("parameters").(map[string]interface{}) err = d.Set("parameters", flattenParameters(stack.Parameters, originalParams)) if err != nil { - return err + return fmt.Errorf("reading CloudFormation Stack (%s): %w", d.Id(), err) } tags := KeyValueTags(stack.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -308,13 +308,13 @@ func resourceStackRead(d *schema.ResourceData, meta interface{}) error { err = d.Set("outputs", flattenOutputs(stack.Outputs)) if err != nil { - return err + return fmt.Errorf("reading CloudFormation Stack (%s): %w", d.Id(), err) } if len(stack.Capabilities) > 0 { err = d.Set("capabilities", flex.FlattenStringSet(stack.Capabilities)) if err != nil { - return err + return fmt.Errorf("reading CloudFormation Stack (%s): %w", d.Id(), err) } } @@ -412,21 +412,18 @@ func resourceStackDelete(d *schema.ResourceData, meta interface{}) error { StackName: aws.String(d.Id()), ClientRequestToken: aws.String(requestToken), } - log.Printf("[DEBUG] Deleting CloudFormation stack %s", input) _, err := conn.DeleteStack(input) if tfawserr.ErrCodeEquals(err, "ValidationError") { return nil } if err != nil { - return err + return fmt.Errorf("deleting CloudFormation Stack (%s): %w", d.Id(), err) } _, err = WaitStackDeleted(conn, d.Id(), requestToken, d.Timeout(schema.TimeoutDelete)) if err != nil { - return fmt.Errorf("error waiting for CloudFormation Stack deletion: %w", err) + return fmt.Errorf("deleting CloudFormation Stack (%s): waiting for completion: %w", d.Id(), err) } - log.Printf("[INFO] CloudFormation stack (%s) deleted", d.Id()) - return nil } diff --git a/internal/service/cloudformation/stack_data_source.go b/internal/service/cloudformation/stack_data_source.go index 406f382ea5a..0e3b7a071f6 100644 --- a/internal/service/cloudformation/stack_data_source.go +++ b/internal/service/cloudformation/stack_data_source.go @@ -113,7 +113,7 @@ func dataSourceStackRead(d *schema.ResourceData, meta interface{}) error { } tOut, err := conn.GetTemplate(&tInput) if err != nil { - return err + return fmt.Errorf("reading CloudFormation Stack (%s): reading template: %w", name, err) } template, err := verify.NormalizeJSONOrYAMLString(*tOut.TemplateBody) diff --git a/internal/service/cloudformation/stack_set_instance.go b/internal/service/cloudformation/stack_set_instance.go index b273c51d652..c1772f79ab4 100644 --- a/internal/service/cloudformation/stack_set_instance.go +++ b/internal/service/cloudformation/stack_set_instance.go @@ -201,12 +201,16 @@ func resourceStackSetInstanceCreate(d *schema.ResourceData, meta interface{}) er output, err := conn.CreateStackInstances(input) if err != nil { - return nil, fmt.Errorf("error creating CloudFormation StackSet (%s) Instance: %w", stackSetName, err) + return nil, err } d.SetId(StackSetInstanceCreateResourceID(stackSetName, accountID, region)) - return WaitStackSetOperationSucceeded(conn, stackSetName, aws.StringValue(output.OperationId), callAs, d.Timeout(schema.TimeoutCreate)) + operation, err := WaitStackSetOperationSucceeded(conn, stackSetName, aws.StringValue(output.OperationId), callAs, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return nil, fmt.Errorf("waiting for completion: %w", err) + } + return operation, nil }, func(err error) (bool, error) { if err == nil { @@ -248,7 +252,7 @@ func resourceStackSetInstanceCreate(d *schema.ResourceData, meta interface{}) er ) if err != nil { - return err + return fmt.Errorf("error creating CloudFormation StackSet (%s) Instance: %w", stackSetName, err) } return resourceStackSetInstanceRead(d, meta) @@ -262,7 +266,7 @@ func resourceStackSetInstanceRead(d *schema.ResourceData, meta interface{}) erro callAs := d.Get("call_as").(string) if err != nil { - return err + return fmt.Errorf("reading CloudFormation StackSet Instance (%s): %w", d.Id(), err) } // Determine correct account ID for the Instance if created with deployment targets; @@ -288,7 +292,7 @@ func resourceStackSetInstanceRead(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("error reading CloudFormation StackSet Instance (%s): %w", d.Id(), err) + return fmt.Errorf("reading CloudFormation StackSet Instance (%s): %w", d.Id(), err) } d.Set("account_id", stackInstance.Account) @@ -311,7 +315,7 @@ func resourceStackSetInstanceUpdate(d *schema.ResourceData, meta interface{}) er stackSetName, accountID, region, err := StackSetInstanceParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating CloudFormation StackSet Instance (%s): %w", d.Id(), err) } input := &cloudformation.UpdateStackInstancesInput{ @@ -345,11 +349,11 @@ func resourceStackSetInstanceUpdate(d *schema.ResourceData, meta interface{}) er output, err := conn.UpdateStackInstances(input) if err != nil { - return fmt.Errorf("error updating CloudFormation StackSet Instance (%s): %w", d.Id(), err) + return fmt.Errorf("updating CloudFormation StackSet Instance (%s): %w", d.Id(), err) } if _, err := WaitStackSetOperationSucceeded(conn, stackSetName, aws.StringValue(output.OperationId), callAs, d.Timeout(schema.TimeoutUpdate)); err != nil { - return fmt.Errorf("error waiting for CloudFormation StackSet Instance (%s) update: %s", d.Id(), err) + return fmt.Errorf("updating CloudFormation StackSet Instance (%s): waiting for completion: %w", d.Id(), err) } } @@ -362,7 +366,7 @@ func resourceStackSetInstanceDelete(d *schema.ResourceData, meta interface{}) er stackSetName, accountID, region, err := StackSetInstanceParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting CloudFormation StackSet Instance (%s): %s", d.Id(), err) } input := &cloudformation.DeleteStackInstancesInput{ @@ -395,11 +399,11 @@ func resourceStackSetInstanceDelete(d *schema.ResourceData, meta interface{}) er } if err != nil { - return fmt.Errorf("error deleting CloudFormation StackSet Instance (%s): %s", d.Id(), err) + return fmt.Errorf("deleting CloudFormation StackSet Instance (%s): %s", d.Id(), err) } if _, err := WaitStackSetOperationSucceeded(conn, stackSetName, aws.StringValue(output.OperationId), callAs, d.Timeout(schema.TimeoutDelete)); err != nil { - return fmt.Errorf("error waiting for CloudFormation StackSet Instance (%s) deletion: %s", d.Id(), err) + return fmt.Errorf("deleting CloudFormation StackSet Instance (%s): waiting for completion: %s", d.Id(), err) } return nil diff --git a/internal/service/cloudformation/wait.go b/internal/service/cloudformation/wait.go index 15d501ed4c6..b1f54533107 100644 --- a/internal/service/cloudformation/wait.go +++ b/internal/service/cloudformation/wait.go @@ -89,7 +89,7 @@ func WaitStackSetOperationSucceeded(conn *cloudformation.CloudFormation, stackSe if listErr == nil { tfresource.SetLastError(waitErr, fmt.Errorf("Operation (%s) Results: %w", operationID, StackSetOperationError(summaries))) } else { - tfresource.SetLastError(waitErr, fmt.Errorf("error listing CloudFormation Stack Set (%s) Operation (%s) results: %w", stackSetName, operationID, listErr)) + tfresource.SetLastError(waitErr, fmt.Errorf("listing CloudFormation Stack Set (%s) Operation (%s) results: %w", stackSetName, operationID, listErr)) } } From 05fab27c0569da9e8725b181c5c8541c5715aa30 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:50:10 -0800 Subject: [PATCH 089/106] Fixes bare errors in `cloud9` --- internal/service/cloud9/environment_membership.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/cloud9/environment_membership.go b/internal/service/cloud9/environment_membership.go index 32586bfd1dc..17a1aefd5c5 100644 --- a/internal/service/cloud9/environment_membership.go +++ b/internal/service/cloud9/environment_membership.go @@ -78,7 +78,7 @@ func resourceEnvironmentMembershipRead(d *schema.ResourceData, meta interface{}) envId, userArn, err := DecodeEnviornmentMemberId(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Cloud9 EC2 Environment (%s): %w", d.Id(), err) } env, err := FindEnvironmentMembershipByID(conn, envId, userArn) @@ -90,7 +90,7 @@ func resourceEnvironmentMembershipRead(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error reading Cloud9 EC2 Environment (%s): %w", d.Id(), err) + return fmt.Errorf("reading Cloud9 EC2 Environment (%s): %w", d.Id(), err) } d.Set("environment_id", env.EnvironmentId) From 3daf30839930b81375c8436364874384b62055ec Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:50:24 -0800 Subject: [PATCH 090/106] Fixes bare errors in `batch` --- .../batch/compute_environment_data_source.go | 14 +++++--------- internal/service/batch/job_definition.go | 6 +++--- internal/service/batch/job_queue.go | 7 +++---- internal/service/batch/job_queue_data_source.go | 12 +++++------- internal/service/batch/scheduling_policy.go | 2 +- 5 files changed, 17 insertions(+), 24 deletions(-) diff --git a/internal/service/batch/compute_environment_data_source.go b/internal/service/batch/compute_environment_data_source.go index 2d725315d45..c93bf23556a 100644 --- a/internal/service/batch/compute_environment_data_source.go +++ b/internal/service/batch/compute_environment_data_source.go @@ -2,7 +2,6 @@ package batch import ( "fmt" - "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/batch" @@ -68,19 +67,16 @@ func dataSourceComputeEnvironmentRead(d *schema.ResourceData, meta interface{}) params := &batch.DescribeComputeEnvironmentsInput{ ComputeEnvironments: []*string{aws.String(d.Get("compute_environment_name").(string))}, } - log.Printf("[DEBUG] Reading Batch Compute Environment: %s", params) desc, err := conn.DescribeComputeEnvironments(params) if err != nil { - return err + return fmt.Errorf("reading Batch Compute Environment (%s): %w", d.Get("compute_environment_name").(string), err) } - if len(desc.ComputeEnvironments) == 0 { - return fmt.Errorf("no matches found for name: %s", d.Get("compute_environment_name").(string)) - } - - if len(desc.ComputeEnvironments) > 1 { - return fmt.Errorf("multiple matches found for name: %s", d.Get("compute_environment_name").(string)) + if l := len(desc.ComputeEnvironments); l == 0 { + return fmt.Errorf("reading Batch Compute Environment (%s): empty response", d.Get("compute_environment_name").(string)) + } else if l > 1 { + return fmt.Errorf("reading Batch Compute Environment (%s): too many results: wanted 1, got %d", d.Get("compute_environment_name").(string), l) } computeEnvironment := desc.ComputeEnvironments[0] diff --git a/internal/service/batch/job_definition.go b/internal/service/batch/job_definition.go index e0d67d5eb1c..e5591360f4d 100644 --- a/internal/service/batch/job_definition.go +++ b/internal/service/batch/job_definition.go @@ -189,7 +189,7 @@ func resourceJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error if v, ok := d.GetOk("container_properties"); ok { props, err := expandJobContainerProperties(v.(string)) if err != nil { - return err + return fmt.Errorf("creating Batch Job Definition (%s): %w", name, err) } input.ContainerProperties = props @@ -218,7 +218,7 @@ func resourceJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error output, err := conn.RegisterJobDefinition(input) if err != nil { - return fmt.Errorf("error creating Batch Job Definition (%s): %w", name, err) + return fmt.Errorf("creating Batch Job Definition (%s): %w", name, err) } d.SetId(aws.StringValue(output.JobDefinitionArn)) @@ -336,7 +336,7 @@ func expandJobContainerProperties(rawProps string) (*batch.ContainerProperties, err := json.Unmarshal([]byte(rawProps), &props) if err != nil { - return nil, fmt.Errorf("Error decoding JSON: %s", err) + return nil, fmt.Errorf("decoding JSON: %s", err) } return props, nil diff --git a/internal/service/batch/job_queue.go b/internal/service/batch/job_queue.go index 70b55177b94..29d57c43966 100644 --- a/internal/service/batch/job_queue.go +++ b/internal/service/batch/job_queue.go @@ -121,7 +121,7 @@ func resourceJobQueueRead(d *schema.ResourceData, meta interface{}) error { jq, err := GetJobQueue(conn, d.Id()) if err != nil { - return err + return fmt.Errorf("reading Batch Job Queue (%s): %w", d.Get("name").(string), err) } if jq == nil { log.Printf("[WARN] Batch Job Queue (%s) not found, removing from state", d.Id()) @@ -193,7 +193,7 @@ func resourceJobQueueUpdate(d *schema.ResourceData, meta interface{}) error { _, err := conn.UpdateJobQueue(updateInput) if err != nil { - return err + return fmt.Errorf("updating Batch Job Queue (%s): %w", d.Get("name").(string), err) } stateConf := &resource.StateChangeConf{ Pending: []string{batch.JQStatusUpdating}, @@ -206,7 +206,7 @@ func resourceJobQueueUpdate(d *schema.ResourceData, meta interface{}) error { _, err = stateConf.WaitForState() if err != nil { - return err + return fmt.Errorf("updating Batch Job Queue (%s): waiting for completion: %w", d.Get("name").(string), err) } } @@ -304,7 +304,6 @@ func GetJobQueue(conn *batch.Batch, sn string) (*batch.JobQueueDetail, error) { numJobQueues := len(resp.JobQueues) switch { case numJobQueues == 0: - log.Printf("[DEBUG] Job Queue %q is already gone", sn) return nil, nil case numJobQueues == 1: return resp.JobQueues[0], nil diff --git a/internal/service/batch/job_queue_data_source.go b/internal/service/batch/job_queue_data_source.go index 96f8aee0be9..ce882e6bc74 100644 --- a/internal/service/batch/job_queue_data_source.go +++ b/internal/service/batch/job_queue_data_source.go @@ -84,15 +84,13 @@ func dataSourceJobQueueRead(d *schema.ResourceData, meta interface{}) error { desc, err := conn.DescribeJobQueues(params) if err != nil { - return err + return fmt.Errorf("reading Batch Job Queue (%s): %w", d.Get("name").(string), err) } - if len(desc.JobQueues) == 0 { - return fmt.Errorf("no matches found for name: %s", d.Get("name").(string)) - } - - if len(desc.JobQueues) > 1 { - return fmt.Errorf("multiple matches found for name: %s", d.Get("name").(string)) + if l := len(desc.JobQueues); l == 0 { + return fmt.Errorf("reading Batch Job Queue (%s): empty response", d.Get("name").(string)) + } else if l > 1 { + return fmt.Errorf("reading Batch Job Queue (%s): too many results: wanted 1, got %d", d.Get("name").(string), l) } jobQueue := desc.JobQueues[0] diff --git a/internal/service/batch/scheduling_policy.go b/internal/service/batch/scheduling_policy.go index 5bf0902e185..06f89344aaf 100644 --- a/internal/service/batch/scheduling_policy.go +++ b/internal/service/batch/scheduling_policy.go @@ -178,7 +178,7 @@ func resourceSchedulingPolicyUpdate(ctx context.Context, d *schema.ResourceData, _, err := conn.UpdateSchedulingPolicyWithContext(ctx, input) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating SchedulingPolicy (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating SchedulingPolicy (%s): %w", d.Id(), err)) } if d.HasChange("tags_all") { From 636208aa06b7d921f4d448a5ffef41bbcd7df2a4 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:50:37 -0800 Subject: [PATCH 091/106] Fixes bare errors in `backup` --- internal/service/backup/vault.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/backup/vault.go b/internal/service/backup/vault.go index fefff5376bf..96acf753942 100644 --- a/internal/service/backup/vault.go +++ b/internal/service/backup/vault.go @@ -176,12 +176,12 @@ func resourceVaultDelete(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - recoveryPointErrs = multierror.Append(recoveryPointErrs, fmt.Errorf("deleting Backup Vault (%s) recovery point (%s): %w", d.Id(), recoveryPointARN, err)) + recoveryPointErrs = multierror.Append(recoveryPointErrs, fmt.Errorf("deleting recovery point (%s): %w", recoveryPointARN, err)) continue } if _, err := waitRecoveryPointDeleted(conn, d.Id(), recoveryPointARN, d.Timeout(schema.TimeoutDelete)); err != nil { - recoveryPointErrs = multierror.Append(recoveryPointErrs, fmt.Errorf("waiting for Backup Vault (%s) recovery point (%s) delete: %w", d.Id(), recoveryPointARN, err)) + recoveryPointErrs = multierror.Append(recoveryPointErrs, fmt.Errorf("deleting recovery point (%s): waiting for completion: %w", recoveryPointARN, err)) } } @@ -193,7 +193,7 @@ func resourceVaultDelete(d *schema.ResourceData, meta interface{}) error { } if err := recoveryPointErrs.ErrorOrNil(); err != nil { - return err + return fmt.Errorf("deleting Backup Vault (%s): %w", d.Id(), err) } } From b103da03af03bb7f16bc7fd6e61934da048a5fc2 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:50:51 -0800 Subject: [PATCH 092/106] Fixes bare errors in `autoscalingplans` --- .../service/autoscalingplans/scaling_plan.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/internal/service/autoscalingplans/scaling_plan.go b/internal/service/autoscalingplans/scaling_plan.go index c9722692d7d..36d21dea5f7 100644 --- a/internal/service/autoscalingplans/scaling_plan.go +++ b/internal/service/autoscalingplans/scaling_plan.go @@ -354,7 +354,7 @@ func resourceScalingPlanRead(d *schema.ResourceData, meta interface{}) error { scalingPlanName, scalingPlanVersion, err := scalingPlanParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Auto Scaling Scaling Plan (%s): %w", d.Id(), err) } scalingPlan, err := FindScalingPlanByNameAndVersion(conn, scalingPlanName, scalingPlanVersion) @@ -366,7 +366,7 @@ func resourceScalingPlanRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading Auto Scaling Scaling Plan (%s): %w", d.Id(), err) + return fmt.Errorf("reading Auto Scaling Scaling Plan (%s): %w", d.Id(), err) } err = d.Set("application_source", flattenApplicationSource(scalingPlan.ApplicationSource)) @@ -389,7 +389,7 @@ func resourceScalingPlanUpdate(d *schema.ResourceData, meta interface{}) error { scalingPlanName, scalingPlanVersion, err := scalingPlanParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Auto Scaling Scaling Plan (%s): %w", d.Id(), err) } input := &autoscalingplans.UpdateScalingPlanInput{ @@ -403,13 +403,13 @@ func resourceScalingPlanUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateScalingPlan(input) if err != nil { - return fmt.Errorf("error updating Auto Scaling Scaling Plan (%s): %w", d.Id(), err) + return fmt.Errorf("updating Auto Scaling Scaling Plan (%s): %w", d.Id(), err) } _, err = waitScalingPlanUpdated(conn, scalingPlanName, scalingPlanVersion) if err != nil { - return fmt.Errorf("error waiting for Auto Scaling Scaling Plan (%s) update: %w", d.Id(), err) + return fmt.Errorf("updating Auto Scaling Scaling Plan (%s): waiting for completion: %w", d.Id(), err) } return resourceScalingPlanRead(d, meta) @@ -421,7 +421,7 @@ func resourceScalingPlanDelete(d *schema.ResourceData, meta interface{}) error { scalingPlanName, scalingPlanVersion, err := scalingPlanParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Auto Scaling Scaling Plan (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Deleting Auto Scaling Scaling Plan: %s", d.Id()) @@ -435,13 +435,13 @@ func resourceScalingPlanDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting Auto Scaling Scaling Plan (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Auto Scaling Scaling Plan (%s): %w", d.Id(), err) } _, err = waitScalingPlanDeleted(conn, scalingPlanName, scalingPlanVersion) if err != nil { - return fmt.Errorf("error waiting for Auto Scaling Scaling Plan (%s) delete: %w", d.Id(), err) + return fmt.Errorf("deleting Auto Scaling Scaling Plan (%s): waiting for completion: %w", d.Id(), err) } return nil From cfa23e52166d76185b52c072cea01e67d212215f Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:51:00 -0800 Subject: [PATCH 093/106] Fixes bare errors in `autoscaling` --- internal/service/autoscaling/group.go | 8 ++--- internal/service/autoscaling/group_tag.go | 12 ++++---- .../autoscaling/launch_configuration.go | 4 +-- .../launch_configuration_data_source.go | 2 +- internal/service/autoscaling/notification.go | 30 ++++++++++--------- internal/service/autoscaling/policy.go | 4 +-- 6 files changed, 31 insertions(+), 29 deletions(-) diff --git a/internal/service/autoscaling/group.go b/internal/service/autoscaling/group.go index 467adf676dd..842902d9427 100644 --- a/internal/service/autoscaling/group.go +++ b/internal/service/autoscaling/group.go @@ -1478,7 +1478,7 @@ func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { if shouldRefreshInstances { if err := startInstanceRefresh(conn, expandStartInstanceRefreshInput(d.Id(), tfMap)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } } @@ -1491,7 +1491,7 @@ func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { forceDeleteWarmPool := d.Get("force_delete").(bool) || d.Get("force_delete_warm_pool").(bool) if err := deleteWarmPool(conn, d.Id(), forceDeleteWarmPool, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + return err // nosemgrep:bare-error-returns } } else { _, err := conn.PutWarmPool(expandPutWarmPoolInput(d.Id(), w[0].(map[string]interface{}))) @@ -1632,7 +1632,7 @@ func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { err = deleteWarmPool(conn, d.Id(), forceDeleteWarmPool, d.Timeout(schema.TimeoutDelete)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } @@ -1640,7 +1640,7 @@ func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { err = drainGroup(conn, d.Id(), group.Instances, d.Timeout(schema.TimeoutDelete)) if err != nil { - return err + return err // nosemgrep:bare-error-returns } } diff --git a/internal/service/autoscaling/group_tag.go b/internal/service/autoscaling/group_tag.go index c4019f85326..5e20ba34b50 100644 --- a/internal/service/autoscaling/group_tag.go +++ b/internal/service/autoscaling/group_tag.go @@ -73,7 +73,7 @@ func resourceGroupTagRead(d *schema.ResourceData, meta interface{}) error { identifier, key, err := tftags.GetResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AutoScaling Group (%s) tag (%s): %w", identifier, key, err) } value, err := GetTag(conn, identifier, TagResourceTypeGroup, key) @@ -85,7 +85,7 @@ func resourceGroupTagRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error reading AutoScaling Group (%s) tag (%s): %w", identifier, key, err) + return fmt.Errorf("reading AutoScaling Group (%s) tag (%s): %w", identifier, key, err) } d.Set("autoscaling_group_name", identifier) @@ -106,11 +106,11 @@ func resourceGroupTagUpdate(d *schema.ResourceData, meta interface{}) error { identifier, key, err := tftags.GetResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating AutoScaling Group Tag (%s): %w", d.Id(), err) } if err := UpdateTags(conn, identifier, TagResourceTypeGroup, nil, d.Get("tag")); err != nil { - return fmt.Errorf("error updating AutoScaling Group (%s) tag (%s): %w", identifier, key, err) + return fmt.Errorf("updating AutoScaling Group (%s) tag (%s): %w", identifier, key, err) } return resourceGroupTagRead(d, meta) @@ -121,11 +121,11 @@ func resourceGroupTagDelete(d *schema.ResourceData, meta interface{}) error { identifier, key, err := tftags.GetResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting AutoScaling Group Tag (%s): %w", d.Id(), err) } if err := UpdateTags(conn, identifier, TagResourceTypeGroup, d.Get("tag"), nil); err != nil { - return fmt.Errorf("error deleting AutoScaling Group (%s) tag (%s): %w", identifier, key, err) + return fmt.Errorf("deleting AutoScaling Group (%s) tag (%s): %w", identifier, key, err) } return nil diff --git a/internal/service/autoscaling/launch_configuration.go b/internal/service/autoscaling/launch_configuration.go index c209554cb02..2048828769f 100644 --- a/internal/service/autoscaling/launch_configuration.go +++ b/internal/service/autoscaling/launch_configuration.go @@ -385,7 +385,7 @@ func resourceLaunchConfigurationCreate(d *schema.ResourceData, meta interface{}) rootDeviceName, err := findImageRootDeviceName(ec2conn, d.Get("image_id").(string)) if err != nil { - return err + return fmt.Errorf("creating Auto Scaling Launch Configuration (%s): %w", lcName, err) } var blockDeviceMappings []*autoscaling.BlockDeviceMapping @@ -500,7 +500,7 @@ func resourceLaunchConfigurationRead(d *schema.ResourceData, meta interface{}) e // Don't block a refresh for a bad image. rootDeviceName = "" } else if err != nil { - return err + return fmt.Errorf("reading Auto Scaling Launch Configuration (%s): %w", d.Id(), err) } configuredEBSBlockDevices := make(map[string]map[string]interface{}) diff --git a/internal/service/autoscaling/launch_configuration_data_source.go b/internal/service/autoscaling/launch_configuration_data_source.go index 2e289fe71b2..90216d8b6f3 100644 --- a/internal/service/autoscaling/launch_configuration_data_source.go +++ b/internal/service/autoscaling/launch_configuration_data_source.go @@ -234,7 +234,7 @@ func dataSourceLaunchConfigurationRead(d *schema.ResourceData, meta interface{}) rootDeviceName, err := findImageRootDeviceName(ec2conn, d.Get("image_id").(string)) if err != nil { - return err + return fmt.Errorf("reading Auto Scaling Launch Configuration (%s): %w", name, err) } tfListEBSBlockDevice, tfListEphemeralBlockDevice, tfListRootBlockDevice := flattenBlockDeviceMappings(lc.BlockDeviceMappings, rootDeviceName, map[string]map[string]interface{}{}) diff --git a/internal/service/autoscaling/notification.go b/internal/service/autoscaling/notification.go index cd749082867..b8701ca8a7e 100644 --- a/internal/service/autoscaling/notification.go +++ b/internal/service/autoscaling/notification.go @@ -45,7 +45,7 @@ func resourceNotificationCreate(d *schema.ResourceData, meta interface{}) error topic := d.Get("topic_arn").(string) if err := addNotificationConfigToGroupsWithTopic(conn, gl, nl, topic); err != nil { - return err + return fmt.Errorf("creating Autoscaling Group Notification (%s): %w", topic, err) } // ARNs are unique, and these notifications are per ARN, so we re-use the ARN @@ -92,7 +92,7 @@ func resourceNotificationRead(d *schema.ResourceData, meta interface{}) error { return true // return false to stop paging }) if err != nil { - return err + return fmt.Errorf("updating Autoscaling Group Notification (%s): %w", topic, err) } // Grab the keys here as the list of Groups @@ -108,10 +108,10 @@ func resourceNotificationRead(d *schema.ResourceData, meta interface{}) error { } if err := d.Set("group_names", gList); err != nil { - return err + return fmt.Errorf("updating Autoscaling Group Notification (%s): %w", topic, err) } if err := d.Set("notifications", nList); err != nil { - return err + return fmt.Errorf("updating Autoscaling Group Notification (%s): %w", topic, err) } return nil @@ -138,7 +138,7 @@ func resourceNotificationUpdate(d *schema.ResourceData, meta interface{}) error topic := d.Get("topic_arn").(string) if err := removeNotificationConfigToGroupsWithTopic(conn, remove, topic); err != nil { - return err + return fmt.Errorf("updating Autoscaling Group Notification (%s): %w", topic, err) } var update []*string @@ -149,16 +149,16 @@ func resourceNotificationUpdate(d *schema.ResourceData, meta interface{}) error } if err := addNotificationConfigToGroupsWithTopic(conn, update, nl, topic); err != nil { - return err + return fmt.Errorf("updating Autoscaling Group Notification (%s): %w", topic, err) } return resourceNotificationRead(d, meta) } func addNotificationConfigToGroupsWithTopic(conn *autoscaling.AutoScaling, groups []*string, nl []*string, topic string) error { - for _, a := range groups { + for _, group := range groups { opts := &autoscaling.PutNotificationConfigurationInput{ - AutoScalingGroupName: a, + AutoScalingGroupName: group, NotificationTypes: nl, TopicARN: aws.String(topic), } @@ -166,7 +166,7 @@ func addNotificationConfigToGroupsWithTopic(conn *autoscaling.AutoScaling, group _, err := conn.PutNotificationConfiguration(opts) if err != nil { - return fmt.Errorf("Error creating Autoscaling Group Notification for Group (%s): %w", aws.StringValue(a), err) + return fmt.Errorf("adding notifications for (%s): %w", aws.StringValue(group), err) } } @@ -174,15 +174,15 @@ func addNotificationConfigToGroupsWithTopic(conn *autoscaling.AutoScaling, group } func removeNotificationConfigToGroupsWithTopic(conn *autoscaling.AutoScaling, groups []*string, topic string) error { - for _, r := range groups { + for _, group := range groups { opts := &autoscaling.DeleteNotificationConfigurationInput{ - AutoScalingGroupName: r, + AutoScalingGroupName: group, TopicARN: aws.String(topic), } _, err := conn.DeleteNotificationConfiguration(opts) if err != nil { - return fmt.Errorf("Error deleting notification configuration for ASG \"%s\", Topic ARN \"%s\"", *r, topic) + return fmt.Errorf("removing notifications for (%s): %w", aws.StringValue(group), err) } } return nil @@ -194,6 +194,8 @@ func resourceNotificationDelete(d *schema.ResourceData, meta interface{}) error gl := flex.ExpandStringSet(d.Get("group_names").(*schema.Set)) topic := d.Get("topic_arn").(string) - err := removeNotificationConfigToGroupsWithTopic(conn, gl, topic) - return err + if err := removeNotificationConfigToGroupsWithTopic(conn, gl, topic); err != nil { + return fmt.Errorf("deleting Autoscaling Group Notification (%s): %w", topic, err) + } + return nil } diff --git a/internal/service/autoscaling/policy.go b/internal/service/autoscaling/policy.go index 23ee71de0b4..93d3188e695 100644 --- a/internal/service/autoscaling/policy.go +++ b/internal/service/autoscaling/policy.go @@ -419,7 +419,7 @@ func resourcePolicyCreate(d *schema.ResourceData, meta interface{}) error { input, err := getPutScalingPolicyInput(d) if err != nil { - return err + return fmt.Errorf("creating Auto Scaling Policy (%s): %w", name, err) } log.Printf("[DEBUG] Creating Auto Scaling Policy: %s", input) @@ -482,7 +482,7 @@ func resourcePolicyUpdate(d *schema.ResourceData, meta interface{}) error { input, err := getPutScalingPolicyInput(d) if err != nil { - return err + return fmt.Errorf("updating Auto Scaling Policy (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Updating Auto Scaling Policy: %s", input) From 0c176c3f38218085c9dc9a78d58ea6751e0d963a Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:51:13 -0800 Subject: [PATCH 094/106] Fixes bare errors in `athena` --- internal/service/athena/database.go | 24 ++++++++++++------------ internal/service/athena/database_test.go | 18 +++++++++--------- internal/service/athena/named_query.go | 10 ++++++---- 3 files changed, 27 insertions(+), 25 deletions(-) diff --git a/internal/service/athena/database.go b/internal/service/athena/database.go index 827d8d74303..0c4160deeee 100644 --- a/internal/service/athena/database.go +++ b/internal/service/athena/database.go @@ -135,11 +135,11 @@ func resourceDatabaseCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.StartQueryExecution(input) if err != nil { - return fmt.Errorf("error starting Athena Database (%s) query execution: %w", name, err) + return fmt.Errorf("creating Athena Database (%s): %w", name, err) } - if err := executeAndExpectNoRows(*resp.QueryExecutionId, "create", conn); err != nil { - return err + if err := executeAndExpectNoRows(conn, aws.StringValue(resp.QueryExecutionId)); err != nil { + return fmt.Errorf("creating Athena Database (%s): %w", name, err) } d.SetId(name) @@ -191,11 +191,11 @@ func resourceDatabaseDelete(d *schema.ResourceData, meta interface{}) error { resp, err := conn.StartQueryExecution(input) if err != nil { - return err + return fmt.Errorf("deleting Athena Database (%s): %w", d.Id(), err) } - if err := executeAndExpectNoRows(*resp.QueryExecutionId, "delete", conn); err != nil { - return err + if err := executeAndExpectNoRows(conn, aws.StringValue(resp.QueryExecutionId)); err != nil { + return fmt.Errorf("deleting Athena Database (%s): %w", d.Id(), err) } return nil @@ -250,22 +250,22 @@ func expandResultConfigurationACLConfig(config []interface{}) *athena.AclConfigu return encryptionConfig } -func executeAndExpectNoRows(qeid, action string, conn *athena.Athena) error { - rs, err := QueryExecutionResult(qeid, conn) +func executeAndExpectNoRows(conn *athena.Athena, qeid string) error { + rs, err := QueryExecutionResult(conn, qeid) if err != nil { return err } if len(rs.Rows) != 0 { - return fmt.Errorf("Athena %s database, unexpected query result: %s", action, flattenResultSet(rs)) + return fmt.Errorf("unexpected query result: %s", flattenResultSet(rs)) } return nil } -func QueryExecutionResult(qeid string, conn *athena.Athena) (*athena.ResultSet, error) { +func QueryExecutionResult(conn *athena.Athena, qeid string) (*athena.ResultSet, error) { executionStateConf := &resource.StateChangeConf{ Pending: []string{athena.QueryExecutionStateQueued, athena.QueryExecutionStateRunning}, Target: []string{athena.QueryExecutionStateSucceeded}, - Refresh: queryExecutionStateRefreshFunc(qeid, conn), + Refresh: queryExecutionStateRefreshFunc(conn, qeid), Timeout: 10 * time.Minute, Delay: 3 * time.Second, MinTimeout: 3 * time.Second, @@ -285,7 +285,7 @@ func QueryExecutionResult(qeid string, conn *athena.Athena) (*athena.ResultSet, return resp.ResultSet, nil } -func queryExecutionStateRefreshFunc(qeid string, conn *athena.Athena) resource.StateRefreshFunc { +func queryExecutionStateRefreshFunc(conn *athena.Athena, qeid string) resource.StateRefreshFunc { return func() (interface{}, string, error) { input := &athena.GetQueryExecutionInput{ QueryExecutionId: aws.String(qeid), diff --git a/internal/service/athena/database_test.go b/internal/service/athena/database_test.go index a2637a13eca..5ab5343a7fb 100644 --- a/internal/service/athena/database_test.go +++ b/internal/service/athena/database_test.go @@ -356,7 +356,7 @@ func testAccDatabaseCreateTables(dbName string) resource.TestCheckFunc { return err } - athenaconn := acctest.Provider.Meta().(*conns.AWSClient).AthenaConn() + conn := acctest.Provider.Meta().(*conns.AWSClient).AthenaConn() input := &athena.StartQueryExecutionInput{ QueryExecutionContext: &athena.QueryExecutionContext{ @@ -369,12 +369,12 @@ func testAccDatabaseCreateTables(dbName string) resource.TestCheckFunc { }, } - resp, err := athenaconn.StartQueryExecution(input) + resp, err := conn.StartQueryExecution(input) if err != nil { return err } - _, err = tfathena.QueryExecutionResult(*resp.QueryExecutionId, athenaconn) + _, err = tfathena.QueryExecutionResult(conn, aws.StringValue(resp.QueryExecutionId)) return err } } @@ -386,7 +386,7 @@ func testAccDatabaseDestroyTables(dbName string) resource.TestCheckFunc { return err } - athenaconn := acctest.Provider.Meta().(*conns.AWSClient).AthenaConn() + conn := acctest.Provider.Meta().(*conns.AWSClient).AthenaConn() input := &athena.StartQueryExecutionInput{ QueryExecutionContext: &athena.QueryExecutionContext{ @@ -398,12 +398,12 @@ func testAccDatabaseDestroyTables(dbName string) resource.TestCheckFunc { }, } - resp, err := athenaconn.StartQueryExecution(input) + resp, err := conn.StartQueryExecution(input) if err != nil { return err } - _, err = tfathena.QueryExecutionResult(*resp.QueryExecutionId, athenaconn) + _, err = tfathena.QueryExecutionResult(conn, aws.StringValue(resp.QueryExecutionId)) return err } } @@ -415,7 +415,7 @@ func testAccCheckDatabaseDropFails(dbName string) resource.TestCheckFunc { return err } - athenaconn := acctest.Provider.Meta().(*conns.AWSClient).AthenaConn() + conn := acctest.Provider.Meta().(*conns.AWSClient).AthenaConn() input := &athena.StartQueryExecutionInput{ QueryExecutionContext: &athena.QueryExecutionContext{ @@ -427,12 +427,12 @@ func testAccCheckDatabaseDropFails(dbName string) resource.TestCheckFunc { }, } - resp, err := athenaconn.StartQueryExecution(input) + resp, err := conn.StartQueryExecution(input) if err != nil { return err } - _, err = tfathena.QueryExecutionResult(*resp.QueryExecutionId, athenaconn) + _, err = tfathena.QueryExecutionResult(conn, aws.StringValue(resp.QueryExecutionId)) if err == nil { return fmt.Errorf("drop database unexpectedly succeeded for a database with tables") } diff --git a/internal/service/athena/named_query.go b/internal/service/athena/named_query.go index da06aa6e616..eec9bcffcec 100644 --- a/internal/service/athena/named_query.go +++ b/internal/service/athena/named_query.go @@ -69,7 +69,7 @@ func resourceNamedQueryCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateNamedQuery(input) if err != nil { - return err + return fmt.Errorf("creating Athena Named Query (%s): %w", d.Get("name").(string), err) } d.SetId(aws.StringValue(resp.NamedQueryId)) return resourceNamedQueryRead(d, meta) @@ -89,7 +89,7 @@ func resourceNamedQueryRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error getting Athena Named Query (%s): %w", d.Id(), err) + return fmt.Errorf("reading Athena Named Query (%s): %w", d.Id(), err) } d.Set("name", resp.NamedQuery.Name) @@ -107,6 +107,8 @@ func resourceNamedQueryDelete(d *schema.ResourceData, meta interface{}) error { NamedQueryId: aws.String(d.Id()), } - _, err := conn.DeleteNamedQuery(input) - return err + if _, err := conn.DeleteNamedQuery(input); err != nil { + return fmt.Errorf("deleting Athena Named Query (%s): %w", d.Id(), err) + } + return nil } From b7f88ff15bb20af8fbd906ffe97b2303e186a7aa Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:51:31 -0800 Subject: [PATCH 095/106] Fixes bare errors in `appsync` --- internal/service/appsync/api_key.go | 12 ++++++------ internal/service/appsync/datasource.go | 13 +++++++------ internal/service/appsync/function.go | 12 ++++++------ internal/service/appsync/graphql_api.go | 4 ++-- internal/service/appsync/resolver.go | 8 ++++---- internal/service/appsync/type.go | 4 ++-- 6 files changed, 27 insertions(+), 26 deletions(-) diff --git a/internal/service/appsync/api_key.go b/internal/service/appsync/api_key.go index dbe9a0dc6f3..10664fd6c05 100644 --- a/internal/service/appsync/api_key.go +++ b/internal/service/appsync/api_key.go @@ -82,12 +82,12 @@ func resourceAPIKeyRead(d *schema.ResourceData, meta interface{}) error { apiID, keyID, err := DecodeAPIKeyID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Appsync API Key (%s): %s", d.Id(), err) } key, err := GetAPIKey(apiID, keyID, conn) if err != nil { - return fmt.Errorf("error getting Appsync API Key %q: %s", d.Id(), err) + return fmt.Errorf("reading Appsync API Key (%s): %s", d.Id(), err) } if key == nil && !d.IsNewResource() { log.Printf("[WARN] AppSync API Key (%s) not found, removing from state", d.Id()) @@ -107,7 +107,7 @@ func resourceAPIKeyUpdate(d *schema.ResourceData, meta interface{}) error { apiID, keyID, err := DecodeAPIKeyID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Appsync API Key (%s): %s", d.Id(), err) } params := &appsync.UpdateApiKeyInput{ @@ -124,7 +124,7 @@ func resourceAPIKeyUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateApiKey(params) if err != nil { - return err + return fmt.Errorf("updating Appsync API Key (%s): %s", d.Id(), err) } return resourceAPIKeyRead(d, meta) @@ -135,7 +135,7 @@ func resourceAPIKeyDelete(d *schema.ResourceData, meta interface{}) error { apiID, keyID, err := DecodeAPIKeyID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Appsync API Key (%s): %s", d.Id(), err) } input := &appsync.DeleteApiKeyInput{ @@ -147,7 +147,7 @@ func resourceAPIKeyDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, appsync.ErrCodeNotFoundException) { return nil } - return err + return fmt.Errorf("deleting Appsync API Key (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/appsync/datasource.go b/internal/service/appsync/datasource.go index a81c35eda5d..feb7bbd7314 100644 --- a/internal/service/appsync/datasource.go +++ b/internal/service/appsync/datasource.go @@ -289,7 +289,7 @@ func resourceDataSourceRead(d *schema.ResourceData, meta interface{}) error { apiID, name, err := DecodeID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Appsync Data Source (%s): %s", d.Id(), err) } input := &appsync.GetDataSourceInput{ @@ -304,7 +304,7 @@ func resourceDataSourceRead(d *schema.ResourceData, meta interface{}) error { d.SetId("") return nil } - return err + return fmt.Errorf("reading Appsync Data Source (%s): %s", d.Id(), err) } dataSource := resp.DataSource @@ -347,7 +347,7 @@ func resourceDataSourceUpdate(d *schema.ResourceData, meta interface{}) error { apiID, name, err := DecodeID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating Appsync Data Source (%s): %s", d.Id(), err) } input := &appsync.UpdateDataSourceInput{ @@ -386,8 +386,9 @@ func resourceDataSourceUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateDataSource(input) if err != nil { - return err + return fmt.Errorf("updating Appsync Data Source (%s): %s", d.Id(), err) } + return resourceDataSourceRead(d, meta) } @@ -397,7 +398,7 @@ func resourceDataSourceDelete(d *schema.ResourceData, meta interface{}) error { apiID, name, err := DecodeID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Appsync Data Source (%s): %s", d.Id(), err) } input := &appsync.DeleteDataSourceInput{ @@ -410,7 +411,7 @@ func resourceDataSourceDelete(d *schema.ResourceData, meta interface{}) error { if tfawserr.ErrCodeEquals(err, appsync.ErrCodeNotFoundException) { return nil } - return err + return fmt.Errorf("deleting Appsync Data Source (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/appsync/function.go b/internal/service/appsync/function.go index 07f0588eb47..a8982d629e0 100644 --- a/internal/service/appsync/function.go +++ b/internal/service/appsync/function.go @@ -192,7 +192,7 @@ func resourceFunctionRead(d *schema.ResourceData, meta interface{}) error { apiID, functionID, err := DecodeFunctionID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AppSync Function (%s): %w", d.Id(), err) } input := &appsync.GetFunctionInput{ @@ -207,7 +207,7 @@ func resourceFunctionRead(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error getting AppSync Function %s: %w", d.Id(), err) + return fmt.Errorf("reading AppSync Function (%s): %w", d.Id(), err) } function := resp.FunctionConfiguration @@ -239,7 +239,7 @@ func resourceFunctionUpdate(d *schema.ResourceData, meta interface{}) error { apiID, functionID, err := DecodeFunctionID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating AppSync Function (%s): %w", d.Id(), err) } input := &appsync.UpdateFunctionInput{ @@ -280,7 +280,7 @@ func resourceFunctionUpdate(d *schema.ResourceData, meta interface{}) error { _, err = conn.UpdateFunction(input) if err != nil { - return fmt.Errorf("error updating AppSync Function %s: %w", d.Id(), err) + return fmt.Errorf("updating AppSync Function (%s): %w", d.Id(), err) } return resourceFunctionRead(d, meta) @@ -291,7 +291,7 @@ func resourceFunctionDelete(d *schema.ResourceData, meta interface{}) error { apiID, functionID, err := DecodeFunctionID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting AppSync Function (%s): %w", d.Id(), err) } input := &appsync.DeleteFunctionInput{ @@ -304,7 +304,7 @@ func resourceFunctionDelete(d *schema.ResourceData, meta interface{}) error { return nil } if err != nil { - return fmt.Errorf("error deleting AppSync Function %s: %w", d.Id(), err) + return fmt.Errorf("deleting AppSync Function (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/appsync/graphql_api.go b/internal/service/appsync/graphql_api.go index b94f94a5b7a..11b6661e5a8 100644 --- a/internal/service/appsync/graphql_api.go +++ b/internal/service/appsync/graphql_api.go @@ -709,7 +709,7 @@ func resourceSchemaPut(d *schema.ResourceData, meta interface{}) error { Definition: ([]byte)(v.(string)), } if _, err := conn.StartSchemaCreation(input); err != nil { - return err + return err // nosemgrep:bare-error-returns } activeSchemaConfig := &resource.StateChangeConf{ @@ -728,7 +728,7 @@ func resourceSchemaPut(d *schema.ResourceData, meta interface{}) error { } if _, err := activeSchemaConfig.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for schema creation status on AppSync API %s: %s", d.Id(), err) + return fmt.Errorf("waiting for completion: %s", err) } } diff --git a/internal/service/appsync/resolver.go b/internal/service/appsync/resolver.go index 29ecf6a8fcf..ef6ad5b29d5 100644 --- a/internal/service/appsync/resolver.go +++ b/internal/service/appsync/resolver.go @@ -241,7 +241,7 @@ func resourceResolverRead(d *schema.ResourceData, meta interface{}) error { apiID, typeName, fieldName, err := DecodeResolverID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AppSync Resolver (%s): %w", d.Id(), err) } input := &appsync.GetResolverInput{ @@ -259,7 +259,7 @@ func resourceResolverRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error getting AppSync Resolver (%s): %w", d.Id(), err) + return fmt.Errorf("reading AppSync Resolver (%s): %w", d.Id(), err) } resolver := resp.Resolver @@ -363,7 +363,7 @@ func resourceResolverDelete(d *schema.ResourceData, meta interface{}) error { apiID, typeName, fieldName, err := DecodeResolverID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting AppSync Resolver (%s): %s", d.Id(), err) } input := &appsync.DeleteResolverInput{ @@ -381,7 +381,7 @@ func resourceResolverDelete(d *schema.ResourceData, meta interface{}) error { }, appsync.ErrCodeConcurrentModificationException) if err != nil { - return fmt.Errorf("error deleting AppSync Resolver (%s): %s", d.Id(), err) + return fmt.Errorf("deleting AppSync Resolver (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/appsync/type.go b/internal/service/appsync/type.go index a3ec2171030..bacfbc217cc 100644 --- a/internal/service/appsync/type.go +++ b/internal/service/appsync/type.go @@ -81,7 +81,7 @@ func resourceTypeRead(d *schema.ResourceData, meta interface{}) error { apiID, format, name, err := DecodeTypeID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading Appsync Type %q: %s", d.Id(), err) } resp, err := FindTypeByID(conn, apiID, format, name) @@ -92,7 +92,7 @@ func resourceTypeRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error getting Appsync Type %q: %s", d.Id(), err) + return fmt.Errorf("reading Appsync Type %q: %s", d.Id(), err) } d.Set("api_id", apiID) From 7514e74630293cd245a3e8f0b2f92eee798f2aed Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:51:46 -0800 Subject: [PATCH 096/106] Fixes bare errors in `appintegrations` --- internal/service/appintegrations/event_integration.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/service/appintegrations/event_integration.go b/internal/service/appintegrations/event_integration.go index e2aea6edec2..bdc96fd15c2 100644 --- a/internal/service/appintegrations/event_integration.go +++ b/internal/service/appintegrations/event_integration.go @@ -171,7 +171,7 @@ func resourceEventIntegrationUpdate(ctx context.Context, d *schema.ResourceData, }) if err != nil { - return diag.FromErr(fmt.Errorf("[ERROR] Error updating EventIntegration (%s): %w", d.Id(), err)) + return diag.FromErr(fmt.Errorf("updating EventIntegration (%s): %w", d.Id(), err)) } } From 42e281275926673536ea4ac4acda0e6fb1da5ac1 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:52:00 -0800 Subject: [PATCH 097/106] Fixes bare errors in `appconfig` --- internal/service/appconfig/configuration_profile.go | 10 +++++----- internal/service/appconfig/deployment.go | 6 +++--- internal/service/appconfig/environment.go | 10 +++++----- .../service/appconfig/hosted_configuration_version.go | 10 +++++----- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/internal/service/appconfig/configuration_profile.go b/internal/service/appconfig/configuration_profile.go index f1ca0701a2a..d679dcab73d 100644 --- a/internal/service/appconfig/configuration_profile.go +++ b/internal/service/appconfig/configuration_profile.go @@ -155,7 +155,7 @@ func resourceConfigurationProfileRead(d *schema.ResourceData, meta interface{}) confProfID, appID, err := ConfigurationProfileParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AppConfig Configuration Profile (%s): %w", d.Id(), err) } input := &appconfig.GetConfigurationProfileInput{ @@ -172,11 +172,11 @@ func resourceConfigurationProfileRead(d *schema.ResourceData, meta interface{}) } if err != nil { - return fmt.Errorf("error getting AppConfig Configuration Profile (%s) for Application (%s): %w", confProfID, appID, err) + return fmt.Errorf("reading AppConfig Configuration Profile (%s) for Application (%s): %w", confProfID, appID, err) } if output == nil { - return fmt.Errorf("error getting AppConfig Configuration Profile (%s) for Application (%s): empty response", confProfID, appID) + return fmt.Errorf("reading AppConfig Configuration Profile (%s) for Application (%s): empty response", confProfID, appID) } d.Set("application_id", output.ApplicationId) @@ -227,7 +227,7 @@ func resourceConfigurationProfileUpdate(d *schema.ResourceData, meta interface{} confProfID, appID, err := ConfigurationProfileParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating AppConfig Configuration Profile (%s): %w", d.Id(), err) } updateInput := &appconfig.UpdateConfigurationProfileInput{ @@ -274,7 +274,7 @@ func resourceConfigurationProfileDelete(d *schema.ResourceData, meta interface{} confProfID, appID, err := ConfigurationProfileParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting AppConfig Configuration Profile (%s): %w", d.Id(), err) } input := &appconfig.DeleteConfigurationProfileInput{ diff --git a/internal/service/appconfig/deployment.go b/internal/service/appconfig/deployment.go index 7791ace49a3..e1b6aaa536a 100644 --- a/internal/service/appconfig/deployment.go +++ b/internal/service/appconfig/deployment.go @@ -126,7 +126,7 @@ func resourceDeploymentRead(d *schema.ResourceData, meta interface{}) error { appID, envID, deploymentNum, err := DeploymentParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AppConfig Deployment (%s): %w", d.Id(), err) } input := &appconfig.GetDeploymentInput{ @@ -144,11 +144,11 @@ func resourceDeploymentRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error getting AppConfig Deployment (%s): %w", d.Id(), err) + return fmt.Errorf("reading AppConfig Deployment (%s): %w", d.Id(), err) } if output == nil { - return fmt.Errorf("error getting AppConfig Deployment (%s): empty response", d.Id()) + return fmt.Errorf("reading AppConfig Deployment (%s): empty response", d.Id()) } arn := arn.ARN{ diff --git a/internal/service/appconfig/environment.go b/internal/service/appconfig/environment.go index 82f7b6ba0f8..3faf51df542 100644 --- a/internal/service/appconfig/environment.go +++ b/internal/service/appconfig/environment.go @@ -130,7 +130,7 @@ func resourceEnvironmentRead(d *schema.ResourceData, meta interface{}) error { envID, appID, err := EnvironmentParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AppConfig Environment (%s): %w", d.Id(), err) } input := &appconfig.GetEnvironmentInput{ @@ -147,11 +147,11 @@ func resourceEnvironmentRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error getting AppConfig Environment (%s) for Application (%s): %w", envID, appID, err) + return fmt.Errorf("reading AppConfig Environment (%s) for Application (%s): %w", envID, appID, err) } if output == nil { - return fmt.Errorf("error getting AppConfig Environment (%s) for Application (%s): empty response", envID, appID) + return fmt.Errorf("reading AppConfig Environment (%s) for Application (%s): empty response", envID, appID) } d.Set("application_id", output.ApplicationId) @@ -201,7 +201,7 @@ func resourceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error { envID, appID, err := EnvironmentParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating AppConfig Environment (%s): %w", d.Id(), err) } updateInput := &appconfig.UpdateEnvironmentInput{ @@ -244,7 +244,7 @@ func resourceEnvironmentDelete(d *schema.ResourceData, meta interface{}) error { envID, appID, err := EnvironmentParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting AppConfig Environment (%s): %w", d.Id(), err) } input := &appconfig.DeleteEnvironmentInput{ diff --git a/internal/service/appconfig/hosted_configuration_version.go b/internal/service/appconfig/hosted_configuration_version.go index 363fdbcdcef..fce8bda0399 100644 --- a/internal/service/appconfig/hosted_configuration_version.go +++ b/internal/service/appconfig/hosted_configuration_version.go @@ -102,7 +102,7 @@ func resourceHostedConfigurationVersionRead(d *schema.ResourceData, meta interfa appID, confProfID, versionNumber, err := HostedConfigurationVersionParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading AppConfig Hosted Configuration Version (%s): %w", d.Id(), err) } input := &appconfig.GetHostedConfigurationVersionInput{ @@ -120,11 +120,11 @@ func resourceHostedConfigurationVersionRead(d *schema.ResourceData, meta interfa } if err != nil { - return fmt.Errorf("error getting AppConfig Hosted Configuration Version (%s): %w", d.Id(), err) + return fmt.Errorf("reading AppConfig Hosted Configuration Version (%s): %w", d.Id(), err) } if output == nil { - return fmt.Errorf("error getting AppConfig Hosted Configuration Version (%s): empty response", d.Id()) + return fmt.Errorf("reading AppConfig Hosted Configuration Version (%s): empty response", d.Id()) } d.Set("application_id", output.ApplicationId) @@ -153,7 +153,7 @@ func resourceHostedConfigurationVersionDelete(d *schema.ResourceData, meta inter appID, confProfID, versionNumber, err := HostedConfigurationVersionParseID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting Appconfig Hosted Configuration Version (%s): %w", d.Id(), err) } input := &appconfig.DeleteHostedConfigurationVersionInput{ @@ -169,7 +169,7 @@ func resourceHostedConfigurationVersionDelete(d *schema.ResourceData, meta inter } if err != nil { - return fmt.Errorf("error deleting Appconfig Hosted Configuration Version (%s): %w", d.Id(), err) + return fmt.Errorf("deleting Appconfig Hosted Configuration Version (%s): %w", d.Id(), err) } return nil From ae435bd97677a04e2b94be14b2b8bf5e3a52bdab Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:52:13 -0800 Subject: [PATCH 098/106] Fixes bare errors in `appautoscaling` --- internal/service/appautoscaling/policy.go | 2 +- internal/service/appautoscaling/scheduled_action.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/appautoscaling/policy.go b/internal/service/appautoscaling/policy.go index 44eab5bdb89..f307c12af95 100644 --- a/internal/service/appautoscaling/policy.go +++ b/internal/service/appautoscaling/policy.go @@ -214,7 +214,7 @@ func resourcePolicyCreate(d *schema.ResourceData, meta interface{}) error { params, err := getPutScalingPolicyInput(d) if err != nil { - return err + return create.Error(names.AppAutoScaling, create.ErrActionCreating, ResNamePolicy, d.Get("name").(string), err) } log.Printf("[DEBUG] ApplicationAutoScaling PutScalingPolicy: %#v", params) diff --git a/internal/service/appautoscaling/scheduled_action.go b/internal/service/appautoscaling/scheduled_action.go index 052a502f3af..8bb4e91000c 100644 --- a/internal/service/appautoscaling/scheduled_action.go +++ b/internal/service/appautoscaling/scheduled_action.go @@ -244,7 +244,7 @@ func resourceScheduledActionDelete(d *schema.ResourceData, meta interface{}) err log.Printf("[WARN] Application Auto Scaling scheduled action (%s) not found, removing from state", d.Id()) return nil } - return err + return fmt.Errorf("deleting Application Auto Scaling Scheduled Action (%s): %w", d.Id(), err) } return nil From 674817ba23cc0c0693be77bf8b576c128acfd6da Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:52:32 -0800 Subject: [PATCH 099/106] Fixes bare errors in `apigatewayv2` --- internal/service/apigatewayv2/api.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/internal/service/apigatewayv2/api.go b/internal/service/apigatewayv2/api.go index fd3a270ddcb..9f863adee96 100644 --- a/internal/service/apigatewayv2/api.go +++ b/internal/service/apigatewayv2/api.go @@ -179,7 +179,7 @@ func resourceImportOpenAPI(d *schema.ResourceData, meta interface{}) error { _, err := conn.ReimportApi(importReq) if err != nil { - return fmt.Errorf("error importing API Gateway v2 API (%s) OpenAPI specification: %s", d.Id(), err) + return fmt.Errorf("importing API Gateway v2 API (%s) OpenAPI specification: %s", d.Id(), err) } tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{}))) @@ -187,7 +187,7 @@ func resourceImportOpenAPI(d *schema.ResourceData, meta interface{}) error { corsConfiguration := d.Get("cors_configuration") if err := resourceAPIRead(d, meta); err != nil { - return err + return fmt.Errorf("importing API Gateway v2 API (%s) OpenAPI specification: %s", d.Id(), err) } if !reflect.DeepEqual(corsConfiguration, d.Get("cors_configuration")) { @@ -257,17 +257,16 @@ func resourceAPICreate(d *schema.ResourceData, meta interface{}) error { req.Version = aws.String(v.(string)) } - log.Printf("[DEBUG] Creating API Gateway v2 API: %s", req) resp, err := conn.CreateApi(req) if err != nil { - return fmt.Errorf("error creating API Gateway v2 API: %s", err) + return fmt.Errorf("creating API Gateway v2 API (%s): %s", d.Get("name").(string), err) } d.SetId(aws.StringValue(resp.ApiId)) err = resourceImportOpenAPI(d, meta) if err != nil { - return err + return fmt.Errorf("creating API Gateway v2 API (%s): %s", d.Get("name").(string), err) } return resourceAPIRead(d, meta) @@ -395,7 +394,7 @@ func resourceAPIUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("body") { err := resourceImportOpenAPI(d, meta) if err != nil { - return err + return fmt.Errorf("updating API Gateway v2 API (%s): %s", d.Id(), err) } } From 362c59d73a4a60ca4a752a63a6cefe79984b0f2e Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:52:38 -0800 Subject: [PATCH 100/106] Fixes bare errors in `apigateway` --- internal/service/apigateway/account.go | 7 +++--- internal/service/apigateway/api_key.go | 2 +- .../service/apigateway/api_key_data_source.go | 2 +- internal/service/apigateway/authorizer.go | 4 ++-- .../service/apigateway/base_path_mapping.go | 8 +++---- internal/service/apigateway/deployment.go | 2 +- .../service/apigateway/documentation_part.go | 23 ++++++++----------- .../apigateway/documentation_version.go | 11 +++++---- internal/service/apigateway/domain_name.go | 4 ++-- .../service/apigateway/export_data_source.go | 2 +- internal/service/apigateway/method.go | 8 +++---- .../service/apigateway/method_response.go | 8 +++---- internal/service/apigateway/model.go | 7 +++--- .../service/apigateway/request_validator.go | 4 ++-- internal/service/apigateway/resource.go | 4 ++-- .../apigateway/rest_api_data_source.go | 5 +++- .../service/apigateway/sdk_data_source.go | 2 +- internal/service/apigateway/vpc_link.go | 11 +++++---- 18 files changed, 57 insertions(+), 57 deletions(-) diff --git a/internal/service/apigateway/account.go b/internal/service/apigateway/account.go index b8dc39ffefa..bf0de59a5f0 100644 --- a/internal/service/apigateway/account.go +++ b/internal/service/apigateway/account.go @@ -51,10 +51,9 @@ func ResourceAccount() *schema.Resource { func resourceAccountRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*conns.AWSClient).APIGatewayConn() - log.Printf("[INFO] Reading API Gateway Account %s", d.Id()) account, err := conn.GetAccount(&apigateway.GetAccountInput{}) if err != nil { - return err + return fmt.Errorf("reading API Gateway Account: %w", err) } log.Printf("[DEBUG] Received API Gateway Account: %s", account) @@ -65,7 +64,9 @@ func resourceAccountRead(d *schema.ResourceData, meta interface{}) error { // (e.g. for referencing throttle_settings) d.Set("cloudwatch_role_arn", account.CloudwatchRoleArn) } - d.Set("throttle_settings", FlattenThrottleSettings(account.ThrottleSettings)) + if err := d.Set("throttle_settings", FlattenThrottleSettings(account.ThrottleSettings)); err != nil { + return fmt.Errorf("reading API Gateway Account: %w", err) + } return nil } diff --git a/internal/service/apigateway/api_key.go b/internal/service/apigateway/api_key.go index adf99370635..3014ad4c1ec 100644 --- a/internal/service/apigateway/api_key.go +++ b/internal/service/apigateway/api_key.go @@ -195,7 +195,7 @@ func resourceAPIKeyUpdate(d *schema.ResourceData, meta interface{}) error { PatchOperations: resourceAPIKeyUpdateOperations(d), }) if err != nil { - return err + return fmt.Errorf("updating API Gateway API Key (%s): %w", d.Id(), err) } return resourceAPIKeyRead(d, meta) diff --git a/internal/service/apigateway/api_key_data_source.go b/internal/service/apigateway/api_key_data_source.go index d4e796bf91a..f5361146d58 100644 --- a/internal/service/apigateway/api_key_data_source.go +++ b/internal/service/apigateway/api_key_data_source.go @@ -59,7 +59,7 @@ func dataSourceAPIKeyRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("reading API Gateway API Key (%s): %w", d.Get("id").(string), err) } d.SetId(aws.StringValue(apiKey.Id)) diff --git a/internal/service/apigateway/authorizer.go b/internal/service/apigateway/authorizer.go index d55cb2e68f6..6df30c73a6a 100644 --- a/internal/service/apigateway/authorizer.go +++ b/internal/service/apigateway/authorizer.go @@ -110,7 +110,7 @@ func resourceAuthorizerCreate(d *schema.ResourceData, meta interface{}) error { } if err := validateAuthorizerType(d); err != nil { - return err + return fmt.Errorf("creating API Gateway Authorizer: %w", err) } if v, ok := d.GetOk("authorizer_uri"); ok { input.AuthorizerUri = aws.String(v.(string)) @@ -141,7 +141,7 @@ func resourceAuthorizerCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[INFO] Creating API Gateway Authorizer: %s", input) out, err := conn.CreateAuthorizer(&input) if err != nil { - return fmt.Errorf("error creating API Gateway Authorizer: %w", err) + return fmt.Errorf("creating API Gateway Authorizer: %w", err) } d.SetId(aws.StringValue(out.Id)) diff --git a/internal/service/apigateway/base_path_mapping.go b/internal/service/apigateway/base_path_mapping.go index be9957a5390..8707d947522 100644 --- a/internal/service/apigateway/base_path_mapping.go +++ b/internal/service/apigateway/base_path_mapping.go @@ -151,7 +151,7 @@ func resourceBasePathMappingRead(d *schema.ResourceData, meta interface{}) error domainName, basePath, err := DecodeBasePathMappingID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading API Gateway Base Path Mapping (%s): %w", d.Id(), err) } mapping, err := conn.GetBasePathMapping(&apigateway.GetBasePathMappingInput{ @@ -165,7 +165,7 @@ func resourceBasePathMappingRead(d *schema.ResourceData, meta interface{}) error return nil } - return fmt.Errorf("error reading API Gateway Base Path Mapping (%s): %w", d.Id(), err) + return fmt.Errorf("reading API Gateway Base Path Mapping (%s): %w", d.Id(), err) } mappingBasePath := aws.StringValue(mapping.BasePath) @@ -187,7 +187,7 @@ func resourceBasePathMappingDelete(d *schema.ResourceData, meta interface{}) err domainName, basePath, err := DecodeBasePathMappingID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting API Gateway Base Path Mapping (%s): %w", d.Id(), err) } _, err = conn.DeleteBasePathMapping(&apigateway.DeleteBasePathMappingInput{ @@ -200,7 +200,7 @@ func resourceBasePathMappingDelete(d *schema.ResourceData, meta interface{}) err return nil } - return err + return fmt.Errorf("deleting API Gateway Base Path Mapping (%s): %w", d.Id(), err) } return nil diff --git a/internal/service/apigateway/deployment.go b/internal/service/apigateway/deployment.go index 42014fdcc05..d1f4c676f3e 100644 --- a/internal/service/apigateway/deployment.go +++ b/internal/service/apigateway/deployment.go @@ -171,7 +171,7 @@ func resourceDeploymentUpdate(d *schema.ResourceData, meta interface{}) error { PatchOperations: resourceDeploymentUpdateOperations(d), }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Deployment (%s): %w", d.Id(), err) } return resourceDeploymentRead(d, meta) diff --git a/internal/service/apigateway/documentation_part.go b/internal/service/apigateway/documentation_part.go index 131529a96e6..c923705aeeb 100644 --- a/internal/service/apigateway/documentation_part.go +++ b/internal/service/apigateway/documentation_part.go @@ -82,9 +82,9 @@ func resourceDocumentationPartCreate(d *schema.ResourceData, meta interface{}) e RestApiId: aws.String(apiId), }) if err != nil { - return err + return fmt.Errorf("reading API Gateway Documentation Part: %w", err) } - d.SetId(apiId + "/" + *out.Id) + d.SetId(apiId + "/" + aws.StringValue(out.Id)) return nil } @@ -96,7 +96,7 @@ func resourceDocumentationPartRead(d *schema.ResourceData, meta interface{}) err apiId, id, err := DecodeDocumentationPartID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading API Gateway Documentation Part (%s): %w", d.Id(), err) } docPart, err := conn.GetDocumentationPart(&apigateway.GetDocumentationPartInput{ @@ -109,7 +109,7 @@ func resourceDocumentationPartRead(d *schema.ResourceData, meta interface{}) err d.SetId("") return nil } - return fmt.Errorf("error reading API Gateway Documentation Part (%s): %w", d.Id(), err) + return fmt.Errorf("reading API Gateway Documentation Part (%s): %w", d.Id(), err) } d.Set("rest_api_id", apiId) @@ -124,7 +124,7 @@ func resourceDocumentationPartUpdate(d *schema.ResourceData, meta interface{}) e apiId, id, err := DecodeDocumentationPartID(d.Id()) if err != nil { - return err + return fmt.Errorf("updating API Gateway Documentation Part (%s): %w", d.Id(), err) } input := apigateway.UpdateDocumentationPartInput{ @@ -144,15 +144,10 @@ func resourceDocumentationPartUpdate(d *schema.ResourceData, meta interface{}) e input.PatchOperations = operations - log.Printf("[INFO] Updating API Gateway Documentation Part: %s", input) - - out, err := conn.UpdateDocumentationPart(&input) - if err != nil { - return err + if _, err := conn.UpdateDocumentationPart(&input); err != nil { + return fmt.Errorf("updating API Gateway Documentation Part (%s): %w", d.Id(), err) } - log.Printf("[DEBUG] API Gateway Documentation Part updated: %s", out) - return resourceDocumentationPartRead(d, meta) } @@ -161,14 +156,14 @@ func resourceDocumentationPartDelete(d *schema.ResourceData, meta interface{}) e apiId, id, err := DecodeDocumentationPartID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting API Gateway Documentation Part (%s): %w", d.Id(), err) } _, err = conn.DeleteDocumentationPart(&apigateway.DeleteDocumentationPartInput{ DocumentationPartId: aws.String(id), RestApiId: aws.String(apiId), }) - return err + return fmt.Errorf("deleting API Gateway Documentation Part (%s): %w", d.Id(), err) } func expandDocumentationPartLocation(l []interface{}) *apigateway.DocumentationPartLocation { diff --git a/internal/service/apigateway/documentation_version.go b/internal/service/apigateway/documentation_version.go index 4c3a981905c..e05e04e9b8a 100644 --- a/internal/service/apigateway/documentation_version.go +++ b/internal/service/apigateway/documentation_version.go @@ -73,7 +73,7 @@ func resourceDocumentationVersionRead(d *schema.ResourceData, meta interface{}) apiId, docVersion, err := DecodeDocumentationVersionID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading API Gateway Documentation Version (%s): %w", d.Id(), err) } version, err := conn.GetDocumentationVersion(&apigateway.GetDocumentationVersionInput{ @@ -86,7 +86,7 @@ func resourceDocumentationVersionRead(d *schema.ResourceData, meta interface{}) d.SetId("") return nil } - return fmt.Errorf("error reading API Gateway Documentation Version (%s): %w", d.Id(), err) + return fmt.Errorf("reading API Gateway Documentation Version (%s): %w", d.Id(), err) } d.Set("rest_api_id", apiId) @@ -112,7 +112,7 @@ func resourceDocumentationVersionUpdate(d *schema.ResourceData, meta interface{} }, }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Documentation Version (%s): %w", d.Id(), err) } log.Printf("[DEBUG] Updated API Gateway Documentation Version %s", d.Id()) @@ -127,7 +127,10 @@ func resourceDocumentationVersionDelete(d *schema.ResourceData, meta interface{} DocumentationVersion: aws.String(d.Get("version").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), }) - return err + if err != nil { + return fmt.Errorf("deleting API Gateway Documentation Version (%s): %w", d.Id(), err) + } + return nil } func DecodeDocumentationVersionID(id string) (string, string, error) { diff --git a/internal/service/apigateway/domain_name.go b/internal/service/apigateway/domain_name.go index c20d7256b7a..a9ea57cf3c7 100644 --- a/internal/service/apigateway/domain_name.go +++ b/internal/service/apigateway/domain_name.go @@ -406,7 +406,7 @@ func resourceDomainNameUpdate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Domain Name (%s): %s", d.Id(), err) } return resourceDomainNameRead(d, meta) @@ -425,7 +425,7 @@ func resourceDomainNameDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("Error deleting API Gateway domain name: %s", err) + return fmt.Errorf("deleting API Gateway Domain Name (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/apigateway/export_data_source.go b/internal/service/apigateway/export_data_source.go index 12ca78ee378..c63ff0dbd76 100644 --- a/internal/service/apigateway/export_data_source.go +++ b/internal/service/apigateway/export_data_source.go @@ -76,7 +76,7 @@ func dataSourceExportRead(d *schema.ResourceData, meta interface{}) error { export, err := conn.GetExport(input) if err != nil { - return err + return fmt.Errorf("reading API Gateway Export: %w", err) } d.SetId(fmt.Sprintf("%s:%s", restApiId, stageName)) diff --git a/internal/service/apigateway/method.go b/internal/service/apigateway/method.go index 7e4a3378c3d..890dc484b67 100644 --- a/internal/service/apigateway/method.go +++ b/internal/service/apigateway/method.go @@ -316,7 +316,7 @@ func resourceMethodUpdate(d *schema.ResourceData, meta interface{}) error { }) } - method, err := conn.UpdateMethod(&apigateway.UpdateMethodInput{ + _, err := conn.UpdateMethod(&apigateway.UpdateMethodInput{ HttpMethod: aws.String(d.Get("http_method").(string)), ResourceId: aws.String(d.Get("resource_id").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), @@ -324,11 +324,9 @@ func resourceMethodUpdate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Method (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Received API Gateway Method: %s", method) - return resourceMethodRead(d, meta) } @@ -347,7 +345,7 @@ func resourceMethodDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("error deleting API Gateway Method (%s): %s", d.Id(), err) + return fmt.Errorf("deleting API Gateway Method (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/apigateway/method_response.go b/internal/service/apigateway/method_response.go index 4bb6c5c764f..5522bd7cae3 100644 --- a/internal/service/apigateway/method_response.go +++ b/internal/service/apigateway/method_response.go @@ -173,7 +173,7 @@ func resourceMethodResponseUpdate(d *schema.ResourceData, meta interface{}) erro operations = append(operations, ops...) } - out, err := conn.UpdateMethodResponse(&apigateway.UpdateMethodResponseInput{ + _, err := conn.UpdateMethodResponse(&apigateway.UpdateMethodResponseInput{ HttpMethod: aws.String(d.Get("http_method").(string)), ResourceId: aws.String(d.Get("resource_id").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), @@ -182,11 +182,9 @@ func resourceMethodResponseUpdate(d *schema.ResourceData, meta interface{}) erro }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Method Response (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Received API Gateway Method Response: %s", out) - return resourceMethodResponseRead(d, meta) } @@ -206,7 +204,7 @@ func resourceMethodResponseDelete(d *schema.ResourceData, meta interface{}) erro } if err != nil { - return fmt.Errorf("error deleting API Gateway Method Response (%s): %s", d.Id(), err) + return fmt.Errorf("deleting API Gateway Method Response (%s): %s", d.Id(), err) } return nil diff --git a/internal/service/apigateway/model.go b/internal/service/apigateway/model.go index 32f80059518..282c1b79bc1 100644 --- a/internal/service/apigateway/model.go +++ b/internal/service/apigateway/model.go @@ -164,15 +164,14 @@ func resourceModelUpdate(d *schema.ResourceData, meta interface{}) error { }) } - out, err := conn.UpdateModel(&apigateway.UpdateModelInput{ + _, err := conn.UpdateModel(&apigateway.UpdateModelInput{ ModelName: aws.String(d.Get("name").(string)), RestApiId: aws.String(d.Get("rest_api_id").(string)), PatchOperations: operations, }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Model (%s): %s", d.Id(), err) } - log.Printf("[DEBUG] Received API Gateway Model: %s", out) return resourceModelRead(d, meta) } @@ -193,7 +192,7 @@ func resourceModelDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("Error deleting API gateway model: %s", err) + return fmt.Errorf("deleting API Gateway Model (%s): %s", d.Id(), err) } return nil } diff --git a/internal/service/apigateway/request_validator.go b/internal/service/apigateway/request_validator.go index 23912faf93d..b14ab3ef6ab 100644 --- a/internal/service/apigateway/request_validator.go +++ b/internal/service/apigateway/request_validator.go @@ -142,7 +142,7 @@ func resourceRequestValidatorUpdate(d *schema.ResourceData, meta interface{}) er _, err := conn.UpdateRequestValidator(&input) if err != nil { - return err + return fmt.Errorf("updating API Gateway Request Validator (%s): %s", d.Id(), err) } log.Printf("[DEBUG] Updated Request Validator %s", d.Id()) @@ -162,7 +162,7 @@ func resourceRequestValidatorDelete(d *schema.ResourceData, meta interface{}) er // XXX: Figure out a way to delete the method that depends on the request validator first // otherwise the validator will be dangling until the API is deleted if !strings.Contains(err.Error(), apigateway.ErrCodeConflictException) { - return fmt.Errorf("Deleting Request Validator failed: %s", err) + return fmt.Errorf("deleting API Gateway Request Validator (%s): %s", d.Id(), err) } } diff --git a/internal/service/apigateway/resource.go b/internal/service/apigateway/resource.go index 3e555436603..67eccf70b34 100644 --- a/internal/service/apigateway/resource.go +++ b/internal/service/apigateway/resource.go @@ -133,7 +133,7 @@ func resourceResourceUpdate(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - return err + return fmt.Errorf("updating API Gateway Resource (%s): %s", d.Id(), err) } return resourceResourceRead(d, meta) @@ -154,7 +154,7 @@ func resourceResourceDelete(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return fmt.Errorf("Error deleting API Gateway Resource: %s", err) + return fmt.Errorf("deleting API Gateway Resource (%s): %s", d.Id(), err) } return nil } diff --git a/internal/service/apigateway/rest_api_data_source.go b/internal/service/apigateway/rest_api_data_source.go index eddf54b1c4c..d988c9303a2 100644 --- a/internal/service/apigateway/rest_api_data_source.go +++ b/internal/service/apigateway/rest_api_data_source.go @@ -157,5 +157,8 @@ func dataSourceRestAPIRead(d *schema.ResourceData, meta interface{}) error { return !lastPage }) - return err + if err != nil { + return fmt.Errorf("reading API Gateway REST API (%s): %w", target, err) + } + return nil } diff --git a/internal/service/apigateway/sdk_data_source.go b/internal/service/apigateway/sdk_data_source.go index a9d765eef76..eb682e2a01a 100644 --- a/internal/service/apigateway/sdk_data_source.go +++ b/internal/service/apigateway/sdk_data_source.go @@ -68,7 +68,7 @@ func dataSourceSdkRead(d *schema.ResourceData, meta interface{}) error { export, err := conn.GetSdk(input) if err != nil { - return err + return fmt.Errorf("reading API Gateway API: %w", err) } d.SetId(fmt.Sprintf("%s:%s:%s", restApiId, stageName, sdkType)) diff --git a/internal/service/apigateway/vpc_link.go b/internal/service/apigateway/vpc_link.go index 47058c99027..b3e09dbc34a 100644 --- a/internal/service/apigateway/vpc_link.go +++ b/internal/service/apigateway/vpc_link.go @@ -70,7 +70,7 @@ func resourceVPCLinkCreate(d *schema.ResourceData, meta interface{}) error { resp, err := conn.CreateVpcLink(input) if err != nil { - return err + return fmt.Errorf("creating API Gateway VPC Link (%s): %w", d.Get("name").(string), err) } d.SetId(aws.StringValue(resp.Id)) @@ -94,11 +94,11 @@ func resourceVPCLinkRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.GetVpcLink(input) if err != nil { if !d.IsNewResource() && tfawserr.ErrCodeEquals(err, apigateway.ErrCodeNotFoundException) { - log.Printf("[WARN] VPC Link %s not found, removing from state", d.Id()) + log.Printf("[WARN] API Gateway VPC Link %s not found, removing from state", d.Id()) d.SetId("") return nil } - return err + return fmt.Errorf("reading API Gateway VPC Link (%s): %w", d.Id(), err) } tags := KeyValueTags(resp.Tags).IgnoreAWS().IgnoreConfig(ignoreTagsConfig) @@ -122,7 +122,10 @@ func resourceVPCLinkRead(d *schema.ResourceData, meta interface{}) error { d.Set("name", resp.Name) d.Set("description", resp.Description) - d.Set("target_arns", flex.FlattenStringList(resp.TargetArns)) + if err := d.Set("target_arns", flex.FlattenStringList(resp.TargetArns)); err != nil { + return fmt.Errorf("reading API Gateway VPC Link (%s): %w", d.Id(), err) + } + return nil } From 2efba6a165dafb7fb8bcb940f1a1bdc12e2870b1 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 15:52:55 -0800 Subject: [PATCH 101/106] Fixes bare errors in `acmpca` --- internal/service/acmpca/permission.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/service/acmpca/permission.go b/internal/service/acmpca/permission.go index 18e4ab105fa..d3a92bd5134 100644 --- a/internal/service/acmpca/permission.go +++ b/internal/service/acmpca/permission.go @@ -95,7 +95,7 @@ func resourcePermissionRead(d *schema.ResourceData, meta interface{}) error { caARN, principal, sourceAccount, err := PermissionParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("reading ACM PCA Permission (%s): %w", d.Id(), err) } permission, err := FindPermission(conn, caARN, principal, sourceAccount) @@ -125,7 +125,7 @@ func resourcePermissionDelete(d *schema.ResourceData, meta interface{}) error { caARN, principal, sourceAccount, err := PermissionParseResourceID(d.Id()) if err != nil { - return err + return fmt.Errorf("deleting ACM PCA Permission: %s", err) } input := &acmpca.DeletePermissionInput{ From a19251459c6358cb7fa7cc3d54c0cea2aab10e2f Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Thu, 12 Jan 2023 16:09:00 -0800 Subject: [PATCH 102/106] Adds semgrep rule to default file --- .ci/.semgrep.yml | 17 ++++++++++++++++ internal/service/appsync/graphql_api.go | 2 +- internal/service/autoscaling/group.go | 8 ++++---- .../distribution_configuration_structure.go | 18 ++++++++--------- internal/service/cloudtrail/cloudtrail.go | 6 +++--- .../hosted_private_virtual_interface.go | 4 ++-- ...sted_private_virtual_interface_accepter.go | 6 +++--- .../hosted_public_virtual_interface.go | 4 ++-- ...osted_public_virtual_interface_accepter.go | 6 +++--- .../hosted_transit_virtual_interface.go | 4 ++-- ...sted_transit_virtual_interface_accepter.go | 6 +++--- internal/service/directconnect/lag.go | 6 +++--- .../private_virtual_interface.go | 8 ++++---- .../directconnect/public_virtual_interface.go | 6 +++--- .../transit_virtual_interface.go | 8 ++++---- internal/service/dms/replication_task.go | 12 +++++------ internal/service/ds/directory.go | 12 +++++------ internal/service/ec2/ec2_instance.go | 16 +++++++-------- .../service/ec2/ec2_spot_instance_request.go | 8 ++++---- .../service/ec2/vpc_default_network_acl.go | 4 ++-- .../service/ec2/vpc_default_route_table.go | 6 +++--- internal/service/ec2/vpc_default_subnet.go | 2 +- .../ec2/vpc_dhcp_options_association.go | 2 +- ...vpc_endpoint_security_group_association.go | 6 +++--- .../ec2/vpc_network_acl_association.go | 4 ++-- internal/service/ec2/vpc_network_interface.go | 8 ++++---- .../ec2/vpc_network_interface_attachment.go | 2 +- .../service/ec2/vpc_peering_connection.go | 8 ++++---- .../ec2/vpc_peering_connection_accepter.go | 4 ++-- .../ec2/vpc_peering_connection_options.go | 4 ++-- internal/service/ec2/vpc_route_table.go | 14 ++++++------- internal/service/ec2/vpc_subnet.go | 20 +++++++++---------- .../ec2/vpnsite_gateway_route_propagation.go | 8 ++++---- internal/service/elasticache/cluster.go | 2 +- .../service/elasticbeanstalk/environment.go | 6 +++--- internal/service/ssm/document.go | 2 +- 36 files changed, 138 insertions(+), 121 deletions(-) diff --git a/.ci/.semgrep.yml b/.ci/.semgrep.yml index 3dceb26904e..21cadb752b4 100644 --- a/.ci/.semgrep.yml +++ b/.ci/.semgrep.yml @@ -854,3 +854,20 @@ rules: patterns: - pattern-regex: '(Create|Read|Update|Delete)Context:' severity: ERROR + + - id: bare-error-returns + languages: [go] + message: API errors should be wrapped with the CRUD info + paths: + include: + - internal/service + patterns: + - pattern: return $ERR + - pattern-inside: | + func $FUNC($D *schema.ResourceData, ...) error { + ... + } + - metavariable-regex: + metavariable: $ERR + regex: "[Ee]rr(?!ors\\.)" + severity: ERROR diff --git a/internal/service/appsync/graphql_api.go b/internal/service/appsync/graphql_api.go index 11b6661e5a8..bea58e1c360 100644 --- a/internal/service/appsync/graphql_api.go +++ b/internal/service/appsync/graphql_api.go @@ -709,7 +709,7 @@ func resourceSchemaPut(d *schema.ResourceData, meta interface{}) error { Definition: ([]byte)(v.(string)), } if _, err := conn.StartSchemaCreation(input); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } activeSchemaConfig := &resource.StateChangeConf{ diff --git a/internal/service/autoscaling/group.go b/internal/service/autoscaling/group.go index 842902d9427..87de6914a53 100644 --- a/internal/service/autoscaling/group.go +++ b/internal/service/autoscaling/group.go @@ -1478,7 +1478,7 @@ func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { if shouldRefreshInstances { if err := startInstanceRefresh(conn, expandStartInstanceRefreshInput(d.Id(), tfMap)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -1491,7 +1491,7 @@ func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error { forceDeleteWarmPool := d.Get("force_delete").(bool) || d.Get("force_delete_warm_pool").(bool) if err := deleteWarmPool(conn, d.Id(), forceDeleteWarmPool, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } else { _, err := conn.PutWarmPool(expandPutWarmPoolInput(d.Id(), w[0].(map[string]interface{}))) @@ -1632,7 +1632,7 @@ func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { err = deleteWarmPool(conn, d.Id(), forceDeleteWarmPool, d.Timeout(schema.TimeoutDelete)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -1640,7 +1640,7 @@ func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error { err = drainGroup(conn, d.Id(), group.Instances, d.Timeout(schema.TimeoutDelete)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/cloudfront/distribution_configuration_structure.go b/internal/service/cloudfront/distribution_configuration_structure.go index bb1320714d9..2d3de631f37 100644 --- a/internal/service/cloudfront/distribution_configuration_structure.go +++ b/internal/service/cloudfront/distribution_configuration_structure.go @@ -94,11 +94,11 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud err = d.Set("default_cache_behavior", []interface{}{flattenDefaultCacheBehavior(distributionConfig.DefaultCacheBehavior)}) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } err = d.Set("viewer_certificate", flattenViewerCertificate(distributionConfig.ViewerCertificate)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if distributionConfig.CallerReference != nil { @@ -122,12 +122,12 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud if distributionConfig.CustomErrorResponses != nil { err = d.Set("custom_error_response", FlattenCustomErrorResponses(distributionConfig.CustomErrorResponses)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if distributionConfig.CacheBehaviors != nil { if err := d.Set("ordered_cache_behavior", flattenCacheBehaviors(distributionConfig.CacheBehaviors)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -137,31 +137,31 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud err = d.Set("logging_config", []interface{}{}) } if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if distributionConfig.Aliases != nil { err = d.Set("aliases", FlattenAliases(distributionConfig.Aliases)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if distributionConfig.Restrictions != nil { err = d.Set("restrictions", flattenRestrictions(distributionConfig.Restrictions)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if aws.Int64Value(distributionConfig.Origins.Quantity) > 0 { err = d.Set("origin", FlattenOrigins(distributionConfig.Origins)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if aws.Int64Value(distributionConfig.OriginGroups.Quantity) > 0 { err = d.Set("origin_group", FlattenOriginGroups(distributionConfig.OriginGroups)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/cloudtrail/cloudtrail.go b/internal/service/cloudtrail/cloudtrail.go index e4641a4bb7e..106fd0250a9 100644 --- a/internal/service/cloudtrail/cloudtrail.go +++ b/internal/service/cloudtrail/cloudtrail.go @@ -326,19 +326,19 @@ func resourceCloudTrailCreate(d *schema.ResourceData, meta interface{}) error { // Event Selectors if _, ok := d.GetOk("event_selector"); ok { if err := setEventSelectors(conn, d); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if _, ok := d.GetOk("advanced_event_selector"); ok { if err := setAdvancedEventSelectors(conn, d); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if _, ok := d.GetOk("insight_selector"); ok { if err := setInsightSelectors(conn, d); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/directconnect/hosted_private_virtual_interface.go b/internal/service/directconnect/hosted_private_virtual_interface.go index 6e3a39cf1ca..fef2a2a0c65 100644 --- a/internal/service/directconnect/hosted_private_virtual_interface.go +++ b/internal/service/directconnect/hosted_private_virtual_interface.go @@ -147,7 +147,7 @@ func resourceHostedPrivateVirtualInterfaceCreate(d *schema.ResourceData, meta in d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := hostedPrivateVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedPrivateVirtualInterfaceRead(d, meta) @@ -158,7 +158,7 @@ func resourceHostedPrivateVirtualInterfaceRead(d *schema.ResourceData, meta inte vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted private virtual interface (%s) not found, removing from state", d.Id()) diff --git a/internal/service/directconnect/hosted_private_virtual_interface_accepter.go b/internal/service/directconnect/hosted_private_virtual_interface_accepter.go index ad693ef0028..59260b56488 100644 --- a/internal/service/directconnect/hosted_private_virtual_interface_accepter.go +++ b/internal/service/directconnect/hosted_private_virtual_interface_accepter.go @@ -97,7 +97,7 @@ func resourceHostedPrivateVirtualInterfaceAccepterCreate(d *schema.ResourceData, d.Set("arn", arn) if err := hostedPrivateVirtualInterfaceAccepterWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedPrivateVirtualInterfaceAccepterUpdate(d, meta) @@ -110,7 +110,7 @@ func resourceHostedPrivateVirtualInterfaceAccepterRead(d *schema.ResourceData, m vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted private virtual interface (%s) not found, removing from state", d.Id()) @@ -152,7 +152,7 @@ func resourceHostedPrivateVirtualInterfaceAccepterRead(d *schema.ResourceData, m func resourceHostedPrivateVirtualInterfaceAccepterUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedPrivateVirtualInterfaceAccepterRead(d, meta) diff --git a/internal/service/directconnect/hosted_public_virtual_interface.go b/internal/service/directconnect/hosted_public_virtual_interface.go index 0c77253c370..f656af60ccf 100644 --- a/internal/service/directconnect/hosted_public_virtual_interface.go +++ b/internal/service/directconnect/hosted_public_virtual_interface.go @@ -144,7 +144,7 @@ func resourceHostedPublicVirtualInterfaceCreate(d *schema.ResourceData, meta int d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := hostedPublicVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedPublicVirtualInterfaceRead(d, meta) @@ -155,7 +155,7 @@ func resourceHostedPublicVirtualInterfaceRead(d *schema.ResourceData, meta inter vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect virtual interface (%s) not found, removing from state", d.Id()) diff --git a/internal/service/directconnect/hosted_public_virtual_interface_accepter.go b/internal/service/directconnect/hosted_public_virtual_interface_accepter.go index a3aea455f57..1dccd2c491f 100644 --- a/internal/service/directconnect/hosted_public_virtual_interface_accepter.go +++ b/internal/service/directconnect/hosted_public_virtual_interface_accepter.go @@ -72,7 +72,7 @@ func resourceHostedPublicVirtualInterfaceAccepterCreate(d *schema.ResourceData, d.Set("arn", arn) if err := hostedPublicVirtualInterfaceAccepterWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedPublicVirtualInterfaceAccepterUpdate(d, meta) @@ -85,7 +85,7 @@ func resourceHostedPublicVirtualInterfaceAccepterRead(d *schema.ResourceData, me vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted public virtual interface (%s) not found, removing from state", d.Id()) @@ -126,7 +126,7 @@ func resourceHostedPublicVirtualInterfaceAccepterRead(d *schema.ResourceData, me func resourceHostedPublicVirtualInterfaceAccepterUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedPublicVirtualInterfaceAccepterRead(d, meta) diff --git a/internal/service/directconnect/hosted_transit_virtual_interface.go b/internal/service/directconnect/hosted_transit_virtual_interface.go index 5c4cf6fa76e..67260da67d5 100644 --- a/internal/service/directconnect/hosted_transit_virtual_interface.go +++ b/internal/service/directconnect/hosted_transit_virtual_interface.go @@ -144,7 +144,7 @@ func resourceHostedTransitVirtualInterfaceCreate(d *schema.ResourceData, meta in d.SetId(aws.StringValue(resp.VirtualInterface.VirtualInterfaceId)) if err := hostedTransitVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedTransitVirtualInterfaceRead(d, meta) @@ -155,7 +155,7 @@ func resourceHostedTransitVirtualInterfaceRead(d *schema.ResourceData, meta inte vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect hosted transit virtual interface (%s) not found, removing from state", d.Id()) diff --git a/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go b/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go index 5711ee50416..52aa9b4afad 100644 --- a/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go +++ b/internal/service/directconnect/hosted_transit_virtual_interface_accepter.go @@ -78,7 +78,7 @@ func resourceHostedTransitVirtualInterfaceAccepterCreate(d *schema.ResourceData, d.Set("arn", arn) if err := hostedTransitVirtualInterfaceAccepterWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedTransitVirtualInterfaceAccepterUpdate(d, meta) @@ -91,7 +91,7 @@ func resourceHostedTransitVirtualInterfaceAccepterRead(d *schema.ResourceData, m vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect transit virtual interface (%s) not found, removing from state", d.Id()) @@ -131,7 +131,7 @@ func resourceHostedTransitVirtualInterfaceAccepterRead(d *schema.ResourceData, m func resourceHostedTransitVirtualInterfaceAccepterUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceHostedTransitVirtualInterfaceAccepterRead(d, meta) diff --git a/internal/service/directconnect/lag.go b/internal/service/directconnect/lag.go index 6b5b32a6a40..193fa06e1bb 100644 --- a/internal/service/directconnect/lag.go +++ b/internal/service/directconnect/lag.go @@ -124,7 +124,7 @@ func resourceLagCreate(d *schema.ResourceData, meta interface{}) error { err = deleteConnection(conn, aws.StringValue(output.Connections[0].ConnectionId), waitConnectionDeleted) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -227,12 +227,12 @@ func resourceLagDelete(d *schema.ResourceData, meta interface{}) error { err = deleteConnection(conn, aws.StringValue(connection.ConnectionId), waitConnectionDeleted) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } else if v, ok := d.GetOk("connection_id"); ok { if err := deleteConnectionLAGAssociation(conn, v.(string), d.Id()); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/directconnect/private_virtual_interface.go b/internal/service/directconnect/private_virtual_interface.go index d8694000a10..27c7e0851e5 100644 --- a/internal/service/directconnect/private_virtual_interface.go +++ b/internal/service/directconnect/private_virtual_interface.go @@ -178,7 +178,7 @@ func resourcePrivateVirtualInterfaceCreate(d *schema.ResourceData, meta interfac d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := privateVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourcePrivateVirtualInterfaceRead(d, meta) @@ -191,7 +191,7 @@ func resourcePrivateVirtualInterfaceRead(d *schema.ResourceData, meta interface{ vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect private virtual interface (%s) not found, removing from state", d.Id()) @@ -245,11 +245,11 @@ func resourcePrivateVirtualInterfaceRead(d *schema.ResourceData, meta interface{ func resourcePrivateVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if err := privateVirtualInterfaceWaitUntilAvailable(meta.(*conns.AWSClient).DirectConnectConn(), d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourcePrivateVirtualInterfaceRead(d, meta) diff --git a/internal/service/directconnect/public_virtual_interface.go b/internal/service/directconnect/public_virtual_interface.go index b805c3f5c8e..3acd3908549 100644 --- a/internal/service/directconnect/public_virtual_interface.go +++ b/internal/service/directconnect/public_virtual_interface.go @@ -150,7 +150,7 @@ func resourcePublicVirtualInterfaceCreate(d *schema.ResourceData, meta interface d.SetId(aws.StringValue(resp.VirtualInterfaceId)) if err := publicVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourcePublicVirtualInterfaceRead(d, meta) @@ -163,7 +163,7 @@ func resourcePublicVirtualInterfaceRead(d *schema.ResourceData, meta interface{} vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect virtual interface (%s) not found, removing from state", d.Id()) @@ -215,7 +215,7 @@ func resourcePublicVirtualInterfaceRead(d *schema.ResourceData, meta interface{} func resourcePublicVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourcePublicVirtualInterfaceRead(d, meta) diff --git a/internal/service/directconnect/transit_virtual_interface.go b/internal/service/directconnect/transit_virtual_interface.go index e88f4512051..5aeb12f64b5 100644 --- a/internal/service/directconnect/transit_virtual_interface.go +++ b/internal/service/directconnect/transit_virtual_interface.go @@ -159,7 +159,7 @@ func resourceTransitVirtualInterfaceCreate(d *schema.ResourceData, meta interfac d.SetId(aws.StringValue(resp.VirtualInterface.VirtualInterfaceId)) if err := transitVirtualInterfaceWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceTransitVirtualInterfaceRead(d, meta) @@ -172,7 +172,7 @@ func resourceTransitVirtualInterfaceRead(d *schema.ResourceData, meta interface{ vif, err := virtualInterfaceRead(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if vif == nil { log.Printf("[WARN] Direct Connect transit virtual interface (%s) not found, removing from state", d.Id()) @@ -225,11 +225,11 @@ func resourceTransitVirtualInterfaceRead(d *schema.ResourceData, meta interface{ func resourceTransitVirtualInterfaceUpdate(d *schema.ResourceData, meta interface{}) error { if err := virtualInterfaceUpdate(d, meta); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if err := transitVirtualInterfaceWaitUntilAvailable(meta.(*conns.AWSClient).DirectConnectConn(), d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceTransitVirtualInterfaceRead(d, meta) diff --git a/internal/service/dms/replication_task.go b/internal/service/dms/replication_task.go index 7c32d6028ae..d7ad6933aaa 100644 --- a/internal/service/dms/replication_task.go +++ b/internal/service/dms/replication_task.go @@ -156,7 +156,7 @@ func resourceReplicationTaskCreate(d *schema.ResourceData, meta interface{}) err if d.Get("start_replication_task").(bool) { if err := startReplicationTask(d.Id(), conn); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -251,7 +251,7 @@ func resourceReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) err if status == replicationTaskStatusRunning { log.Println("[DEBUG] stopping DMS replication task:", input) if err := stopReplicationTask(d.Id(), conn); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -268,7 +268,7 @@ func resourceReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) err if d.Get("start_replication_task").(bool) { err := startReplicationTask(d.Id(), conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -278,13 +278,13 @@ func resourceReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) err if d.Get("start_replication_task").(bool) { if status != replicationTaskStatusRunning { if err := startReplicationTask(d.Id(), conn); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } else { if status == replicationTaskStatusRunning { if err := stopReplicationTask(d.Id(), conn); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -307,7 +307,7 @@ func resourceReplicationTaskDelete(d *schema.ResourceData, meta interface{}) err if status := d.Get("status").(string); status == replicationTaskStatusRunning { if err := stopReplicationTask(d.Id(), conn); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/ds/directory.go b/internal/service/ds/directory.go index 6b1dc5e80dd..05c803a994b 100644 --- a/internal/service/ds/directory.go +++ b/internal/service/ds/directory.go @@ -304,19 +304,19 @@ func resourceDirectoryCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("alias"); ok { if err := createAlias(conn, d.Id(), v.(string)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if v, ok := d.GetOk("desired_number_of_domain_controllers"); ok { if err := updateNumberOfDomainControllers(conn, d.Id(), v.(int), d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if _, ok := d.GetOk("enable_sso"); ok { if err := enableSSO(conn, d.Id()); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -400,18 +400,18 @@ func resourceDirectoryUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChange("desired_number_of_domain_controllers") { if err := updateNumberOfDomainControllers(conn, d.Id(), d.Get("desired_number_of_domain_controllers").(int), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("enable_sso") { if _, ok := d.GetOk("enable_sso"); ok { if err := enableSSO(conn, d.Id()); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } else { if err := disableSSO(conn, d.Id()); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } diff --git a/internal/service/ec2/ec2_instance.go b/internal/service/ec2/ec2_instance.go index 9a0a712a8a1..d50d460044a 100644 --- a/internal/service/ec2/ec2_instance.go +++ b/internal/service/ec2/ec2_instance.go @@ -1834,7 +1834,7 @@ func resourceInstanceDelete(d *schema.ResourceData, meta interface{}) error { } if err := terminateInstance(conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return nil @@ -1948,20 +1948,20 @@ func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2. } if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } // This handles the import case which needs to be defaulted to empty if _, ok := d.GetOk("root_block_device"); !ok { if err := d.Set("root_block_device", []interface{}{}); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if ibds["root"] != nil { roots := []interface{}{ibds["root"]} if err := d.Set("root_block_device", roots); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -2431,11 +2431,11 @@ func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec } log.Printf("[DEBUG] Setting Security Group IDs: %#v", sgs) if err := d.Set("vpc_security_group_ids", sgs); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } else { if err := d.Set("vpc_security_group_ids", []string{}); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if useName { @@ -2445,11 +2445,11 @@ func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec } log.Printf("[DEBUG] Setting Security Group Names: %#v", sgs) if err := d.Set("security_groups", sgs); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } else { if err := d.Set("security_groups", []string{}); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } return nil diff --git a/internal/service/ec2/ec2_spot_instance_request.go b/internal/service/ec2/ec2_spot_instance_request.go index fe0560864ed..1399a469718 100644 --- a/internal/service/ec2/ec2_spot_instance_request.go +++ b/internal/service/ec2/ec2_spot_instance_request.go @@ -318,7 +318,7 @@ func readInstance(d *schema.ResourceData, meta interface{}) error { instance, err := FindInstanceByID(conn, d.Get("spot_instance_id").(string)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } d.Set("public_dns", instance.PublicDnsName) @@ -340,7 +340,7 @@ func readInstance(d *schema.ResourceData, meta interface{}) error { }) } if err := readBlockDevices(d, instance, conn); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } var ipv6Addresses []string @@ -373,7 +373,7 @@ func readInstance(d *schema.ResourceData, meta interface{}) error { if d.Get("get_password_data").(bool) { passwordData, err := getInstancePasswordData(*instance.InstanceId, conn) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } d.Set("password_data", passwordData) } else { @@ -412,7 +412,7 @@ func resourceSpotInstanceRequestDelete(d *schema.ResourceData, meta interface{}) if instanceId := d.Get("spot_instance_id").(string); instanceId != "" { if err := terminateInstance(conn, instanceId, d.Timeout(schema.TimeoutDelete)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/ec2/vpc_default_network_acl.go b/internal/service/ec2/vpc_default_network_acl.go index 5f8fc02ac90..33b1675ec54 100644 --- a/internal/service/ec2/vpc_default_network_acl.go +++ b/internal/service/ec2/vpc_default_network_acl.go @@ -109,11 +109,11 @@ func resourceDefaultNetworkACLCreate(d *schema.ResourceData, meta interface{}) e // Revoke all default and pre-existing rules on the default network ACL. if err := deleteNetworkACLEntries(conn, d.Id(), nacl.Entries); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if err := modifyNetworkACLAttributesOnCreate(conn, d); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } // Configure tags. diff --git a/internal/service/ec2/vpc_default_route_table.go b/internal/service/ec2/vpc_default_route_table.go index 656467e1f54..58846e69a7b 100644 --- a/internal/service/ec2/vpc_default_route_table.go +++ b/internal/service/ec2/vpc_default_route_table.go @@ -160,7 +160,7 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e // Remove all existing VGW associations. for _, v := range routeTable.PropagatingVgws { if err := routeTableDisableVGWRoutePropagation(conn, d.Id(), aws.StringValue(v.GatewayId)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -226,7 +226,7 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e v := v.(string) if err := routeTableEnableVGWRoutePropagation(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -237,7 +237,7 @@ func resourceDefaultRouteTableCreate(d *schema.ResourceData, meta interface{}) e v := v.(map[string]interface{}) if err := routeTableAddRoute(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } diff --git a/internal/service/ec2/vpc_default_subnet.go b/internal/service/ec2/vpc_default_subnet.go index ae0ab323a43..a1163a54fb8 100644 --- a/internal/service/ec2/vpc_default_subnet.go +++ b/internal/service/ec2/vpc_default_subnet.go @@ -222,7 +222,7 @@ func resourceDefaultSubnetCreate(d *schema.ResourceData, meta interface{}) error } if err := modifySubnetAttributesOnCreate(conn, d, subnet, computedIPv6CIDRBlock); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } // Configure tags. diff --git a/internal/service/ec2/vpc_dhcp_options_association.go b/internal/service/ec2/vpc_dhcp_options_association.go index 6eac3d89597..e5ea5ba6e68 100644 --- a/internal/service/ec2/vpc_dhcp_options_association.go +++ b/internal/service/ec2/vpc_dhcp_options_association.go @@ -96,7 +96,7 @@ func resourceVPCDHCPOptionsAssociationDelete(d *schema.ResourceData, meta interf dhcpOptionsID, vpcID, err := VPCDHCPOptionsAssociationParseResourceID(d.Id()) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if dhcpOptionsID == DefaultDHCPOptionsID { diff --git a/internal/service/ec2/vpc_endpoint_security_group_association.go b/internal/service/ec2/vpc_endpoint_security_group_association.go index 78fa0d72ab6..e208e4223fd 100644 --- a/internal/service/ec2/vpc_endpoint_security_group_association.go +++ b/internal/service/ec2/vpc_endpoint_security_group_association.go @@ -86,7 +86,7 @@ func resourceVPCEndpointSecurityGroupAssociationCreate(d *schema.ResourceData, m err := createVPCEndpointSecurityGroupAssociation(conn, vpcEndpointID, securityGroupID) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } d.SetId(VPCEndpointSecurityGroupAssociationCreateID(vpcEndpointID, securityGroupID)) @@ -94,7 +94,7 @@ func resourceVPCEndpointSecurityGroupAssociationCreate(d *schema.ResourceData, m if replaceDefaultAssociation { // Delete the existing VPC endpoint/default security group association. if err := deleteVPCEndpointSecurityGroupAssociation(conn, vpcEndpointID, defaultSecurityGroupID); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -150,7 +150,7 @@ func resourceVPCEndpointSecurityGroupAssociationDelete(d *schema.ResourceData, m err = createVPCEndpointSecurityGroupAssociation(conn, vpcEndpointID, aws.StringValue(defaultSecurityGroup.GroupId)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/ec2/vpc_network_acl_association.go b/internal/service/ec2/vpc_network_acl_association.go index 1e8d9b96d25..b7af091cd09 100644 --- a/internal/service/ec2/vpc_network_acl_association.go +++ b/internal/service/ec2/vpc_network_acl_association.go @@ -42,7 +42,7 @@ func resourceNetworkACLAssociationCreate(d *schema.ResourceData, meta interface{ associationID, err := networkACLAssociationCreate(conn, d.Get("network_acl_id").(string), d.Get("subnet_id").(string)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } d.SetId(associationID) @@ -94,7 +94,7 @@ func resourceNetworkACLAssociationDelete(d *schema.ResourceData, meta interface{ } if err := networkACLAssociationDelete(conn, d.Id(), aws.StringValue(defaultNACL.NetworkAclId)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return nil diff --git a/internal/service/ec2/vpc_network_interface.go b/internal/service/ec2/vpc_network_interface.go index 71a3a70a7ae..0270c9a4b36 100644 --- a/internal/service/ec2/vpc_network_interface.go +++ b/internal/service/ec2/vpc_network_interface.go @@ -471,7 +471,7 @@ func resourceNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) er _, err := attachNetworkInterface(conn, d.Id(), attachment["instance"].(string), attachment["device_index"].(int), networkInterfaceAttachedTimeout) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -577,7 +577,7 @@ func resourceNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) er err := DetachNetworkInterface(conn, d.Id(), attachment["attachment_id"].(string), NetworkInterfaceDetachedTimeout) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -587,7 +587,7 @@ func resourceNetworkInterfaceUpdate(d *schema.ResourceData, meta interface{}) er _, err := attachNetworkInterface(conn, d.Id(), attachment["instance"].(string), attachment["device_index"].(int), networkInterfaceAttachedTimeout) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -1055,7 +1055,7 @@ func resourceNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) er err := DetachNetworkInterface(conn, d.Id(), attachment["attachment_id"].(string), NetworkInterfaceDetachedTimeout) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/ec2/vpc_network_interface_attachment.go b/internal/service/ec2/vpc_network_interface_attachment.go index 40ef02e17a0..d922ee36a32 100644 --- a/internal/service/ec2/vpc_network_interface_attachment.go +++ b/internal/service/ec2/vpc_network_interface_attachment.go @@ -59,7 +59,7 @@ func resourceNetworkInterfaceAttachmentCreate(d *schema.ResourceData, meta inter ) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if attachmentID != "" { diff --git a/internal/service/ec2/vpc_peering_connection.go b/internal/service/ec2/vpc_peering_connection.go index 53d5909af70..7485ced144f 100644 --- a/internal/service/ec2/vpc_peering_connection.go +++ b/internal/service/ec2/vpc_peering_connection.go @@ -150,12 +150,12 @@ func resourceVPCPeeringConnectionCreate(d *schema.ResourceData, meta interface{} vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceVPCPeeringConnectionRead(d, meta) @@ -236,13 +236,13 @@ func resourceVPCPeeringConnectionUpdate(d *schema.ResourceData, meta interface{} vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChanges("accepter", "requester") { if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/ec2/vpc_peering_connection_accepter.go b/internal/service/ec2/vpc_peering_connection_accepter.go index e61778376f4..706953bc4bb 100644 --- a/internal/service/ec2/vpc_peering_connection_accepter.go +++ b/internal/service/ec2/vpc_peering_connection_accepter.go @@ -103,12 +103,12 @@ func resourceVPCPeeringAccepterCreate(d *schema.ResourceData, meta interface{}) vpcPeeringConnection, err = acceptVPCPeeringConnection(conn, d.Id(), d.Timeout(schema.TimeoutCreate)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, true); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if len(tags) > 0 { diff --git a/internal/service/ec2/vpc_peering_connection_options.go b/internal/service/ec2/vpc_peering_connection_options.go index 5b1273f9f65..b21ae0641d5 100644 --- a/internal/service/ec2/vpc_peering_connection_options.go +++ b/internal/service/ec2/vpc_peering_connection_options.go @@ -49,7 +49,7 @@ func resourceVPCPeeringConnectionOptionsCreate(d *schema.ResourceData, meta inte d.SetId(vpcPeeringConnectionID) if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, false); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceVPCPeeringConnectionOptionsRead(d, meta) @@ -101,7 +101,7 @@ func resourceVPCPeeringConnectionOptionsUpdate(d *schema.ResourceData, meta inte } if err := modifyVPCPeeringConnectionOptions(conn, d, vpcPeeringConnection, false); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceVPCPeeringConnectionOptionsRead(d, meta) diff --git a/internal/service/ec2/vpc_route_table.go b/internal/service/ec2/vpc_route_table.go index 16f63ba1fe7..39e4b7dbd77 100644 --- a/internal/service/ec2/vpc_route_table.go +++ b/internal/service/ec2/vpc_route_table.go @@ -194,7 +194,7 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { v := v.(string) if err := routeTableEnableVGWRoutePropagation(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -204,7 +204,7 @@ func resourceRouteTableCreate(d *schema.ResourceData, meta interface{}) error { v := v.(map[string]interface{}) if err := routeTableAddRoute(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -283,7 +283,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { v := v.(string) if err := routeTableDisableVGWRoutePropagation(conn, d.Id(), v); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } @@ -291,7 +291,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { v := v.(string) if err := routeTableEnableVGWRoutePropagation(conn, d.Id(), v, d.Timeout(schema.TimeoutCreate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -318,7 +318,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { if oldTarget != newTarget { if err := routeTableUpdateRoute(conn, d.Id(), vNew, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -326,7 +326,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { if addRoute { if err := routeTableAddRoute(conn, d.Id(), vNew, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } @@ -350,7 +350,7 @@ func resourceRouteTableUpdate(d *schema.ResourceData, meta interface{}) error { if delRoute { if err := routeTableDeleteRoute(conn, d.Id(), vOld, d.Timeout(schema.TimeoutUpdate)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } } diff --git a/internal/service/ec2/vpc_subnet.go b/internal/service/ec2/vpc_subnet.go index 102ee5407ef..4a652b18672 100644 --- a/internal/service/ec2/vpc_subnet.go +++ b/internal/service/ec2/vpc_subnet.go @@ -206,7 +206,7 @@ func resourceSubnetCreate(d *schema.ResourceData, meta interface{}) error { } if err := modifySubnetAttributesOnCreate(conn, d, subnet, false); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return resourceSubnetRead(d, meta) @@ -300,57 +300,57 @@ func resourceSubnetUpdate(d *schema.ResourceData, meta interface{}) error { if d.HasChanges("customer_owned_ipv4_pool", "map_customer_owned_ip_on_launch") { if err := modifySubnetOutpostRackAttributes(conn, d.Id(), d.Get("customer_owned_ipv4_pool").(string), d.Get("map_customer_owned_ip_on_launch").(bool)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("enable_dns64") { if err := modifySubnetEnableDNS64(conn, d.Id(), d.Get("enable_dns64").(bool)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("enable_resource_name_dns_aaaa_record_on_launch") { if err := modifySubnetEnableResourceNameDNSAAAARecordOnLaunch(conn, d.Id(), d.Get("enable_resource_name_dns_aaaa_record_on_launch").(bool)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("enable_resource_name_dns_a_record_on_launch") { if err := modifySubnetEnableResourceNameDNSARecordOnLaunch(conn, d.Id(), d.Get("enable_resource_name_dns_a_record_on_launch").(bool)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("map_public_ip_on_launch") { if err := modifySubnetMapPublicIPOnLaunch(conn, d.Id(), d.Get("map_public_ip_on_launch").(bool)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("private_dns_hostname_type_on_launch") { if err := modifySubnetPrivateDNSHostnameTypeOnLaunch(conn, d.Id(), d.Get("private_dns_hostname_type_on_launch").(string)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } // If we're disabling IPv6 assignment for new ENIs, do that before modifying the IPv6 CIDR block. if d.HasChange("assign_ipv6_address_on_creation") && !d.Get("assign_ipv6_address_on_creation").(bool) { if err := modifySubnetAssignIPv6AddressOnCreation(conn, d.Id(), false); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } if d.HasChange("ipv6_cidr_block") { if err := modifySubnetIPv6CIDRBlockAssociation(conn, d.Id(), d.Get("ipv6_cidr_block_association_id").(string), d.Get("ipv6_cidr_block").(string)); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } // If we're enabling IPv6 assignment for new ENIs, do that after modifying the IPv6 CIDR block. if d.HasChange("assign_ipv6_address_on_creation") && d.Get("assign_ipv6_address_on_creation").(bool) { if err := modifySubnetAssignIPv6AddressOnCreation(conn, d.Id(), true); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } diff --git a/internal/service/ec2/vpnsite_gateway_route_propagation.go b/internal/service/ec2/vpnsite_gateway_route_propagation.go index 221f92129bf..efd7291f6a0 100644 --- a/internal/service/ec2/vpnsite_gateway_route_propagation.go +++ b/internal/service/ec2/vpnsite_gateway_route_propagation.go @@ -45,7 +45,7 @@ func resourceVPNGatewayRoutePropagationEnable(d *schema.ResourceData, meta inter err := routeTableEnableVGWRoutePropagation(conn, routeTableID, gatewayID, d.Timeout(schema.TimeoutCreate)) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } d.SetId(VPNGatewayRoutePropagationCreateID(routeTableID, gatewayID)) @@ -59,7 +59,7 @@ func resourceVPNGatewayRoutePropagationDisable(d *schema.ResourceData, meta inte routeTableID, gatewayID, err := VPNGatewayRoutePropagationParseID(d.Id()) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } err = routeTableDisableVGWRoutePropagation(conn, routeTableID, gatewayID) @@ -68,7 +68,7 @@ func resourceVPNGatewayRoutePropagationDisable(d *schema.ResourceData, meta inte return nil } - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } func resourceVPNGatewayRoutePropagationRead(d *schema.ResourceData, meta interface{}) error { @@ -77,7 +77,7 @@ func resourceVPNGatewayRoutePropagationRead(d *schema.ResourceData, meta interfa routeTableID, gatewayID, err := VPNGatewayRoutePropagationParseID(d.Id()) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } err = FindVPNGatewayRoutePropagationExists(conn, routeTableID, gatewayID) diff --git a/internal/service/elasticache/cluster.go b/internal/service/elasticache/cluster.go index e300f7ef38d..04083dbd474 100644 --- a/internal/service/elasticache/cluster.go +++ b/internal/service/elasticache/cluster.go @@ -586,7 +586,7 @@ func setFromCacheCluster(d *schema.ResourceData, c *elasticache.CacheCluster) er d.Set("engine", c.Engine) if aws.StringValue(c.Engine) == engineRedis { if err := setEngineVersionRedis(d, c.EngineVersion); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } else { setEngineVersionMemcached(d, c.EngineVersion) diff --git a/internal/service/elasticbeanstalk/environment.go b/internal/service/elasticbeanstalk/environment.go index 4ed43349634..d19ec638d51 100644 --- a/internal/service/elasticbeanstalk/environment.go +++ b/internal/service/elasticbeanstalk/environment.go @@ -683,7 +683,7 @@ func resourceEnvironmentSettingsRead(d *schema.ResourceData, meta interface{}) e allSettings, err := fetchEnvironmentSettings(d, meta) if err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } settings := d.Get("setting").(*schema.Set) @@ -701,11 +701,11 @@ func resourceEnvironmentSettingsRead(d *schema.ResourceData, meta interface{}) e updatedSettings := schema.NewSet(optionSettingValueHash, updatedSettingsKeySet.List()) if err := d.Set("all_settings", allSettings.List()); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } if err := d.Set("setting", updatedSettings.List()); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } return nil diff --git a/internal/service/ssm/document.go b/internal/service/ssm/document.go index ca4837f7ae6..85a7c804669 100644 --- a/internal/service/ssm/document.go +++ b/internal/service/ssm/document.go @@ -526,7 +526,7 @@ func setDocumentPermissions(d *schema.ResourceData, meta interface{}) error { } if err := modifyDocumentPermissions(conn, d.Get("name").(string), accountIdsToAdd, accountIdsToRemove); err != nil { - return err // nosemgrep:bare-error-returns + return err // nosemgrep:ci.bare-error-returns } } From 7a10b5755812107cc1a516280e2ec454068cf646 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Fri, 13 Jan 2023 10:53:26 -0800 Subject: [PATCH 103/106] Removes extra leading `error ` from error messages in documentation --- docs/data-handling-and-conversion.md | 6 +++--- docs/raising-a-pull-request.md | 2 +- internal/generate/tags/README.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/data-handling-and-conversion.md b/docs/data-handling-and-conversion.md index a610e16164a..b433b1cf1b8 100644 --- a/docs/data-handling-and-conversion.md +++ b/docs/data-handling-and-conversion.md @@ -282,7 +282,7 @@ To write: ```go if err := d.Set("attribute_name", flattenStructures(output.Thing.AttributeName)); err != nil { - return fmt.Errorf("error setting attribute_name: %w", err) + return fmt.Errorf("setting attribute_name: %w", err) } ``` @@ -303,7 +303,7 @@ To write (_likely to have helper function introduced soon_): ```go if output.Thing.AttributeName != nil { if err := d.Set("attribute_name", []interface{}{flattenStructure(output.Thing.AttributeName)}); err != nil { - return fmt.Errorf("error setting attribute_name: %w", err) + return fmt.Errorf("setting attribute_name: %w", err) } } else { d.Set("attribute_name", nil) @@ -362,7 +362,7 @@ To write: ```go if err := d.Set("attribute_name", flattenStructures(output.Thing.AttributeNames)); err != nil { - return fmt.Errorf("error setting attribute_name: %w", err) + return fmt.Errorf("setting attribute_name: %w", err) } ``` diff --git a/docs/raising-a-pull-request.md b/docs/raising-a-pull-request.md index 05db5eed454..6195c6e9cf1 100644 --- a/docs/raising-a-pull-request.md +++ b/docs/raising-a-pull-request.md @@ -137,7 +137,7 @@ This Contribution Guide also includes separate sections on topics such as [Error } if err != nil { - return fmt.Errorf("error creating KMS External Key: %s", err) + return fmt.Errorf("creating KMS External Key: %s", err) } ``` diff --git a/internal/generate/tags/README.md b/internal/generate/tags/README.md index 08348282d3f..bc43188e210 100644 --- a/internal/generate/tags/README.md +++ b/internal/generate/tags/README.md @@ -350,7 +350,7 @@ func AthenaUpdateTags(conn *athena.Athena, identifier string, oldTagsMap interfa _, err := conn.UntagResource(input) if err != nil { - return fmt.Errorf("error untagging resource (%s): %s", identifier, err) + return fmt.Errorf("untagging resource (%s): %s", identifier, err) } } @@ -363,7 +363,7 @@ func AthenaUpdateTags(conn *athena.Athena, identifier string, oldTagsMap interfa _, err := conn.TagResource(input) if err != nil { - return fmt.Errorf("error tagging resource (%s): %s", identifier, err) + return fmt.Errorf("tagging resource (%s): %s", identifier, err) } } From 3c6272c5fe05ca6c7acddb0f6350b0d4c7d29ccc Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Fri, 13 Jan 2023 11:01:40 -0800 Subject: [PATCH 104/106] Missing documentation --- internal/generate/tags/README_updatetags.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/generate/tags/README_updatetags.md b/internal/generate/tags/README_updatetags.md index 90d23491e23..b33dec3e40d 100644 --- a/internal/generate/tags/README_updatetags.md +++ b/internal/generate/tags/README_updatetags.md @@ -27,7 +27,7 @@ func AthenaUpdateTags(conn *athena.Athena, identifier string, oldTagsMap interfa _, err := conn.UntagResource(input) if err != nil { - return fmt.Errorf("error untagging resource (%s): %s", identifier, err) + return fmt.Errorf("untagging resource (%s): %s", identifier, err) } } @@ -40,7 +40,7 @@ func AthenaUpdateTags(conn *athena.Athena, identifier string, oldTagsMap interfa _, err := conn.TagResource(input) if err != nil { - return fmt.Errorf("error tagging resource (%s): %s", identifier, err) + return fmt.Errorf("tagging resource (%s): %s", identifier, err) } } From a614ace7c1de5b932ad7b56ba38210672921f22e Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Fri, 13 Jan 2023 14:46:56 -0800 Subject: [PATCH 105/106] `yamllint` --- .ci/.semgrep.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.ci/.semgrep.yml b/.ci/.semgrep.yml index 21cadb752b4..f93f09bc72d 100644 --- a/.ci/.semgrep.yml +++ b/.ci/.semgrep.yml @@ -858,10 +858,10 @@ rules: - id: bare-error-returns languages: [go] message: API errors should be wrapped with the CRUD info - paths: + paths: include: - internal/service - patterns: + patterns: - pattern: return $ERR - pattern-inside: | func $FUNC($D *schema.ResourceData, ...) error { From cd0112262c4dd18beb5ee6f1fe1c5a14d9ccc163 Mon Sep 17 00:00:00 2001 From: Graham Davison Date: Fri, 13 Jan 2023 14:58:04 -0800 Subject: [PATCH 106/106] Test fixes --- internal/service/elb/flex_test.go | 2 +- internal/service/kms/arn_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/service/elb/flex_test.go b/internal/service/elb/flex_test.go index 4aa793b4c15..95266c1621d 100644 --- a/internal/service/elb/flex_test.go +++ b/internal/service/elb/flex_test.go @@ -64,7 +64,7 @@ func TestExpandListeners_invalid(t *testing.T) { _, err := ExpandListeners(expanded) if err != nil { // Check the error we got - if !strings.Contains(err.Error(), "ssl_certificate_id may be set only when protocol") { + if !strings.Contains(err.Error(), `"ssl_certificate_id" may be set only when "protocol"`) { t.Fatalf("Got error in TestExpandListeners_invalid, but not what we expected: %s", err) } } diff --git a/internal/service/kms/arn_test.go b/internal/service/kms/arn_test.go index 70b7f848202..cc5d7c6705e 100644 --- a/internal/service/kms/arn_test.go +++ b/internal/service/kms/arn_test.go @@ -19,12 +19,12 @@ func TestAliasARNToKeyARN(t *testing.T) { { TestName: "empty ARN", InputARN: "", - ExpectedError: regexp.MustCompile(`error parsing ARN`), + ExpectedError: regexp.MustCompile(`parsing ARN`), }, { TestName: "unparsable ARN", InputARN: "test", - ExpectedError: regexp.MustCompile(`error parsing ARN`), + ExpectedError: regexp.MustCompile(`parsing ARN`), }, { TestName: "invalid ARN service",