Skip to content

Commit

Permalink
Merge pull request #2556 from pdecat/f-azurerm_application_insights_a…
Browse files Browse the repository at this point in the history
…pi_key

Add azurerm_application_insights_api_key resource
  • Loading branch information
katbyte authored Dec 28, 2018
2 parents 01ca86a + b46ed17 commit 44fb9c4
Show file tree
Hide file tree
Showing 7 changed files with 615 additions and 1 deletion.
7 changes: 6 additions & 1 deletion azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ type ArmClient struct {
apiManagementServiceClient apimanagement.ServiceClient

// Application Insights
appInsightsClient appinsights.ComponentsClient
appInsightsClient appinsights.ComponentsClient
appInsightsAPIKeyClient appinsights.APIKeysClient

// Authentication
roleAssignmentsClient authorization.RoleAssignmentsClient
Expand Down Expand Up @@ -480,6 +481,10 @@ func (c *ArmClient) registerAppInsightsClients(endpoint, subscriptionId string,
ai := appinsights.NewComponentsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&ai.Client, auth)
c.appInsightsClient = ai

aiak := appinsights.NewAPIKeysClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&aiak.Client, auth)
c.appInsightsAPIKeyClient = aiak
}

func (c *ArmClient) registerAutomationClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
Expand Down
33 changes: 33 additions & 0 deletions azurerm/helpers/azure/app_insights.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package azure

import (
"fmt"
"strings"

"github.com/hashicorp/terraform/helper/schema"
)

func ExpandApplicationInsightsAPIKeyLinkedProperties(v *schema.Set, appInsightsId string) *[]string {
if v == nil {
return &[]string{}
}

result := make([]string, v.Len())
for i, prop := range v.List() {
result[i] = fmt.Sprintf("%s/%s", appInsightsId, prop)
}
return &result
}

func FlattenApplicationInsightsAPIKeyLinkedProperties(props *[]string) *[]string {
if props == nil {
return &[]string{}
}

result := make([]string, len(*props))
for i, prop := range *props {
elems := strings.Split(prop, "/")
result[i] = elems[len(elems)-1]
}
return &result
}
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_api_management": resourceArmApiManagementService(),
"azurerm_application_gateway": resourceArmApplicationGateway(),
"azurerm_application_insights": resourceArmApplicationInsights(),
"azurerm_application_insights_api_key": resourceArmApplicationInsightsAPIKey(),
"azurerm_application_security_group": resourceArmApplicationSecurityGroup(),
"azurerm_app_service": resourceArmAppService(),
"azurerm_app_service_plan": resourceArmAppServicePlan(),
Expand Down
188 changes: 188 additions & 0 deletions azurerm/resource_arm_application_insights_api_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package azurerm

import (
"fmt"
"log"

"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"

"github.com/Azure/azure-sdk-for-go/services/appinsights/mgmt/2015-05-01/insights"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmApplicationInsightsAPIKey() *schema.Resource {
return &schema.Resource{
Create: resourceArmApplicationInsightsAPIKeyCreate,
Read: resourceArmApplicationInsightsAPIKeyRead,
Delete: resourceArmApplicationInsightsAPIKeyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},

"application_insights_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
},

"read_permissions": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Set: schema.HashString,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"agentconfig", "aggregate", "api", "draft", "extendqueries", "search"}, false),
},
},

"write_permissions": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Set: schema.HashString,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{"annotations"}, false),
},
},

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

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

log.Printf("[INFO] preparing arguments for AzureRM Application Insights API key creation.")

name := d.Get("name").(string)
appInsightsID := d.Get("application_insights_id").(string)

id, err := parseAzureResourceID(appInsightsID)
if err != nil {
return err
}

resGroup := id.ResourceGroup
appInsightsName := id.Path["components"]

if requireResourcesToBeImported && d.IsNewResource() {
var existing insights.ApplicationInsightsComponentAPIKey
existing, err = client.Get(ctx, resGroup, appInsightsName, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Application Insights API key %q (Resource Group %q): %s", name, resGroup, err)
}
}

if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_application_insights_api_key", *existing.ID)
}
}

apiKeyProperties := insights.APIKeyRequest{
Name: &name,
LinkedReadProperties: azure.ExpandApplicationInsightsAPIKeyLinkedProperties(d.Get("read_permissions").(*schema.Set), appInsightsID),
LinkedWriteProperties: azure.ExpandApplicationInsightsAPIKeyLinkedProperties(d.Get("write_permissions").(*schema.Set), appInsightsID),
}

result, err := client.Create(ctx, resGroup, appInsightsName, apiKeyProperties)
if err != nil {
return fmt.Errorf("Error creating Application Insights API key %q (Resource Group %q): %+v", name, resGroup, err)
}

if result.APIKey == nil {
return fmt.Errorf("Error creating Application Insights API key %q (Resource Group %q): got empty API key", name, resGroup)
}

d.SetId(*result.ID)

// API key can only retrieved at key creation
d.Set("api_key", result.APIKey)

return resourceArmApplicationInsightsAPIKeyRead(d, meta)
}

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

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

log.Printf("[DEBUG] Reading AzureRM Application Insights API key '%s'", id)

resGroup := id.ResourceGroup
appInsightsName := id.Path["components"]
keyID := id.Path["apikeys"]

result, err := client.Get(ctx, resGroup, appInsightsName, keyID)
if err != nil {
if utils.ResponseWasNotFound(result.Response) {
log.Printf("[WARN] AzureRM Application Insights API key '%s' not found, removing from state", id)
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on AzureRM Application Insights API key '%s': %+v", keyID, err)
}

d.Set("application_insights_id", fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s", client.SubscriptionID, resGroup, appInsightsName))

d.Set("name", result.Name)
readProps := azure.FlattenApplicationInsightsAPIKeyLinkedProperties(result.LinkedReadProperties)
if err := d.Set("read_permissions", readProps); err != nil {
return fmt.Errorf("Error flattening `read_permissions `: %s", err)
}
writeProps := azure.FlattenApplicationInsightsAPIKeyLinkedProperties(result.LinkedWriteProperties)
if err := d.Set("write_permissions", writeProps); err != nil {
return fmt.Errorf("Error flattening `write_permissions `: %s", err)
}

return nil
}

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

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
appInsightsName := id.Path["components"]
keyID := id.Path["apikeys"]

log.Printf("[DEBUG] Deleting AzureRM Application Insights API key '%s' (resource group '%s')", keyID, resGroup)

result, err := client.Delete(ctx, resGroup, appInsightsName, keyID)
if err != nil {
if utils.ResponseWasNotFound(result.Response) {
return nil
}
return fmt.Errorf("Error issuing AzureRM delete request for Application Insights API key '%s': %+v", keyID, err)
}

return nil
}
Loading

0 comments on commit 44fb9c4

Please sign in to comment.