Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

r/codebuild_source_credential - finder, sweeper and disappears test #22344

Merged
merged 3 commits into from
Jan 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions internal/service/codebuild/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package codebuild
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/codebuild"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

Expand Down Expand Up @@ -52,3 +53,36 @@ func FindProjectByARN(conn *codebuild.CodeBuild, arn string) (*codebuild.Project

return output.Projects[0], nil
}

func FindSourceCredentialByARN(conn *codebuild.CodeBuild, arn string) (*codebuild.SourceCredentialsInfo, error) {
var result *codebuild.SourceCredentialsInfo
input := &codebuild.ListSourceCredentialsInput{}
output, err := conn.ListSourceCredentials(input)
if err != nil {
return nil, err
}

if output == nil {
return nil, tfresource.NewEmptyResultError(input)
}

for _, sourceCred := range output.SourceCredentialsInfos {
if sourceCred == nil {
continue
}

if aws.StringValue(sourceCred.Arn) == arn {
result = sourceCred
break
}
}

if result == nil {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: input,
}
}

return result, nil
}
55 changes: 20 additions & 35 deletions internal/service/codebuild/source_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ 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/tfresource"
)

func ResourceSourceCredential() *schema.Resource {
Expand All @@ -28,23 +29,16 @@ func ResourceSourceCredential() *schema.Resource {
Computed: true,
},
"auth_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
codebuild.AuthTypeBasicAuth,
codebuild.AuthTypePersonalAccessToken,
}, false),
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(codebuild.AuthType_Values(), false),
},
"server_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
codebuild.ServerTypeGithub,
codebuild.ServerTypeBitbucket,
codebuild.ServerTypeGithubEnterprise,
}, false),
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(codebuild.ServerType_Values(), false),
},
"token": {
Type: schema.TypeString,
Expand Down Expand Up @@ -78,7 +72,7 @@ func resourceSourceCredentialCreate(d *schema.ResourceData, meta interface{}) er

resp, err := conn.ImportSourceCredentials(createOpts)
if err != nil {
return fmt.Errorf("Error importing source credentials: %s", err)
return fmt.Errorf("Error importing source credentials: %w", err)
}

d.SetId(aws.StringValue(resp.Arn))
Expand All @@ -89,29 +83,20 @@ func resourceSourceCredentialCreate(d *schema.ResourceData, meta interface{}) er
func resourceSourceCredentialRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).CodeBuildConn

resp, err := conn.ListSourceCredentials(&codebuild.ListSourceCredentialsInput{})
if err != nil {
return fmt.Errorf("Error List CodeBuild Source Credential: %s", err)
}

var info *codebuild.SourceCredentialsInfo

for _, sourceCredentialsInfo := range resp.SourceCredentialsInfos {
if d.Id() == aws.StringValue(sourceCredentialsInfo.Arn) {
info = sourceCredentialsInfo
break
}
}

if info == nil {
resp, err := FindSourceCredentialByARN(conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] CodeBuild Source Credential (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

d.Set("arn", info.Arn)
d.Set("auth_type", info.AuthType)
d.Set("server_type", info.ServerType)
if err != nil {
return fmt.Errorf("error reading CodeBuild Source Credential (%s): %w", d.Id(), err)
}

d.Set("arn", resp.Arn)
d.Set("auth_type", resp.AuthType)
d.Set("server_type", resp.ServerType)

return nil
}
Expand All @@ -127,7 +112,7 @@ func resourceSourceCredentialDelete(d *schema.ResourceData, meta interface{}) er
if tfawserr.ErrMessageContains(err, codebuild.ErrCodeResourceNotFoundException, "") {
return nil
}
return fmt.Errorf("Error deleting Source Credentials(%s): %s", d.Id(), err)
return fmt.Errorf("Error deleting CodeBuild Source Credentials(%s): %w", d.Id(), err)
}

return nil
Expand Down
59 changes: 38 additions & 21 deletions internal/service/codebuild/source_credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import (
"regexp"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/codebuild"
sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tfcodebuild "github.com/hashicorp/terraform-provider-aws/internal/service/codebuild"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func TestAccCodeBuildSourceCredential_basic(t *testing.T) {
Expand Down Expand Up @@ -91,6 +92,30 @@ func TestAccCodeBuildSourceCredential_basicAuth(t *testing.T) {
})
}

