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/codedeploy_app - add arn attribute & tagging support & sweeper #18564

Merged
merged 10 commits into from
Apr 14, 2021
Merged
Show file tree
Hide file tree
Changes from 6 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
11 changes: 11 additions & 0 deletions .changelog/18564.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
```release-note:enhancement
resource/aws_codedeploy_app: Add `arn`, `linked_to_github`, `github_account_name`, `application_id` attributes
```

```release-note:enhancement
resource/aws_codedeploy_app: Add `tags` argument
```

```release-note:enhancement
resource/aws_codedeploy_app: Add plan time validation for `name`
```
109 changes: 70 additions & 39 deletions aws/resource_aws_codedeploy_app.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import (
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/codedeploy"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
)

func resourceAwsCodeDeployApp() *schema.Resource {
Expand Down Expand Up @@ -52,30 +53,37 @@ func resourceAwsCodeDeployApp() *schema.Resource {
},

Schema: map[string]*schema.Schema{
"name": {
"arn": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Computed: true,
},

"compute_platform": {
"application_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
codedeploy.ComputePlatformEcs,
codedeploy.ComputePlatformLambda,
codedeploy.ComputePlatformServer,
}, false),
Default: codedeploy.ComputePlatformServer,
Computed: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(1, 100),
},

// The unique ID is set by AWS on create.
"unique_id": {
"compute_platform": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(codedeploy.ComputePlatform_Values(), false),
Default: codedeploy.ComputePlatformServer,
},
"github_account_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"linked_to_github": {
Type: schema.TypeBool,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
Expand All @@ -90,6 +98,7 @@ func resourceAwsCodeDeployAppCreate(d *schema.ResourceData, meta interface{}) er
resp, err := conn.CreateApplication(&codedeploy.CreateApplicationInput{
ApplicationName: aws.String(application),
ComputePlatform: aws.String(computePlatform),
Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().CodedeployTags(),
})
if err != nil {
return err
Expand All @@ -101,52 +110,74 @@ func resourceAwsCodeDeployAppCreate(d *schema.ResourceData, meta interface{}) er
// the state file. This allows us to reliably detect both when the TF
// config file changes and when the user deletes the app without removing
// it first from the TF config.
d.SetId(fmt.Sprintf("%s:%s", *resp.ApplicationId, application))
d.SetId(fmt.Sprintf("%s:%s", aws.StringValue(resp.ApplicationId), application))

return resourceAwsCodeDeployAppRead(d, meta)
}

func resourceAwsCodeDeployAppRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).codedeployconn
ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig

application := resourceAwsCodeDeployAppParseId(d.Id())
DrFaust92 marked this conversation as resolved.
Show resolved Hide resolved
log.Printf("[DEBUG] Reading CodeDeploy application %s", application)
resp, err := conn.GetApplication(&codedeploy.GetApplicationInput{
ApplicationName: aws.String(application),
})
if err != nil {
if codedeployerr, ok := err.(awserr.Error); ok && codedeployerr.Code() == "ApplicationDoesNotExistException" {
if isAWSErr(err, codedeploy.ErrCodeApplicationDoesNotExistException, "") {
d.SetId("")
log.Printf("[WARN] CodeDeploy Application (%s) not found, removing from state", d.Id())
return nil
} else {
log.Printf("[ERROR] Error finding CodeDeploy application: %s", err)
return err
}

log.Printf("[ERROR] Error finding CodeDeploy application: %s", err)
return err
}

app := resp.Application
appName := aws.StringValue(app.ApplicationName)

DrFaust92 marked this conversation as resolved.
Show resolved Hide resolved
appArn := arn.ARN{
DrFaust92 marked this conversation as resolved.
Show resolved Hide resolved
Partition: meta.(*AWSClient).partition,
Service: "codedeploy",
Region: meta.(*AWSClient).region,
AccountID: meta.(*AWSClient).accountid,
Resource: fmt.Sprintf("application:%s", appName),
}.String()

d.Set("arn", appArn)
d.Set("application_id", app.ApplicationId)
d.Set("compute_platform", app.ComputePlatform)
d.Set("name", appName)
d.Set("github_account_name", app.GitHubAccountName)
d.Set("linked_to_github", app.LinkedToGitHub)

tags, err := keyvaluetags.CodedeployListTags(conn, appArn)

if err != nil {
return fmt.Errorf("error listing tags for CodeDeploy application (%s): %w", d.Id(), err)
}

d.Set("compute_platform", resp.Application.ComputePlatform)
d.Set("name", resp.Application.ApplicationName)
if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil {
return fmt.Errorf("error setting tags: %w", err)
}

return nil
}

func resourceAwsCodeDeployUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).codedeployconn

o, n := d.GetChange("name")
if d.HasChange("tags") {
o, n := d.GetChange("tags")

_, err := conn.UpdateApplication(&codedeploy.UpdateApplicationInput{
DrFaust92 marked this conversation as resolved.
Show resolved Hide resolved
ApplicationName: aws.String(o.(string)),
NewApplicationName: aws.String(n.(string)),
})
if err != nil {
return err
if err := keyvaluetags.CodedeployUpdateTags(conn, d.Get("arn").(string), o, n); err != nil {
return fmt.Errorf("error updating CodeDeploy Application (%s) tags: %w", d.Get("arn").(string), err)
}
}
log.Printf("[DEBUG] CodeDeploy application %s updated", n)

d.Set("name", n)

return nil
return resourceAwsCodeDeployAppRead(d, meta)
}

