Skip to content

Commit

Permalink
Merge pull request #3103 from terraform-providers/f/api-management-su…
Browse files Browse the repository at this point in the history
…bscription

New Resource: `azurerm_api_management_subscription`
  • Loading branch information
tombuildsstuff authored Mar 24, 2019
2 parents d289eb2 + a3175ec commit b1421a0
Show file tree
Hide file tree
Showing 7 changed files with 603 additions and 0 deletions.
5 changes: 5 additions & 0 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ type ArmClient struct {
apiManagementProductGroupsClient apimanagement.ProductGroupClient
apiManagementPropertyClient apimanagement.PropertyClient
apiManagementServiceClient apimanagement.ServiceClient
apiManagementSubscriptionsClient apimanagement.SubscriptionClient
apiManagementUsersClient apimanagement.UserClient

// Application Insights
Expand Down Expand Up @@ -533,6 +534,10 @@ func (c *ArmClient) registerApiManagementServiceClients(endpoint, subscriptionId
c.configureClient(&propertiesClient.Client, auth)
c.apiManagementPropertyClient = propertiesClient

subscriptionsClient := apimanagement.NewSubscriptionClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&subscriptionsClient.Client, auth)
c.apiManagementSubscriptionsClient = subscriptionsClient

usersClient := apimanagement.NewUserClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&usersClient.Client, auth)
c.apiManagementUsersClient = usersClient
Expand Down
11 changes: 11 additions & 0 deletions azurerm/helpers/azure/api_management.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ func SchemaApiManagementDataSourceName() *schema.Schema {
}
}

// SchemaApiManagementChildID returns the Schema for the identifier
// used by resources within nested under the API Management Service resource
func SchemaApiManagementChildID() *schema.Schema {
return &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: ValidateResourceID,
}
}

// SchemaApiManagementChildName returns the Schema for the identifier
// used by resources within nested under the API Management Service resource
func SchemaApiManagementChildName() *schema.Schema {
Expand Down
13 changes: 13 additions & 0 deletions azurerm/helpers/azure/resourceid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,19 @@ func TestParseAzureResourceID(t *testing.T) {
},
false,
},
{
"/subscriptions/11111111-1111-1111-1111-111111111111/resourceGroups/example-resources/providers/Microsoft.ApiManagement/service/service1/subscriptions/22222222-2222-2222-2222-222222222222",
&ResourceID{
SubscriptionID: "11111111-1111-1111-1111-111111111111",
ResourceGroup: "example-resources",
Provider: "Microsoft.ApiManagement",
Path: map[string]string{
"service": "service1",
"subscriptions": "22222222-2222-2222-2222-222222222222",
},
},
false,
},
}

for _, test := range testCases {
Expand Down
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_api_management_product_api": resourceArmApiManagementProductApi(),
"azurerm_api_management_product_group": resourceArmApiManagementProductGroup(),
"azurerm_api_management_property": resourceArmApiManagementProperty(),
"azurerm_api_management_subscription": resourceArmApiManagementSubscription(),
"azurerm_api_management_user": resourceArmApiManagementUser(),
"azurerm_app_service_active_slot": resourceArmAppServiceActiveSlot(),
"azurerm_app_service_custom_hostname_binding": resourceArmAppServiceCustomHostnameBinding(),
Expand Down
201 changes: 201 additions & 0 deletions azurerm/resource_arm_api_management_subscription.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
package azurerm

import (
"fmt"
"log"

"github.com/Azure/azure-sdk-for-go/services/apimanagement/mgmt/2018-01-01/apimanagement"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/satori/uuid"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmApiManagementSubscription() *schema.Resource {
return &schema.Resource{
Create: resourceArmApiManagementSubscriptionCreateUpdate,
Read: resourceArmApiManagementSubscriptionRead,
Update: resourceArmApiManagementSubscriptionCreateUpdate,
Delete: resourceArmApiManagementSubscriptionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"subscription_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validate.UUIDOrEmpty,
},

"user_id": azure.SchemaApiManagementChildID(),

"product_id": azure.SchemaApiManagementChildID(),

"resource_group_name": resourceGroupNameSchema(),

"api_management_name": azure.SchemaApiManagementName(),

"display_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},

"state": {
Type: schema.TypeString,
Optional: true,
Default: string(apimanagement.Submitted),
ValidateFunc: validation.StringInSlice([]string{
string(apimanagement.Active),
string(apimanagement.Cancelled),
string(apimanagement.Expired),
string(apimanagement.Rejected),
string(apimanagement.Submitted),
string(apimanagement.Suspended),
}, false),
},

"primary_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Sensitive: true,
},

"secondary_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Sensitive: true,
},
},
}
}

func resourceArmApiManagementSubscriptionCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).apiManagementSubscriptionsClient
ctx := meta.(*ArmClient).StopContext

resourceGroup := d.Get("resource_group_name").(string)
serviceName := d.Get("api_management_name").(string)
subscriptionId := d.Get("subscription_id").(string)
if subscriptionId == "" {
subscriptionId = uuid.NewV4().String()
}

if requireResourcesToBeImported {
resp, err := client.Get(ctx, resourceGroup, serviceName, subscriptionId)
if err != nil {
if !utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Error checking for present of existing Subscription %q (API Management Service %q / Resource Group %q): %+v", subscriptionId, serviceName, resourceGroup, err)
}
}

if !utils.ResponseWasNotFound(resp.Response) {
return tf.ImportAsExistsError("azurerm_api_management_subscription", *resp.ID)
}
}

displayName := d.Get("display_name").(string)
productId := d.Get("product_id").(string)
state := d.Get("state").(string)
userId := d.Get("user_id").(string)

params := apimanagement.SubscriptionCreateParameters{
SubscriptionCreateParameterProperties: &apimanagement.SubscriptionCreateParameterProperties{
DisplayName: utils.String(displayName),
ProductID: utils.String(productId),
State: apimanagement.SubscriptionState(state),
UserID: utils.String(userId),
},
}

if v, ok := d.GetOk("primary_key"); ok {
params.SubscriptionCreateParameterProperties.PrimaryKey = utils.String(v.(string))
}

if v, ok := d.GetOk("secondary_key"); ok {
params.SubscriptionCreateParameterProperties.SecondaryKey = utils.String(v.(string))
}

sendEmail := utils.Bool(false)
_, err := client.CreateOrUpdate(ctx, resourceGroup, serviceName, subscriptionId, params, sendEmail, "")
if err != nil {
return fmt.Errorf("Error creating/updating Subscription %q (API Management Service %q / Resource Group %q): %+v", subscriptionId, serviceName, resourceGroup, err)
}

resp, err := client.Get(ctx, resourceGroup, serviceName, subscriptionId)
if err != nil {
return fmt.Errorf("Error retrieving Subscription %q (API Management Service %q / Resource Group %q): %+v", subscriptionId, serviceName, resourceGroup, err)
}

d.SetId(*resp.ID)

return resourceArmApiManagementSubscriptionRead(d, meta)
}

func resourceArmApiManagementSubscriptionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).apiManagementSubscriptionsClient
ctx := meta.(*ArmClient).StopContext

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
serviceName := id.Path["service"]
subscriptionId := id.Path["subscriptions"]

resp, err := client.Get(ctx, resourceGroup, serviceName, subscriptionId)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Subscription %q was not found in API Management Service %q / Resource Group %q - removing from state!", subscriptionId, serviceName, resourceGroup)
d.SetId("")
return nil
}

return fmt.Errorf("Error retrieving Subscription %q (API Management Service %q / Resource Group %q): %+v", subscriptionId, serviceName, resourceGroup, err)
}

d.Set("subscription_id", subscriptionId)
d.Set("resource_group_name", resourceGroup)
d.Set("api_management_name", serviceName)

if props := resp.SubscriptionContractProperties; props != nil {
d.Set("display_name", props.DisplayName)
d.Set("primary_key", props.PrimaryKey)
d.Set("secondary_key", props.SecondaryKey)
d.Set("state", string(props.State))
d.Set("product_id", props.ProductID)
d.Set("user_id", props.UserID)
}

return nil
}

func resourceArmApiManagementSubscriptionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).apiManagementSubscriptionsClient
ctx := meta.(*ArmClient).StopContext

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
serviceName := id.Path["service"]
subscriptionId := id.Path["subscriptions"]

if resp, err := client.Delete(ctx, resourceGroup, serviceName, subscriptionId, ""); err != nil {
if !utils.ResponseWasNotFound(resp) {
return fmt.Errorf("Error removing Subscription %q (API Management Service %q / Resource Group %q): %+v", subscriptionId, serviceName, resourceGroup, err)
}
}

return nil
}
Loading

0 comments on commit b1421a0

Please sign in to comment.