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

Application Insights Webtests #3331

Merged
merged 22 commits into from
May 18, 2019
Merged
Show file tree
Hide file tree
Changes from 20 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
9 changes: 7 additions & 2 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,9 @@ type ArmClient struct {
apiManagementUsersClient apimanagement.UserClient

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

// Authentication
roleAssignmentsClient authorization.RoleAssignmentsClient
Expand Down Expand Up @@ -639,6 +640,10 @@ func (c *ArmClient) registerAppInsightsClients(endpoint, subscriptionId string,
aiak := appinsights.NewAPIKeysClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&aiak.Client, auth)
c.appInsightsAPIKeyClient = aiak

aiwt := appinsights.NewWebTestsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&aiwt.Client, auth)
c.appInsightsWebTestsClient = aiwt
}

func (c *ArmClient) registerAutomationClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
Expand Down
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_application_gateway": resourceArmApplicationGateway(),
"azurerm_application_insights_api_key": resourceArmApplicationInsightsAPIKey(),
"azurerm_application_insights": resourceArmApplicationInsights(),
"azurerm_application_insights_web_test": resourceArmApplicationInsightsWebTests(),
"azurerm_application_security_group": resourceArmApplicationSecurityGroup(),
"azurerm_automation_account": resourceArmAutomationAccount(),
"azurerm_automation_credential": resourceArmAutomationCredential(),
Expand Down
314 changes: 314 additions & 0 deletions azurerm/resource_arm_application_insights_webtests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
package azurerm

import (
"fmt"
"log"
"net/http"
"strings"

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

"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 resourceArmApplicationInsightsWebTests() *schema.Resource {
return &schema.Resource{
Create: resourceArmApplicationInsightsWebTestsCreateUpdate,
Read: resourceArmApplicationInsightsWebTestsRead,
Update: resourceArmApplicationInsightsWebTestsCreateUpdate,
Delete: resourceArmApplicationInsightsWebTestsDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
AndyMoore marked this conversation as resolved.
Show resolved Hide resolved

"resource_group_name": resourceGroupNameSchema(),

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

"location": locationSchema(),

"kind": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(insights.Multistep),
string(insights.Ping),
}, false),
},

"frequency": {
Type: schema.TypeInt,
Optional: true,
Default: 300,
ValidateFunc: validation.IntInSlice([]int{
300,
600,
900,
}),
},

"timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 30,
},

"enabled": {
Type: schema.TypeBool,
Optional: true,
},

"retry_enabled": {
Type: schema.TypeBool,
Optional: true,
},

"geo_locations": {
Type: schema.TypeList,
Required: true,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validate.NoEmptyStrings,
StateFunc: azureRMNormalizeLocation,
DiffSuppressFunc: azureRMSuppressLocationDiff,
},
},

"description": {
Type: schema.TypeString,
Optional: true,
},

"test_configuration": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: suppress.XmlDiff,
},

"tags": tagsSchema(),

"synthetic_monitor_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

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

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

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

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

appInsightsName := id.Path["components"]

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

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

location := azureRMNormalizeLocation(d.Get("location").(string))
kind := d.Get("kind").(string)
description := d.Get("description").(string)
frequency := int32(d.Get("frequency").(int))
timeout := int32(d.Get("timeout").(int))
isEnabled := d.Get("enabled").(bool)
retryEnabled := d.Get("retry_enabled").(bool)
geoLocationsRaw := d.Get("geo_locations").([]interface{})
geoLocations := expandApplicationInsightsWebTestGeoLocations(geoLocationsRaw)
testConf := d.Get("test_configuration").(string)

tags := d.Get("tags").(map[string]interface{})
tagKey := fmt.Sprintf("hidden-link:/subscriptions/%s/resourceGroups/%s/providers/microsoft.insights/components/%s", client.SubscriptionID, resGroup, appInsightsName)
tags[tagKey] = "Resource"
AndyMoore marked this conversation as resolved.
Show resolved Hide resolved

testConfiguration := insights.WebTestPropertiesConfiguration{
WebTest: &testConf,
}

webTestProperties := insights.WebTestProperties{
SyntheticMonitorID: &name,
WebTestName: &name,
Description: &description,
Enabled: &isEnabled,
Frequency: &frequency,
Timeout: &timeout,
WebTestKind: insights.WebTestKind(kind),
RetryEnabled: &retryEnabled,
Locations: &geoLocations,
Configuration: &testConfiguration,
}

webTest := insights.WebTest{
Name: &name,
Location: &location,
Kind: insights.WebTestKind(kind),
WebTestProperties: &webTestProperties,
Tags: expandTags(tags),
}

resp, err := client.CreateOrUpdate(ctx, resGroup, name, webTest)
if err != nil {
return fmt.Errorf("Error creating Application Insights WebTest %q (Resource Group %q): %+v", name, resGroup, err)
}

d.SetId(*resp.ID)

return resourceArmApplicationInsightsWebTestsRead(d, meta)
}

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

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

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

resGroup := id.ResourceGroup
name := id.Path["webtests"]

resp, err := client.Get(ctx, resGroup, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Application Insights WebTest %q was not found in Resource Group %q - removing from state!", name, resGroup)
d.SetId("")
AndyMoore marked this conversation as resolved.
Show resolved Hide resolved
return nil
}
return fmt.Errorf("Error retrieving Application Insights WebTests %q (Resource Group %q): %+v", name, resGroup, err)
}

appInsightsId := ""
tags := resp.Tags
for i := range tags {
if strings.HasPrefix(i, "hidden-link") {
appInsightsId = strings.Split(i, ":")[1]
}
}
d.Set("application_insights_id", appInsightsId)
d.Set("name", resp.Name)
d.Set("resource_group_name", resGroup)
d.Set("kind", resp.Kind)

if location := resp.Location; location != nil {
d.Set("location", azureRMNormalizeLocation(*location))
}

if props := resp.WebTestProperties; props != nil {
d.Set("synthetic_monitor_id", props.SyntheticMonitorID)
d.Set("description", props.Description)
d.Set("enabled", props.Enabled)
d.Set("frequency", props.Frequency)
d.Set("timeout", props.Timeout)
d.Set("retry_enabled", props.RetryEnabled)
d.Set("configuration", props.Configuration)
AndyMoore marked this conversation as resolved.
Show resolved Hide resolved

if config := props.Configuration; config != nil {
d.Set("test_configuration", config.WebTest)
}

if err := d.Set("geo_locations", flattenApplicationInsightsWebTestGeoLocations(props.Locations)); err != nil {
return fmt.Errorf("Error setting `geo_locations`: %+v", err)
}
}

flattenAndSetTags(d, resp.Tags)

return nil
}

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

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["webtests"]

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

resp, err := client.Delete(ctx, resGroup, name)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
return nil
}
return fmt.Errorf("Error issuing AzureRM delete request for Application Insights WebTest '%s': %+v", name, err)
}

return err
}

func expandApplicationInsightsWebTestGeoLocations(input []interface{}) []insights.WebTestGeolocation {
locations := make([]insights.WebTestGeolocation, 0)

for _, v := range input {
lc := v.(string)
loc := insights.WebTestGeolocation{
Location: &lc,
}
locations = append(locations, loc)
}

return locations
}

func flattenApplicationInsightsWebTestGeoLocations(input *[]insights.WebTestGeolocation) []string {
results := make([]string, 0)
if input == nil {
return results
}

for _, prop := range *input {
if prop.Location != nil {
results = append(results, azureRMNormalizeLocation(*prop.Location))
}

}

return results
}
Loading