func resourceAwsCodeDeployAppDelete(d *schema.ResourceData, meta interface{}) error {
Expand All @@ -156,12 +187,12 @@ func resourceAwsCodeDeployAppDelete(d *schema.ResourceData, meta interface{}) er
ApplicationName: aws.String(d.Get("name").(string)),
})
if err != nil {
if cderr, ok := err.(awserr.Error); ok && cderr.Code() == "InvalidApplicationNameException" {
if isAWSErr(err, codedeploy.ErrCodeApplicationDoesNotExistException, "") {
return nil
} else {
log.Printf("[ERROR] Error deleting CodeDeploy application: %s", err)
return err
}

log.Printf("[ERROR] Error deleting CodeDeploy application: %s", err)
return err
}

return nil
Expand Down
149 changes: 149 additions & 0 deletions aws/resource_aws_codedeploy_app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,67 @@ package aws
import (
"errors"
"fmt"
"log"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/codedeploy"
"github.com/hashicorp/go-multierror"
"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"
)

func init() {
resource.AddTestSweepers("aws_codedeploy_app", &resource.Sweeper{
Name: "aws_codedeploy_app",
F: testSweepCodeDeployApps,
})
}

func testSweepCodeDeployApps(region string) error {
client, err := sharedClientForRegion(region)
if err != nil {
return fmt.Errorf("error getting client: %s", err)
}
conn := client.(*AWSClient).codedeployconn
input := &codedeploy.ListApplicationsInput{}
var sweeperErrs *multierror.Error

err = conn.ListApplicationsPages(input, func(page *codedeploy.ListApplicationsOutput, lastPage bool) bool {
for _, app := range page.Applications {
if app == nil {
continue
}

appName := aws.StringValue(app)
r := resourceAwsCodeDeployApp()
d := r.Data(nil)
d.SetId(fmt.Sprintf("%s:%s", "xxxx", appName))
err = r.Delete(d, client)

if err != nil {
sweeperErr := fmt.Errorf("error deleting CodeDeploy Application (%s): %w", appName, err)
log.Printf("[ERROR] %s", sweeperErr)
sweeperErrs = multierror.Append(sweeperErrs, sweeperErr)
}
}

return !lastPage
})

if testSweepSkipSweepError(err) {
log.Printf("[WARN] Skipping CodeDeploy Application sweep for %s: %s", region, err)
return nil
}

if err != nil {
return fmt.Errorf("error listing CodeDeploy Applications: %w", err)
}

return sweeperErrs.ErrorOrNil()
}

func TestAccAWSCodeDeployApp_basic(t *testing.T) {
var application1 codedeploy.ApplicationInfo
rName := acctest.RandomWithPrefix("tf-acc-test")
Expand All @@ -27,8 +79,12 @@ func TestAccAWSCodeDeployApp_basic(t *testing.T) {
Config: testAccAWSCodeDeployAppConfigName(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSCodeDeployAppExists(resourceName, &application1),
testAccCheckResourceAttrRegionalARN(resourceName, "arn", "codedeploy", fmt.Sprintf(`application:%s`, rName)),
resource.TestCheckResourceAttr(resourceName, "compute_platform", "Server"),
resource.TestCheckResourceAttr(resourceName, "name", rName),
resource.TestCheckResourceAttr(resourceName, "linked_to_github", "false"),
resource.TestCheckResourceAttr(resourceName, "tags.%", "0"),
resource.TestCheckResourceAttrSet(resourceName, "application_id"),
),
},
// Import by ID
Expand Down Expand Up @@ -168,6 +224,74 @@ func TestAccAWSCodeDeployApp_name(t *testing.T) {
})
}

func TestAccAWSCodeDeployApp_tags(t *testing.T) {
var application codedeploy.ApplicationInfo
rName := acctest.RandomWithPrefix("tf-acc-test")
resourceName := "aws_codedeploy_app.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, codedeploy.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSCodeDeployAppDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSCodeDeployAppConfigTags1(rName, "key1", "value1"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSCodeDeployAppExists(resourceName, &application),
resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccAWSCodeDeployAppConfigTags2(rName, "key1", "value1updated", "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSCodeDeployAppExists(resourceName, &application),
resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"),
resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"),
),
},
{
Config: testAccAWSCodeDeployAppConfigTags1(rName, "key2", "value2"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSCodeDeployAppExists(resourceName, &application),
resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"),
),
},
},
})
}

func TestAccAWSCodeDeployApp_disappears(t *testing.T) {
var application1 codedeploy.ApplicationInfo
rName := acctest.RandomWithPrefix("tf-acc-test")
resourceName := "aws_codedeploy_app.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, codedeploy.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSCodeDeployAppDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSCodeDeployAppConfigName(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSCodeDeployAppExists(resourceName, &application1),
testAccCheckResourceDisappears(testAccProvider, resourceAwsCodeDeployApp(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckAWSCodeDeployAppDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).codedeployconn

Expand Down Expand Up @@ -249,3 +373,28 @@ resource "aws_codedeploy_app" "test" {
}
`, rName)
}

func testAccAWSCodeDeployAppConfigTags1(rName, tagKey1, tagValue1 string) string {
return fmt.Sprintf(`
resource "aws_codedeploy_app" "test" {
name = %[1]q

tags = {
%[2]q = %[3]q
}
}
`, rName, tagKey1, tagValue1)
}

func testAccAWSCodeDeployAppConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string {
return fmt.Sprintf(`
resource "aws_codedeploy_app" "test" {
name = %[1]q

tags = {
%[2]q = %[3]q
%[4]q = %[5]q
}
}
`, rName, tagKey1, tagValue1, tagKey2, tagValue2)
}
Loading