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

New Resource: azurerm_api_management_product_tag - Support API Management product tag #17798

Merged
merged 3 commits into from
Aug 30, 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package apimanagement

import (
"fmt"
"log"
"time"

"github.com/hashicorp/terraform-provider-azurerm/helpers/azure"
"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/apimanagement/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/apimanagement/schemaz"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

func resourceApiManagementProductTag() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceApiManagementProductTagCreate,
Read: resourceApiManagementProductTagRead,
Delete: resourceApiManagementProductTagDelete,
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.ProductTagID(id)
return err
}),

Timeouts: &pluginsdk.ResourceTimeout{
Create: pluginsdk.DefaultTimeout(30 * time.Minute),
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
Update: pluginsdk.DefaultTimeout(30 * time.Minute),
Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
},

Schema: map[string]*pluginsdk.Schema{
"api_management_product_id": schemaz.SchemaApiManagementChildName(),

"api_management_name": schemaz.SchemaApiManagementName(),

"resource_group_name": azure.SchemaResourceGroupName(),

"name": schemaz.SchemaApiManagementChildName(),
},
}
}

func resourceApiManagementProductTagCreate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).ApiManagement.TagClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()

id := parse.NewProductTagID(subscriptionId, d.Get("resource_group_name").(string), d.Get("api_management_name").(string), d.Get("api_management_product_id").(string), d.Get("name").(string))

if d.IsNewResource() {
existing, err := client.GetByProduct(ctx, id.ResourceGroup, id.ServiceName, id.ProductName, id.TagName)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing %s: %s", id, err)
}
}

if !utils.ResponseWasNotFound(existing.Response) {
return tf.ImportAsExistsError("azurerm_api_management_product_tag", id.ID())
}
}

resp, err := client.AssignToProduct(ctx, id.ResourceGroup, id.ServiceName, id.ProductName, id.TagName)
if err != nil {
return fmt.Errorf(" creating product tag (id : %s): %+v", id, err)
}
d.SetId(*resp.ID)

return resourceApiManagementProductTagRead(d, meta)
}

func resourceApiManagementProductTagRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).ApiManagement.TagClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := parse.ProductTagID(d.Id())
if err != nil {
return err
}

resp, err := client.GetByProduct(ctx, id.ResourceGroup, id.ServiceName, id.ProductName, id.TagName)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("%s was not found - removing from state!", *id)
d.SetId("")
return nil
}

return fmt.Errorf("making Read request on %s: %+v", *id, err)
}

productTagId, err := parse.ProductTagID(*resp.ID)
if err != nil {
return err
}

d.Set("api_management_product_id", productTagId.ProductName)
d.Set("api_management_name", productTagId.ServiceName)
d.Set("resource_group_name", productTagId.ResourceGroup)
d.Set("name", productTagId.TagName)

return nil
}

func resourceApiManagementProductTagDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).ApiManagement.TagClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := parse.ProductTagID(d.Id())
if err != nil {
return err
}

log.Printf("[DEBUG] Deleting %s", *id)
resp, err := client.DetachFromProduct(ctx, id.ResourceGroup, id.ServiceName, id.ProductName, id.TagName)
if err != nil {
if !utils.ResponseWasNotFound(resp) {
return fmt.Errorf("deleting %s: %+v", *id, err)
}
}

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package apimanagement_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/apimanagement/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

type ApiManagementProductTagResource struct{}

func TestAccApiManagementProductTag_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_api_management_product_tag", "test")
r := ApiManagementProductTagResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
check.That(data.ResourceName).Key("api_management_product_id").Exists(),
check.That(data.ResourceName).Key("api_management_name").Exists(),
check.That(data.ResourceName).Key("resource_group_name").Exists(),
check.That(data.ResourceName).Key("name").Exists(),
),
},
data.ImportStep(),
})
}

func TestAccApiManagementProductTag_requiresImport(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_api_management_product_tag", "test")
r := ApiManagementProductTagResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.RequiresImportErrorStep(r.requiresImport),
})
}

