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/ce_cost_allocation_tag - new resource #25272

Merged
merged 6 commits into from
Jun 22, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 3 additions & 0 deletions .changelog/25272.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_ce_cost_allocation_tag
```
3 changes: 2 additions & 1 deletion internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1046,9 +1046,10 @@ func Provider() *schema.Provider {
"aws_budgets_budget": budgets.ResourceBudget(),
"aws_budgets_budget_action": budgets.ResourceBudgetAction(),

"aws_ce_cost_category": ce.ResourceCostCategory(),
"aws_ce_anomaly_monitor": ce.ResourceAnomalyMonitor(),
"aws_ce_anomaly_subscription": ce.ResourceAnomalySubscription(),
"aws_ce_cost_allocation_tag": ce.ResourceCostAllocationTag(),
"aws_ce_cost_category": ce.ResourceCostCategory(),

"aws_chime_voice_connector": chime.ResourceVoiceConnector(),
"aws_chime_voice_connector_group": chime.ResourceVoiceConnectorGroup(),
Expand Down
1 change: 1 addition & 0 deletions internal/service/ce/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ const (
ResAnomalyMonitor = "Anomaly Monitor"
ResAnomalySubscription = "Anomaly Subscription"
ResCostCategory = "Cost Category"
ResCostAllocationTag = "Cost Allocation Tags"
ResTags = "Tags"
)
104 changes: 104 additions & 0 deletions internal/service/ce/cost_allocation_tag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package ce

import (
"context"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/costexplorer"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"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"
"github.com/hashicorp/terraform-provider-aws/names"
)

func ResourceCostAllocationTag() *schema.Resource {
return &schema.Resource{
CreateContext: resourceCostAllocationTagUpdate,
ReadContext: resourceCostAllocationTagRead,
UpdateContext: resourceCostAllocationTagUpdate,
DeleteContext: resourceCostAllocationTagDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"status": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(costexplorer.CostAllocationTagStatus_Values(), false),
},
"tag_key": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 1024),
},
"type": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func resourceCostAllocationTagRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).CEConn

costAllocTag, err := FindCostAllocationTagByKey(ctx, conn, d.Id())

if !d.IsNewResource() && tfresource.NotFound(err) {
names.LogNotFoundRemoveState(names.CE, names.ErrActionReading, ResCostAllocationTag, d.Id())
d.SetId("")
return nil
}

if err != nil {
return names.DiagError(names.CE, names.ErrActionReading, ResCostAllocationTag, d.Id(), err)
}

d.Set("tag_key", costAllocTag.TagKey)
d.Set("status", costAllocTag.Status)
d.Set("type", costAllocTag.Type)

return nil
}

func resourceCostAllocationTagUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
key := d.Get("tag_key").(string)

updateTagStatus(ctx, d, meta, false)

d.SetId(key)

return resourceCostAllocationTagRead(ctx, d, meta)
}

func resourceCostAllocationTagDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
return updateTagStatus(ctx, d, meta, true)
}

func updateTagStatus(ctx context.Context, d *schema.ResourceData, meta interface{}, delete bool) diag.Diagnostics {
conn := meta.(*conns.AWSClient).CEConn

key := d.Get("tag_key").(string)
tagStatus := &costexplorer.CostAllocationTagStatusEntry{
TagKey: aws.String(key),
Status: aws.String(d.Get("status").(string)),
}

if delete {
tagStatus.Status = aws.String(costexplorer.CostAllocationTagStatusInactive)
}

input := &costexplorer.UpdateCostAllocationTagsStatusInput{
CostAllocationTagsStatus: []*costexplorer.CostAllocationTagStatusEntry{tagStatus},
}

_, err := conn.UpdateCostAllocationTagsStatusWithContext(ctx, input)

if err != nil {
return names.DiagError(names.CE, names.ErrActionUpdating, ResCostAllocationTag, d.Id(), err)
}

return nil
}
92 changes: 92 additions & 0 deletions internal/service/ce/cost_allocation_tag_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package ce_test

import (
"context"
"errors"
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/costexplorer"
"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"
tfce "github.com/hashicorp/terraform-provider-aws/internal/service/ce"
"github.com/hashicorp/terraform-provider-aws/names"
)

func TestAccCECostAllocationTag_basic(t *testing.T) {
var output costexplorer.CostAllocationTag
resourceName := "aws_ce_cost_allocation_tag.test"
rName := "Tag01"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ProviderFactories: acctest.ProviderFactories,
CheckDestroy: nil,
ErrorCheck: acctest.ErrorCheck(t, costexplorer.EndpointsID),
Steps: []resource.TestStep{
{
Config: testAccCostAllocationTagConfig(rName, "Active"),
Check: resource.ComposeTestCheckFunc(
testAccCheckCostAllocationTagExists(resourceName, &output),
resource.TestCheckResourceAttr(resourceName, "tag_key", rName),
resource.TestCheckResourceAttr(resourceName, "status", "Active"),
resource.TestCheckResourceAttr(resourceName, "type", "UserDefined"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccCostAllocationTagConfig(rName, "Inactive"),
Check: resource.ComposeTestCheckFunc(
testAccCheckCostAllocationTagExists(resourceName, &output),
resource.TestCheckResourceAttr(resourceName, "tag_key", rName),
resource.TestCheckResourceAttr(resourceName, "status", "Inactive"),
resource.TestCheckResourceAttr(resourceName, "type", "UserDefined"),
),
}, {
Config: testAccCostAllocationTagConfig(rName, "Active"),
Check: resource.ComposeTestCheckFunc(
testAccCheckCostAllocationTagExists(resourceName, &output),
resource.TestCheckResourceAttr(resourceName, "tag_key", rName),
resource.TestCheckResourceAttr(resourceName, "status", "Active"),
resource.TestCheckResourceAttr(resourceName, "type", "UserDefined"),
),
},
},
})
}

func testAccCheckCostAllocationTagExists(resourceName string, output *costexplorer.CostAllocationTag) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return names.Error(names.CE, names.ErrActionCheckingExistence, tfce.ResCostAllocationTag, resourceName, errors.New("not found in state"))
}

ctx := context.TODO()
conn := acctest.Provider.Meta().(*conns.AWSClient).CEConn
costAllocTag, err := tfce.FindCostAllocationTagByKey(ctx, conn, rs.Primary.ID)

if err != nil {
return err
}

*output = *costAllocTag

return nil
}
}

func testAccCostAllocationTagConfig(rName, status string) string {
return fmt.Sprintf(`
resource "aws_ce_cost_allocation_tag" "test" {
tag_key = %[1]q
status = %[2]q
}
`, rName, status)
}
26 changes: 26 additions & 0 deletions internal/service/ce/find.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,29 @@ func FindAnomalySubscriptionByARN(ctx context.Context, conn *costexplorer.CostEx

return out.AnomalySubscriptions[0], nil
}

func FindCostAllocationTagByKey(ctx context.Context, conn *costexplorer.CostExplorer, key string) (*costexplorer.CostAllocationTag, error) {
in := &costexplorer.ListCostAllocationTagsInput{
TagKeys: aws.StringSlice([]string{key}),
MaxResults: aws.Int64(1),
}

out, err := conn.ListCostAllocationTagsWithContext(ctx, in)

if tfawserr.ErrCodeEquals(err, costexplorer.ErrCodeUnknownMonitorException) {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: in,
}
}

if err != nil {
return nil, err
}

if out == nil || len(out.CostAllocationTags) == 0 || out.CostAllocationTags[0] == nil {
return nil, tfresource.NewEmptyResultError(in)
}

return out.CostAllocationTags[0], nil
}
42 changes: 42 additions & 0 deletions website/docs/r/ce_cost_allocation_tag.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
subcategory: "CE (Cost Explorer)"
layout: "aws"
page_title: "AWS: aws_ce_cost_allocation_tag"
description: |-
Provides a CE Cost Allocation Tag
---

# Resource: aws_ce_cost_allocation_tag

Provides a CE Cost Allocation Tag.

## Example Usage

```terraform
resource "aws_ce_cost_allocation_tag" "example" {
tag_key = "example"
status = "Active"
}
```

## Argument Reference

The following arguments are required:

* `tag_key` - (Required) The key for the cost allocation tag.
* `status` - (Required) The status of a cost allocation tag. Valid values are `Active` and `Inactive`.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `id` - The key for the cost allocation tag.
* `type` - The type of cost allocation tag.

## Import

`aws_ce_cost_allocation_tag` can be imported using the `id`, e.g.

```
$ terraform import aws_ce_cost_allocation_tag.example key
```