func TestAccCodeBuildSourceCredential_disappears(t *testing.T) {
var sourceCredentialsInfo codebuild.SourceCredentialsInfo
token := sdkacctest.RandomWithPrefix("token")
resourceName := "aws_codebuild_source_credential.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t); testAccPreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, codebuild.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckSourceCredentialDestroy,
Steps: []resource.TestStep{
{
Config: testAccSourceCredential_Basic("PERSONAL_ACCESS_TOKEN", "GITHUB_ENTERPRISE", token),
Check: resource.ComposeTestCheckFunc(
testAccCheckSourceCredentialExists(resourceName, &sourceCredentialsInfo),
acctest.CheckResourceDisappears(acctest.Provider, tfcodebuild.ResourceSourceCredential(), resourceName),
acctest.CheckResourceDisappears(acctest.Provider, tfcodebuild.ResourceSourceCredential(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckSourceCredentialDestroy(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).CodeBuildConn

Expand All @@ -99,20 +124,17 @@ func testAccCheckSourceCredentialDestroy(s *terraform.State) error {
continue
}

resp, err := conn.ListSourceCredentials(&codebuild.ListSourceCredentialsInput{})
if err != nil {
return err
}
_, err := tfcodebuild.FindSourceCredentialByARN(conn, rs.Primary.ID)

if len(resp.SourceCredentialsInfos) == 0 {
return nil
if tfresource.NotFound(err) {
continue
}

for _, sourceCredentialsInfo := range resp.SourceCredentialsInfos {
if rs.Primary.ID == aws.StringValue(sourceCredentialsInfo.Arn) {
return fmt.Errorf("Found Source Credential %s", rs.Primary.ID)
}
if err != nil {
return err
}

return fmt.Errorf("CodeBuild Source Credential %s still exists", rs.Primary.ID)
}
return nil
}
Expand All @@ -126,23 +148,18 @@ func testAccCheckSourceCredentialExists(name string, sourceCredential *codebuild

conn := acctest.Provider.Meta().(*conns.AWSClient).CodeBuildConn

resp, err := conn.ListSourceCredentials(&codebuild.ListSourceCredentialsInput{})
output, err := tfcodebuild.FindSourceCredentialByARN(conn, rs.Primary.ID)
if err != nil {
return err
}

if len(resp.SourceCredentialsInfos) == 0 {
return fmt.Errorf("Source Credential %s not found", rs.Primary.ID)
if output == nil {
return fmt.Errorf("CodeBuild Source Credential (%s) not found", rs.Primary.ID)
}

for _, sourceCredentialsInfo := range resp.SourceCredentialsInfos {
if rs.Primary.ID == aws.StringValue(sourceCredentialsInfo.Arn) {
*sourceCredential = *sourceCredentialsInfo
return nil
}
}
*sourceCredential = *output

return fmt.Errorf("Source Credential %s not found", rs.Primary.ID)
return nil
}
}

Expand Down
45 changes: 45 additions & 0 deletions internal/service/codebuild/sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ func init() {
Name: "aws_codebuild_project",
F: sweepProjects,
})

resource.AddTestSweepers("aws_codebuild_source_credential", &resource.Sweeper{
Name: "aws_codebuild_source_credential",
F: sweepSourceCredentials,
})
}

func sweepReportGroups(region string) error {
Expand Down Expand Up @@ -119,3 +124,43 @@ func sweepProjects(region string) error {

return sweeperErrs.ErrorOrNil()
}

func sweepSourceCredentials(region string) error {
client, err := sweep.SharedRegionalSweepClient(region)

if err != nil {
return fmt.Errorf("error getting client: %w", err)
}

conn := client.(*conns.AWSClient).CodeBuildConn
input := &codebuild.ListSourceCredentialsInput{}
var sweeperErrs *multierror.Error

creds, err := conn.ListSourceCredentials(input)

for _, cred := range creds.SourceCredentialsInfos {
id := aws.StringValue(cred.Arn)
r := ResourceSourceCredential()
d := r.Data(nil)
d.SetId(id)

err := r.Delete(d, client)
if err != nil {
sweeperErr := fmt.Errorf("error deleting CodeBuild Source Credential (%s): %w", id, err)
log.Printf("[ERROR] %s", sweeperErr)
sweeperErrs = multierror.Append(sweeperErrs, sweeperErr)
continue
}
}

if sweep.SkipSweepError(err) {
log.Printf("[WARN] Skipping CodeBuild Source Credential sweep for %s: %s", region, err)
return sweeperErrs.ErrorOrNil()
}

if err != nil {
sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving CodeBuild Source Credentials: %w", err))
}

return sweeperErrs.ErrorOrNil()
}