func (ApiManagementProductTagResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := parse.ProductTagID(state.ID)
if err != nil {
return nil, err
}

resp, err := clients.ApiManagement.TagClient.GetByProduct(ctx, id.ResourceGroup, id.ServiceName, id.ProductName, id.TagName)
if err != nil {
return nil, fmt.Errorf("reading %s: %+v", *id, err)
}

return utils.Bool(resp.ID != nil), nil
}

func (ApiManagementProductTagResource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}

resource "azurerm_resource_group" "test" {
name = "acctestRG-%d"
location = "%s"
}

resource "azurerm_api_management" "test" {
name = "acctestAM-%d"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
publisher_name = "pub1"
publisher_email = "[email protected]"

sku_name = "Consumption_0"
}

resource "azurerm_api_management_product" "test" {
product_id = "test-product"
api_management_name = azurerm_api_management.test.name
resource_group_name = azurerm_resource_group.test.name
display_name = "Test Product"
subscription_required = false
published = false
}

resource "azurerm_api_management_tag" "test" {
api_management_id = azurerm_api_management.test.id
name = "acctestTag-%d"
}

resource "azurerm_api_management_product_tag" "test" {
api_management_product_id = azurerm_api_management_product.test.product_id
api_management_name = azurerm_api_management.test.name
resource_group_name = azurerm_resource_group.test.name
name = azurerm_api_management_tag.test.name
}
`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger)
}

func (r ApiManagementProductTagResource) requiresImport(data acceptance.TestData) string {
return fmt.Sprintf(`
%s

resource "azurerm_api_management_product_tag" "import" {
api_management_product_id = azurerm_api_management_product_tag.test.api_management_product_id
api_management_name = azurerm_api_management_product_tag.test.api_management_name
resource_group_name = azurerm_api_management_product_tag.test.resource_group_name
name = azurerm_api_management_product_tag.test.name
}
`, r.basic(data))
}
81 changes: 81 additions & 0 deletions internal/services/apimanagement/parse/product_tag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package parse

// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten

import (
"fmt"
"strings"

"github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids"
)

type ProductTagId struct {
SubscriptionId string
ResourceGroup string
ServiceName string
ProductName string
TagName string
}

func NewProductTagID(subscriptionId, resourceGroup, serviceName, productName, tagName string) ProductTagId {
return ProductTagId{
SubscriptionId: subscriptionId,
ResourceGroup: resourceGroup,
ServiceName: serviceName,
ProductName: productName,
TagName: tagName,
}
}

func (id ProductTagId) String() string {
segments := []string{
fmt.Sprintf("Tag Name %q", id.TagName),
fmt.Sprintf("Product Name %q", id.ProductName),
fmt.Sprintf("Service Name %q", id.ServiceName),
fmt.Sprintf("Resource Group %q", id.ResourceGroup),
}
segmentsStr := strings.Join(segments, " / ")
return fmt.Sprintf("%s: (%s)", "Product Tag", segmentsStr)
}

func (id ProductTagId) ID() string {
fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ApiManagement/service/%s/products/%s/tags/%s"
return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.ServiceName, id.ProductName, id.TagName)
}

// ProductTagID parses a ProductTag ID into an ProductTagId struct
func ProductTagID(input string) (*ProductTagId, error) {
id, err := resourceids.ParseAzureResourceID(input)
if err != nil {
return nil, err
}

resourceId := ProductTagId{
SubscriptionId: id.SubscriptionID,
ResourceGroup: id.ResourceGroup,
}

if resourceId.SubscriptionId == "" {
return nil, fmt.Errorf("ID was missing the 'subscriptions' element")
}

if resourceId.ResourceGroup == "" {
return nil, fmt.Errorf("ID was missing the 'resourceGroups' element")
}

if resourceId.ServiceName, err = id.PopSegment("service"); err != nil {
return nil, err
}
if resourceId.ProductName, err = id.PopSegment("products"); err != nil {
return nil, err
}
if resourceId.TagName, err = id.PopSegment("tags"); err != nil {
return nil, err
}

if err := id.ValidateNoEmptySegments(input); err != nil {
return nil, err
}

return &resourceId, nil
}
Loading