From 73b0c47615e2220211e2d8e53e8df78ef546006d Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 13 May 2019 18:19:39 -0700 Subject: [PATCH 01/74] WIP: Initial checkin --- azurerm/config.go | 11 ++ azurerm/helpers/azure/frontdoor.go | 16 ++ azurerm/resource_arm_front_door.go | 189 ++++++++++++++++++++++++ azurerm/resource_arm_front_door_test.go | 60 ++++++++ website/docs/r/front_door.html.markdown | 60 ++++++++ 5 files changed, 336 insertions(+) create mode 100644 azurerm/helpers/azure/frontdoor.go create mode 100644 azurerm/resource_arm_front_door.go create mode 100644 azurerm/resource_arm_front_door_test.go create mode 100644 website/docs/r/front_door.html.markdown diff --git a/azurerm/config.go b/azurerm/config.go index 55373e0aa9b2..2e9566aebb6a 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -28,6 +28,7 @@ import ( storeAccount "github.com/Azure/azure-sdk-for-go/services/datalake/store/mgmt/2016-11-01/account" "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2016-05-15/dtl" "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" keyVault "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault" "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2018-02-14/keyvault" @@ -249,6 +250,9 @@ type ArmClient struct { // Databricks databricksWorkspacesClient databricks.WorkspacesClient + // Frontdoor + frontdoorClient frontdoor.FrontDoorsClient + // HDInsight hdinsightApplicationsClient hdinsight.ApplicationsClient hdinsightClustersClient hdinsight.ClustersClient @@ -508,6 +512,7 @@ func getArmClient(c *authentication.Config, skipProviderRegistration bool, partn client.registerDNSClients(endpoint, c.SubscriptionID, auth) client.registerEventGridClients(endpoint, c.SubscriptionID, auth) client.registerEventHubClients(endpoint, c.SubscriptionID, auth) + client.registerFrontdoorInstanceClients(endpoint, c.SubscriptionID, auth) client.registerHDInsightsClients(endpoint, c.SubscriptionID, auth) client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth) client.registerLogicClients(endpoint, c.SubscriptionID, auth) @@ -1031,6 +1036,12 @@ func (c *ArmClient) registerEventHubClients(endpoint, subscriptionId string, aut c.eventHubNamespacesClient = ehnc } +func (c *ArmClient) registerFrontdoorInstanceClients(endpoint, subscriptionId string, auth autorest.Authorizer) { + fdc := frontdoor.NewFrontDoorsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&fdc.Client, auth) + c.frontdoorClient = fdc +} + func (c *ArmClient) registerHDInsightsClients(endpoint, subscriptionId string, auth autorest.Authorizer) { applicationsClient := hdinsight.NewApplicationsClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&applicationsClient.Client, auth) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go new file mode 100644 index 000000000000..a863e53b0a30 --- /dev/null +++ b/azurerm/helpers/azure/frontdoor.go @@ -0,0 +1,16 @@ +package azure + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" +) + +//Frontdoor name must begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens. +func ValidateFrontDoorName(i interface{}, k string) (_ []string, errors []error) { + if m, regexErrs := validate.RegExHelper(i, k, `^[\da-zA-Z]([-\da-z]{4,61})[\da-zA-Z]?$`); !m { + errors = append(regexErrs, fmt.Errorf(`%q must begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) + } + + return nil, errors +} diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go new file mode 100644 index 000000000000..15ca4947f02f --- /dev/null +++ b/azurerm/resource_arm_front_door.go @@ -0,0 +1,189 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmFrontDoor() *schema.Resource { + return &schema.Resource{ + Create: resourceArmFrontDoorCreateUpdate, + Read: resourceArmFrontDoorRead, + Update: resourceArmFrontDoorCreateUpdate, + Delete: resourceArmFrontDoorDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateFrontDoorName, + }, + + "location": locationSchema(), + + "resource_group_name": resourceGroupNameSchema(), + + "enabled_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.EnabledStateEnabled), + string(frontdoor.EnabledStateDisabled), + }, false), + Default: string(frontdoor.Enabled), + }, + + "enforce_certificate_name_check": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.EnforceCertificateNameCheckEnabledStateEnabled), + string(frontdoor.EnforceCertificateNameCheckEnabledStateDisabled), + }, false), + }, + + "friendly_name": { + Type: schema.TypeString, + Optional: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontdoorClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) + + if requireResourcesToBeImported { + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Error checking for present of existing Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + if !utils.ResponseWasNotFound(resp.Response) { + return tf.ImportAsExistsError("azurerm_front_door", *resp.ID) + } + } + + location := azureRMNormalizeLocation(d.Get("location").(string)) + enabledState := d.Get("enabled_state").(string) + enforceCertificateNameCheck := d.Get("enforce_certificate_name_check").(string) + friendlyName := d.Get("friendly_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + parameters := frontdoor.FrontDoor{ + Location: utils.String(location), + Properties: &frontdoor.Properties{ + BackendPoolsSettings: &frontdoor.BackendPoolsSettings{ + EnforceCertificateNameCheck: frontdoor.EnforceCertificateNameCheckEnabledState(enforceCertificateNameCheck), + }, + EnabledState: frontdoor.EnabledState(enabledState), + FriendlyName: utils.String(friendlyName), + }, + Tags: expandTags(tags), + } + + future, err := client.CreateOrUpdate(ctx, resourceGroup, name, parameters) + if err != nil { + return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Error waiting for creation of Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + return fmt.Errorf("Error retrieving Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + if resp.ID == nil { + return fmt.Errorf("Cannot read Front Door %q (Resource Group %q) ID", name, resourceGroup) + } + d.SetId(*resp.ID) + + return resourceArmFrontDoorRead(d, meta) +} + +func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontdoorClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + name := id.Path["frontDoors"] + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] Front Door %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("Error reading Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resourceGroup) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + if properties := resp.Properties; properties != nil { + d.Set("enabled_state", string(properties.EnabledState)) + if backendPoolsSettings := properties.BackendPoolsSettings; backendPoolsSettings != nil { + d.Set("enforce_certificate_name_check", string(backendPoolsSettings.EnforceCertificateNameCheck)) + } + d.Set("friendly_name", properties.FriendlyName) + } + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontdoorClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + name := id.Path["frontDoors"] + + future, err := client.Delete(ctx, resourceGroup, name) + if err != nil { + if response.WasNotFound(future.Response()) { + return nil + } + return fmt.Errorf("Error deleting Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + if !response.WasNotFound(future.Response()) { + return fmt.Errorf("Error waiting for deleting Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + + return nil +} diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go new file mode 100644 index 000000000000..7b63d6d729c7 --- /dev/null +++ b/azurerm/resource_arm_front_door_test.go @@ -0,0 +1,60 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + + +func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Front Door not found: %s", resourceName) + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + client := testAccProvider.Meta().(*ArmClient).frontdoorClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) + } + return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) + } + + return nil + } +} + +func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*ArmClient).frontdoorClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_front_door" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) + } + } + + return nil + } + + return nil +} diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown new file mode 100644 index 000000000000..1ffb460caefe --- /dev/null +++ b/website/docs/r/front_door.html.markdown @@ -0,0 +1,60 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_front_door" +sidebar_current: "docs-azurerm-resource-front-door" +description: |- + Managed a Front Door on Azure. +--- + +# azurerm_front_door + +Managed a Front Door on Azure. + + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-rg" + location = "West US" +} + +resource "azurerm_frontdoor" "example" { + name = "example-frontdoor" + resource_group_name = "${azurerm_resource_group.example.name}" + location = "${azurerm_resource_group.example.location}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Name of the Front Door which is globally unique. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group in which to create the Batch Account. Changing this forces a new resource to be created. + +* `location` - (Required) Resource location. Changing this forces a new resource to be created. + +* `enabled_state` - (Optional) Operational status of the Front Door load balancer. Defaults to `Enabled`. + +* `enforce_certificate_name_check` - (Optional) Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests. + +* `friendly_name` - (Optional) A friendly name for the frontDoor. + +* `tags` - (Optional) Resource tags. + +## Attributes Reference + +The following attributes are exported: + +* `id` - Resource ID. + + +## Import + +Front Door can be imported using the `resource id`, e.g. + +```shell +$ terraform import azurerm_front_door.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Network/frontDoors/example-frontdoor +``` From 7b2be6d4e1e5f66b3771057a03e14f0516f44498 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 17 May 2019 17:29:43 -0700 Subject: [PATCH 02/74] Updates to Frontdoor --- azurerm/provider.go | 1 + azurerm/resource_arm_front_door.go | 5 + azurerm/resource_arm_front_door_test.go | 125 +- go.mod | 8 +- .../mgmt/2019-04-01/frontdoor/backendpools.go | 457 ++ .../mgmt/2019-04-01/frontdoor/client.go | 216 + .../mgmt/2019-04-01/frontdoor/endpoints.go | 137 + .../mgmt/2019-04-01/frontdoor/frontdoors.go | 637 +++ .../2019-04-01/frontdoor/frontendendpoints.go | 648 +++ .../frontdoor/healthprobesettings.go | 457 ++ .../frontdoor/loadbalancingsettings.go | 457 ++ .../2019-04-01/frontdoor/managedrulesets.go | 151 + .../mgmt/2019-04-01/frontdoor/models.go | 3832 +++++++++++++++++ .../mgmt/2019-04-01/frontdoor/policies.go | 433 ++ .../mgmt/2019-04-01/frontdoor/routingrules.go | 457 ++ .../mgmt/2019-04-01/frontdoor/version.go | 30 + 16 files changed, 8005 insertions(+), 46 deletions(-) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/backendpools.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/endpoints.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontdoors.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontendendpoints.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/healthprobesettings.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/loadbalancingsettings.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/managedrulesets.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/policies.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/routingrules.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/version.go diff --git a/azurerm/provider.go b/azurerm/provider.go index 8c839777bd8b..fa50b40ab965 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -280,6 +280,7 @@ func Provider() terraform.ResourceProvider { "azurerm_firewall_nat_rule_collection": resourceArmFirewallNatRuleCollection(), "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), "azurerm_firewall": resourceArmFirewall(), + "azurerm_frontdoor": resourceArmFrontDoor(), "azurerm_function_app": resourceArmFunctionApp(), "azurerm_hdinsight_hadoop_cluster": resourceArmHDInsightHadoopCluster(), "azurerm_hdinsight_hbase_cluster": resourceArmHDInsightHBaseCluster(), diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 15ca4947f02f..476371ae01f3 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -93,6 +93,11 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) parameters := frontdoor.FrontDoor{ Location: utils.String(location), Properties: &frontdoor.Properties{ + RoutingRules: &[]frontdoor.RoutingRule{}, + LoadBalancingSettings: &[]frontdoor.LoadBalancingSettingsModel{}, + HealthProbeSettings: &[]frontdoor.HealthProbeSettingsModel{}, + BackendPools: &[]frontdoor.BackendPool{}, + FrontendEndpoints: &[]frontdoor.FrontendEndpoint{}, BackendPoolsSettings: &frontdoor.BackendPoolsSettings{ EnforceCertificateNameCheck: frontdoor.EnforceCertificateNameCheckEnabledState(enforceCertificateNameCheck), }, diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 7b63d6d729c7..aee64e527ece 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -1,60 +1,99 @@ package azurerm import ( - "fmt" - "testing" + "fmt" + "testing" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) +func TestAccAzureRMFrontdoor_basic(t *testing.T) { + resourceName := "azurerm_frontdoor.test" + ri := tf.AccRandTimeInt() + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMFrontDoorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMFrontdoor_basic(ri, testLocation()), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Front Door not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - client := testAccProvider.Meta().(*ArmClient).frontdoorClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext - - if resp, err := client.Get(ctx, resourceGroup, name); err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) - } - return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) - } - - return nil - } + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Front Door not found: %s", resourceName) + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + client := testAccProvider.Meta().(*ArmClient).frontdoorClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) + } + return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) + } + + return nil + } } func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).frontdoorClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext + client := testAccProvider.Meta().(*ArmClient).frontdoorClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_front_door" { - continue - } + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_front_door" { + continue + } - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] - if resp, err := client.Get(ctx, resourceGroup, name); err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) - } - } + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) + } + } - return nil - } + return nil + } - return nil + return nil +} + +func testAccAzureRMFrontdoor_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_frontdoor" "test" { + name = "acctest-frontdoor" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + enabled_state = "Enabled" +} +`, rInt, location) } diff --git a/go.mod b/go.mod index 4225209124e9..b15601c0146f 100644 --- a/go.mod +++ b/go.mod @@ -11,10 +11,12 @@ require ( github.com/hashicorp/go-getter v1.1.0 github.com/hashicorp/go-multierror v1.0.0 github.com/hashicorp/go-uuid v1.0.1 + github.com/hashicorp/go-version v1.1.0 github.com/hashicorp/terraform v0.12.0-alpha4.0.20190424121927-9327eedb0417 + github.com/katbyte/tctest v0.0.0-20190516150427-12a4ac6363f8 // indirect github.com/satori/go.uuid v1.2.0 github.com/satori/uuid v0.0.0-20160927100844-b061729afc07 - golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 - golang.org/x/net v0.0.0-20190311183353-d8887717615a + golang.org/x/crypto v0.0.0-20190506204251-e1dfcc566284 + golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 gopkg.in/yaml.v2 v2.2.2 -) +) \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/backendpools.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/backendpools.go new file mode 100644 index 000000000000..f03bd1d7e6ad --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/backendpools.go @@ -0,0 +1,457 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// BackendPoolsClient is the frontDoor Client +type BackendPoolsClient struct { + BaseClient +} + +// NewBackendPoolsClient creates an instance of the BackendPoolsClient client. +func NewBackendPoolsClient(subscriptionID string) BackendPoolsClient { + return NewBackendPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBackendPoolsClientWithBaseURI creates an instance of the BackendPoolsClient client. +func NewBackendPoolsClientWithBaseURI(baseURI string, subscriptionID string) BackendPoolsClient { + return BackendPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new Backend Pool with the specified Pool name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// backendPoolName - name of the Backend Pool which is unique within the Front Door. +// backendPoolParameters - backend Pool properties needed to create a new Pool. +func (client BackendPoolsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, frontDoorName string, backendPoolName string, backendPoolParameters BackendPool) (result BackendPoolsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: backendPoolName, + Constraints: []validation.Constraint{{Target: "backendPoolName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "backendPoolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "backendPoolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.BackendPoolsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, frontDoorName, backendPoolName, backendPoolParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client BackendPoolsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, backendPoolName string, backendPoolParameters BackendPool) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "backendPoolName": autorest.Encode("path", backendPoolName), + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + backendPoolParameters.Type = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/backendPools/{backendPoolName}", pathParameters), + autorest.WithJSON(backendPoolParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client BackendPoolsClient) CreateOrUpdateSender(req *http.Request) (future BackendPoolsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client BackendPoolsClient) CreateOrUpdateResponder(resp *http.Response) (result BackendPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing Backend Pool with the specified parameters. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// backendPoolName - name of the Backend Pool which is unique within the Front Door. +func (client BackendPoolsClient) Delete(ctx context.Context, resourceGroupName string, frontDoorName string, backendPoolName string) (result BackendPoolsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: backendPoolName, + Constraints: []validation.Constraint{{Target: "backendPoolName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "backendPoolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "backendPoolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.BackendPoolsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, frontDoorName, backendPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client BackendPoolsClient) DeletePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, backendPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "backendPoolName": autorest.Encode("path", backendPoolName), + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/backendPools/{backendPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client BackendPoolsClient) DeleteSender(req *http.Request) (future BackendPoolsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client BackendPoolsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Backend Pool with the specified Pool name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// backendPoolName - name of the Backend Pool which is unique within the Front Door. +func (client BackendPoolsClient) Get(ctx context.Context, resourceGroupName string, frontDoorName string, backendPoolName string) (result BackendPool, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: backendPoolName, + Constraints: []validation.Constraint{{Target: "backendPoolName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "backendPoolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "backendPoolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.BackendPoolsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, frontDoorName, backendPoolName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client BackendPoolsClient) GetPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, backendPoolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "backendPoolName": autorest.Encode("path", backendPoolName), + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/backendPools/{backendPoolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client BackendPoolsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client BackendPoolsClient) GetResponder(resp *http.Response) (result BackendPool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByFrontDoor lists all of the Backend Pools within a Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client BackendPoolsClient) ListByFrontDoor(ctx context.Context, resourceGroupName string, frontDoorName string) (result BackendPoolListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.bplr.Response.Response != nil { + sc = result.bplr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.BackendPoolsClient", "ListByFrontDoor", err.Error()) + } + + result.fn = client.listByFrontDoorNextResults + req, err := client.ListByFrontDoorPreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "ListByFrontDoor", nil, "Failure preparing request") + return + } + + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.bplr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "ListByFrontDoor", resp, "Failure sending request") + return + } + + result.bplr, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "ListByFrontDoor", resp, "Failure responding to request") + } + + return +} + +// ListByFrontDoorPreparer prepares the ListByFrontDoor request. +func (client BackendPoolsClient) ListByFrontDoorPreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/backendPools", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByFrontDoorSender sends the ListByFrontDoor request. The method will close the +// http.Response Body if it receives an error. +func (client BackendPoolsClient) ListByFrontDoorSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByFrontDoorResponder handles the response to the ListByFrontDoor request. The method always +// closes the http.Response Body. +func (client BackendPoolsClient) ListByFrontDoorResponder(resp *http.Response) (result BackendPoolListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByFrontDoorNextResults retrieves the next set of results, if any. +func (client BackendPoolsClient) listByFrontDoorNextResults(ctx context.Context, lastResults BackendPoolListResult) (result BackendPoolListResult, err error) { + req, err := lastResults.backendPoolListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "listByFrontDoorNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "listByFrontDoorNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsClient", "listByFrontDoorNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByFrontDoorComplete enumerates all values, automatically crossing page boundaries as required. +func (client BackendPoolsClient) ListByFrontDoorComplete(ctx context.Context, resourceGroupName string, frontDoorName string) (result BackendPoolListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByFrontDoor(ctx, resourceGroupName, frontDoorName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/client.go new file mode 100644 index 000000000000..3e848f7271e7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/client.go @@ -0,0 +1,216 @@ +// Package frontdoor implements the Azure ARM Frontdoor service API version . +// +// FrontDoor Client +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +const ( + // DefaultBaseURI is the default URI used for the service Frontdoor + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Frontdoor. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} + +// CheckFrontDoorNameAvailability check the availability of a Front Door resource name. +// Parameters: +// checkFrontDoorNameAvailabilityInput - input to check. +func (client BaseClient) CheckFrontDoorNameAvailability(ctx context.Context, checkFrontDoorNameAvailabilityInput CheckNameAvailabilityInput) (result CheckNameAvailabilityOutput, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CheckFrontDoorNameAvailability") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: checkFrontDoorNameAvailabilityInput, + Constraints: []validation.Constraint{{Target: "checkFrontDoorNameAvailabilityInput.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.BaseClient", "CheckFrontDoorNameAvailability", err.Error()) + } + + req, err := client.CheckFrontDoorNameAvailabilityPreparer(ctx, checkFrontDoorNameAvailabilityInput) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BaseClient", "CheckFrontDoorNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckFrontDoorNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.BaseClient", "CheckFrontDoorNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckFrontDoorNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BaseClient", "CheckFrontDoorNameAvailability", resp, "Failure responding to request") + } + + return +} + +// CheckFrontDoorNameAvailabilityPreparer prepares the CheckFrontDoorNameAvailability request. +func (client BaseClient) CheckFrontDoorNameAvailabilityPreparer(ctx context.Context, checkFrontDoorNameAvailabilityInput CheckNameAvailabilityInput) (*http.Request, error) { + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.Network/checkFrontDoorNameAvailability"), + autorest.WithJSON(checkFrontDoorNameAvailabilityInput), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckFrontDoorNameAvailabilitySender sends the CheckFrontDoorNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client BaseClient) CheckFrontDoorNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// CheckFrontDoorNameAvailabilityResponder handles the response to the CheckFrontDoorNameAvailability request. The method always +// closes the http.Response Body. +func (client BaseClient) CheckFrontDoorNameAvailabilityResponder(resp *http.Response) (result CheckNameAvailabilityOutput, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CheckFrontDoorNameAvailabilityWithSubscription check the availability of a Front Door subdomain. +// Parameters: +// checkFrontDoorNameAvailabilityInput - input to check. +func (client BaseClient) CheckFrontDoorNameAvailabilityWithSubscription(ctx context.Context, checkFrontDoorNameAvailabilityInput CheckNameAvailabilityInput) (result CheckNameAvailabilityOutput, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CheckFrontDoorNameAvailabilityWithSubscription") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: checkFrontDoorNameAvailabilityInput, + Constraints: []validation.Constraint{{Target: "checkFrontDoorNameAvailabilityInput.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.BaseClient", "CheckFrontDoorNameAvailabilityWithSubscription", err.Error()) + } + + req, err := client.CheckFrontDoorNameAvailabilityWithSubscriptionPreparer(ctx, checkFrontDoorNameAvailabilityInput) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BaseClient", "CheckFrontDoorNameAvailabilityWithSubscription", nil, "Failure preparing request") + return + } + + resp, err := client.CheckFrontDoorNameAvailabilityWithSubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.BaseClient", "CheckFrontDoorNameAvailabilityWithSubscription", resp, "Failure sending request") + return + } + + result, err = client.CheckFrontDoorNameAvailabilityWithSubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BaseClient", "CheckFrontDoorNameAvailabilityWithSubscription", resp, "Failure responding to request") + } + + return +} + +// CheckFrontDoorNameAvailabilityWithSubscriptionPreparer prepares the CheckFrontDoorNameAvailabilityWithSubscription request. +func (client BaseClient) CheckFrontDoorNameAvailabilityWithSubscriptionPreparer(ctx context.Context, checkFrontDoorNameAvailabilityInput CheckNameAvailabilityInput) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/checkFrontDoorNameAvailability", pathParameters), + autorest.WithJSON(checkFrontDoorNameAvailabilityInput), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckFrontDoorNameAvailabilityWithSubscriptionSender sends the CheckFrontDoorNameAvailabilityWithSubscription request. The method will close the +// http.Response Body if it receives an error. +func (client BaseClient) CheckFrontDoorNameAvailabilityWithSubscriptionSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CheckFrontDoorNameAvailabilityWithSubscriptionResponder handles the response to the CheckFrontDoorNameAvailabilityWithSubscription request. The method always +// closes the http.Response Body. +func (client BaseClient) CheckFrontDoorNameAvailabilityWithSubscriptionResponder(resp *http.Response) (result CheckNameAvailabilityOutput, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/endpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/endpoints.go new file mode 100644 index 000000000000..ed2c3cf2769b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/endpoints.go @@ -0,0 +1,137 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// EndpointsClient is the frontDoor Client +type EndpointsClient struct { + BaseClient +} + +// NewEndpointsClient creates an instance of the EndpointsClient client. +func NewEndpointsClient(subscriptionID string) EndpointsClient { + return NewEndpointsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewEndpointsClientWithBaseURI creates an instance of the EndpointsClient client. +func NewEndpointsClientWithBaseURI(baseURI string, subscriptionID string) EndpointsClient { + return EndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// PurgeContent removes a content from Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// contentFilePaths - the path to the content to be purged. Path can be a full URL, e.g. '/pictures/city.png' +// which removes a single file, or a directory with a wildcard, e.g. '/pictures/*' which removes all folders +// and files in the directory. +func (client EndpointsClient) PurgeContent(ctx context.Context, resourceGroupName string, frontDoorName string, contentFilePaths PurgeParameters) (result EndpointsPurgeContentFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EndpointsClient.PurgeContent") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: contentFilePaths, + Constraints: []validation.Constraint{{Target: "contentFilePaths.ContentPaths", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.EndpointsClient", "PurgeContent", err.Error()) + } + + req, err := client.PurgeContentPreparer(ctx, resourceGroupName, frontDoorName, contentFilePaths) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.EndpointsClient", "PurgeContent", nil, "Failure preparing request") + return + } + + result, err = client.PurgeContentSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.EndpointsClient", "PurgeContent", result.Response(), "Failure sending request") + return + } + + return +} + +// PurgeContentPreparer prepares the PurgeContent request. +func (client EndpointsClient) PurgeContentPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, contentFilePaths PurgeParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/purge", pathParameters), + autorest.WithJSON(contentFilePaths), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// PurgeContentSender sends the PurgeContent request. The method will close the +// http.Response Body if it receives an error. +func (client EndpointsClient) PurgeContentSender(req *http.Request) (future EndpointsPurgeContentFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// PurgeContentResponder handles the response to the PurgeContent request. The method always +// closes the http.Response Body. +func (client EndpointsClient) PurgeContentResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontdoors.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontdoors.go new file mode 100644 index 000000000000..3e9f2ff38a4f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontdoors.go @@ -0,0 +1,637 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// FrontDoorsClient is the frontDoor Client +type FrontDoorsClient struct { + BaseClient +} + +// NewFrontDoorsClient creates an instance of the FrontDoorsClient client. +func NewFrontDoorsClient(subscriptionID string) FrontDoorsClient { + return NewFrontDoorsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewFrontDoorsClientWithBaseURI creates an instance of the FrontDoorsClient client. +func NewFrontDoorsClientWithBaseURI(baseURI string, subscriptionID string) FrontDoorsClient { + return FrontDoorsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new Front Door with a Front Door name under the specified subscription and resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// frontDoorParameters - front Door properties needed to create a new Front Door. +func (client FrontDoorsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, frontDoorName string, frontDoorParameters FrontDoor) (result FrontDoorsCreateOrUpdateFutureType, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontDoorsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, frontDoorName, frontDoorParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client FrontDoorsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, frontDoorParameters FrontDoor) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}", pathParameters), + autorest.WithJSON(frontDoorParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client FrontDoorsClient) CreateOrUpdateSender(req *http.Request) (future FrontDoorsCreateOrUpdateFutureType, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client FrontDoorsClient) CreateOrUpdateResponder(resp *http.Response) (result FrontDoor, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing Front Door with the specified parameters. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client FrontDoorsClient) Delete(ctx context.Context, resourceGroupName string, frontDoorName string) (result FrontDoorsDeleteFutureType, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontDoorsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client FrontDoorsClient) DeletePreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client FrontDoorsClient) DeleteSender(req *http.Request) (future FrontDoorsDeleteFutureType, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client FrontDoorsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Front Door with the specified Front Door name under the specified subscription and resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client FrontDoorsClient) Get(ctx context.Context, resourceGroupName string, frontDoorName string) (result FrontDoor, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontDoorsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client FrontDoorsClient) GetPreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client FrontDoorsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client FrontDoorsClient) GetResponder(resp *http.Response) (result FrontDoor, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all of the Front Doors within an Azure subscription. +func (client FrontDoorsClient) List(ctx context.Context) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.List") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.lr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "List", resp, "Failure sending request") + return + } + + result.lr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client FrontDoorsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/frontDoors", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client FrontDoorsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client FrontDoorsClient) ListResponder(resp *http.Response) (result ListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client FrontDoorsClient) listNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client FrontDoorsClient) ListComplete(ctx context.Context) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} + +// ListByResourceGroup lists all of the Front Doors within a resource group under a subscription. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +func (client FrontDoorsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontDoorsClient", "ListByResourceGroup", err.Error()) + } + + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.lr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.lr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client FrontDoorsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client FrontDoorsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client FrontDoorsClient) ListByResourceGroupResponder(resp *http.Response) (result ListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client FrontDoorsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client FrontDoorsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) + return +} + +// ValidateCustomDomain validates the custom domain mapping to ensure it maps to the correct Front Door endpoint in +// DNS. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// customDomainProperties - custom domain to be validated. +func (client FrontDoorsClient) ValidateCustomDomain(ctx context.Context, resourceGroupName string, frontDoorName string, customDomainProperties ValidateCustomDomainInput) (result ValidateCustomDomainOutput, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontDoorsClient.ValidateCustomDomain") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: customDomainProperties, + Constraints: []validation.Constraint{{Target: "customDomainProperties.HostName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontDoorsClient", "ValidateCustomDomain", err.Error()) + } + + req, err := client.ValidateCustomDomainPreparer(ctx, resourceGroupName, frontDoorName, customDomainProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "ValidateCustomDomain", nil, "Failure preparing request") + return + } + + resp, err := client.ValidateCustomDomainSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "ValidateCustomDomain", resp, "Failure sending request") + return + } + + result, err = client.ValidateCustomDomainResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsClient", "ValidateCustomDomain", resp, "Failure responding to request") + } + + return +} + +// ValidateCustomDomainPreparer prepares the ValidateCustomDomain request. +func (client FrontDoorsClient) ValidateCustomDomainPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, customDomainProperties ValidateCustomDomainInput) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/validateCustomDomain", pathParameters), + autorest.WithJSON(customDomainProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ValidateCustomDomainSender sends the ValidateCustomDomain request. The method will close the +// http.Response Body if it receives an error. +func (client FrontDoorsClient) ValidateCustomDomainSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ValidateCustomDomainResponder handles the response to the ValidateCustomDomain request. The method always +// closes the http.Response Body. +func (client FrontDoorsClient) ValidateCustomDomainResponder(resp *http.Response) (result ValidateCustomDomainOutput, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontendendpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontendendpoints.go new file mode 100644 index 000000000000..a16008aa8be0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/frontendendpoints.go @@ -0,0 +1,648 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// FrontendEndpointsClient is the frontDoor Client +type FrontendEndpointsClient struct { + BaseClient +} + +// NewFrontendEndpointsClient creates an instance of the FrontendEndpointsClient client. +func NewFrontendEndpointsClient(subscriptionID string) FrontendEndpointsClient { + return NewFrontendEndpointsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewFrontendEndpointsClientWithBaseURI creates an instance of the FrontendEndpointsClient client. +func NewFrontendEndpointsClientWithBaseURI(baseURI string, subscriptionID string) FrontendEndpointsClient { + return FrontendEndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new frontend endpoint with the specified host name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. +// frontendEndpointParameters - frontend endpoint properties needed to create a new endpoint. +func (client FrontendEndpointsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string, frontendEndpointParameters FrontendEndpoint) (result FrontendEndpointsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: frontendEndpointName, + Constraints: []validation.Constraint{{Target: "frontendEndpointName", Name: validation.MaxLength, Rule: 255, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontendEndpointsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, frontDoorName, frontendEndpointName, frontendEndpointParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client FrontendEndpointsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string, frontendEndpointParameters FrontendEndpoint) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "frontendEndpointName": autorest.Encode("path", frontendEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + frontendEndpointParameters.Type = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/frontendEndpoints/{frontendEndpointName}", pathParameters), + autorest.WithJSON(frontendEndpointParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client FrontendEndpointsClient) CreateOrUpdateSender(req *http.Request) (future FrontendEndpointsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client FrontendEndpointsClient) CreateOrUpdateResponder(resp *http.Response) (result FrontendEndpoint, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing frontend endpoint with the specified parameters. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. +func (client FrontendEndpointsClient) Delete(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string) (result FrontendEndpointsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: frontendEndpointName, + Constraints: []validation.Constraint{{Target: "frontendEndpointName", Name: validation.MaxLength, Rule: 255, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontendEndpointsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, frontDoorName, frontendEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client FrontendEndpointsClient) DeletePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "frontendEndpointName": autorest.Encode("path", frontendEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/frontendEndpoints/{frontendEndpointName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client FrontendEndpointsClient) DeleteSender(req *http.Request) (future FrontendEndpointsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client FrontendEndpointsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DisableHTTPS disables a frontendEndpoint for HTTPS traffic +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. +func (client FrontendEndpointsClient) DisableHTTPS(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string) (result FrontendEndpointsDisableHTTPSFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.DisableHTTPS") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: frontendEndpointName, + Constraints: []validation.Constraint{{Target: "frontendEndpointName", Name: validation.MaxLength, Rule: 255, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontendEndpointsClient", "DisableHTTPS", err.Error()) + } + + req, err := client.DisableHTTPSPreparer(ctx, resourceGroupName, frontDoorName, frontendEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "DisableHTTPS", nil, "Failure preparing request") + return + } + + result, err = client.DisableHTTPSSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "DisableHTTPS", result.Response(), "Failure sending request") + return + } + + return +} + +// DisableHTTPSPreparer prepares the DisableHTTPS request. +func (client FrontendEndpointsClient) DisableHTTPSPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "frontendEndpointName": autorest.Encode("path", frontendEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/frontendEndpoints/{frontendEndpointName}/disableHttps", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DisableHTTPSSender sends the DisableHTTPS request. The method will close the +// http.Response Body if it receives an error. +func (client FrontendEndpointsClient) DisableHTTPSSender(req *http.Request) (future FrontendEndpointsDisableHTTPSFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DisableHTTPSResponder handles the response to the DisableHTTPS request. The method always +// closes the http.Response Body. +func (client FrontendEndpointsClient) DisableHTTPSResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// EnableHTTPS enables a frontendEndpoint for HTTPS traffic +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. +// customHTTPSConfiguration - the configuration specifying how to enable HTTPS +func (client FrontendEndpointsClient) EnableHTTPS(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string, customHTTPSConfiguration CustomHTTPSConfiguration) (result FrontendEndpointsEnableHTTPSFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.EnableHTTPS") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: frontendEndpointName, + Constraints: []validation.Constraint{{Target: "frontendEndpointName", Name: validation.MaxLength, Rule: 255, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontendEndpointsClient", "EnableHTTPS", err.Error()) + } + + req, err := client.EnableHTTPSPreparer(ctx, resourceGroupName, frontDoorName, frontendEndpointName, customHTTPSConfiguration) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "EnableHTTPS", nil, "Failure preparing request") + return + } + + result, err = client.EnableHTTPSSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "EnableHTTPS", result.Response(), "Failure sending request") + return + } + + return +} + +// EnableHTTPSPreparer prepares the EnableHTTPS request. +func (client FrontendEndpointsClient) EnableHTTPSPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string, customHTTPSConfiguration CustomHTTPSConfiguration) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "frontendEndpointName": autorest.Encode("path", frontendEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/frontendEndpoints/{frontendEndpointName}/enableHttps", pathParameters), + autorest.WithJSON(customHTTPSConfiguration), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// EnableHTTPSSender sends the EnableHTTPS request. The method will close the +// http.Response Body if it receives an error. +func (client FrontendEndpointsClient) EnableHTTPSSender(req *http.Request) (future FrontendEndpointsEnableHTTPSFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// EnableHTTPSResponder handles the response to the EnableHTTPS request. The method always +// closes the http.Response Body. +func (client FrontendEndpointsClient) EnableHTTPSResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Frontend endpoint with the specified name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. +func (client FrontendEndpointsClient) Get(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string) (result FrontendEndpoint, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: frontendEndpointName, + Constraints: []validation.Constraint{{Target: "frontendEndpointName", Name: validation.MaxLength, Rule: 255, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "frontendEndpointName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontendEndpointsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, frontDoorName, frontendEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client FrontendEndpointsClient) GetPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, frontendEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "frontendEndpointName": autorest.Encode("path", frontendEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/frontendEndpoints/{frontendEndpointName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client FrontendEndpointsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client FrontendEndpointsClient) GetResponder(resp *http.Response) (result FrontendEndpoint, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByFrontDoor lists all of the frontend endpoints within a Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client FrontendEndpointsClient) ListByFrontDoor(ctx context.Context, resourceGroupName string, frontDoorName string) (result FrontendEndpointsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.felr.Response.Response != nil { + sc = result.felr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.FrontendEndpointsClient", "ListByFrontDoor", err.Error()) + } + + result.fn = client.listByFrontDoorNextResults + req, err := client.ListByFrontDoorPreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "ListByFrontDoor", nil, "Failure preparing request") + return + } + + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.felr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "ListByFrontDoor", resp, "Failure sending request") + return + } + + result.felr, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "ListByFrontDoor", resp, "Failure responding to request") + } + + return +} + +// ListByFrontDoorPreparer prepares the ListByFrontDoor request. +func (client FrontendEndpointsClient) ListByFrontDoorPreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/frontendEndpoints", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByFrontDoorSender sends the ListByFrontDoor request. The method will close the +// http.Response Body if it receives an error. +func (client FrontendEndpointsClient) ListByFrontDoorSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByFrontDoorResponder handles the response to the ListByFrontDoor request. The method always +// closes the http.Response Body. +func (client FrontendEndpointsClient) ListByFrontDoorResponder(resp *http.Response) (result FrontendEndpointsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByFrontDoorNextResults retrieves the next set of results, if any. +func (client FrontendEndpointsClient) listByFrontDoorNextResults(ctx context.Context, lastResults FrontendEndpointsListResult) (result FrontendEndpointsListResult, err error) { + req, err := lastResults.frontendEndpointsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "listByFrontDoorNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "listByFrontDoorNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsClient", "listByFrontDoorNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByFrontDoorComplete enumerates all values, automatically crossing page boundaries as required. +func (client FrontendEndpointsClient) ListByFrontDoorComplete(ctx context.Context, resourceGroupName string, frontDoorName string) (result FrontendEndpointsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByFrontDoor(ctx, resourceGroupName, frontDoorName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/healthprobesettings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/healthprobesettings.go new file mode 100644 index 000000000000..fdeb269b0845 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/healthprobesettings.go @@ -0,0 +1,457 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// HealthProbeSettingsClient is the frontDoor Client +type HealthProbeSettingsClient struct { + BaseClient +} + +// NewHealthProbeSettingsClient creates an instance of the HealthProbeSettingsClient client. +func NewHealthProbeSettingsClient(subscriptionID string) HealthProbeSettingsClient { + return NewHealthProbeSettingsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewHealthProbeSettingsClientWithBaseURI creates an instance of the HealthProbeSettingsClient client. +func NewHealthProbeSettingsClientWithBaseURI(baseURI string, subscriptionID string) HealthProbeSettingsClient { + return HealthProbeSettingsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new HealthProbeSettings with the specified Rule name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// healthProbeSettingsName - name of the health probe settings which is unique within the Front Door. +// healthProbeSettingsParameters - healthProbeSettings properties needed to create a new Front Door. +func (client HealthProbeSettingsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, frontDoorName string, healthProbeSettingsName string, healthProbeSettingsParameters HealthProbeSettingsModel) (result HealthProbeSettingsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: healthProbeSettingsName, + Constraints: []validation.Constraint{{Target: "healthProbeSettingsName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "healthProbeSettingsName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "healthProbeSettingsName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.HealthProbeSettingsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, frontDoorName, healthProbeSettingsName, healthProbeSettingsParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client HealthProbeSettingsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, healthProbeSettingsName string, healthProbeSettingsParameters HealthProbeSettingsModel) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "healthProbeSettingsName": autorest.Encode("path", healthProbeSettingsName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + healthProbeSettingsParameters.Type = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/healthProbeSettings/{healthProbeSettingsName}", pathParameters), + autorest.WithJSON(healthProbeSettingsParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client HealthProbeSettingsClient) CreateOrUpdateSender(req *http.Request) (future HealthProbeSettingsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client HealthProbeSettingsClient) CreateOrUpdateResponder(resp *http.Response) (result HealthProbeSettingsModel, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing HealthProbeSettings with the specified parameters. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// healthProbeSettingsName - name of the health probe settings which is unique within the Front Door. +func (client HealthProbeSettingsClient) Delete(ctx context.Context, resourceGroupName string, frontDoorName string, healthProbeSettingsName string) (result HealthProbeSettingsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: healthProbeSettingsName, + Constraints: []validation.Constraint{{Target: "healthProbeSettingsName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "healthProbeSettingsName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "healthProbeSettingsName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.HealthProbeSettingsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, frontDoorName, healthProbeSettingsName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client HealthProbeSettingsClient) DeletePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, healthProbeSettingsName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "healthProbeSettingsName": autorest.Encode("path", healthProbeSettingsName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/healthProbeSettings/{healthProbeSettingsName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client HealthProbeSettingsClient) DeleteSender(req *http.Request) (future HealthProbeSettingsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client HealthProbeSettingsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a HealthProbeSettings with the specified Rule name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// healthProbeSettingsName - name of the health probe settings which is unique within the Front Door. +func (client HealthProbeSettingsClient) Get(ctx context.Context, resourceGroupName string, frontDoorName string, healthProbeSettingsName string) (result HealthProbeSettingsModel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: healthProbeSettingsName, + Constraints: []validation.Constraint{{Target: "healthProbeSettingsName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "healthProbeSettingsName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "healthProbeSettingsName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.HealthProbeSettingsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, frontDoorName, healthProbeSettingsName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client HealthProbeSettingsClient) GetPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, healthProbeSettingsName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "healthProbeSettingsName": autorest.Encode("path", healthProbeSettingsName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/healthProbeSettings/{healthProbeSettingsName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client HealthProbeSettingsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client HealthProbeSettingsClient) GetResponder(resp *http.Response) (result HealthProbeSettingsModel, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByFrontDoor lists all of the HealthProbeSettings within a Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client HealthProbeSettingsClient) ListByFrontDoor(ctx context.Context, resourceGroupName string, frontDoorName string) (result HealthProbeSettingsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.hpslr.Response.Response != nil { + sc = result.hpslr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.HealthProbeSettingsClient", "ListByFrontDoor", err.Error()) + } + + result.fn = client.listByFrontDoorNextResults + req, err := client.ListByFrontDoorPreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "ListByFrontDoor", nil, "Failure preparing request") + return + } + + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.hpslr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "ListByFrontDoor", resp, "Failure sending request") + return + } + + result.hpslr, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "ListByFrontDoor", resp, "Failure responding to request") + } + + return +} + +// ListByFrontDoorPreparer prepares the ListByFrontDoor request. +func (client HealthProbeSettingsClient) ListByFrontDoorPreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/healthProbeSettings", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByFrontDoorSender sends the ListByFrontDoor request. The method will close the +// http.Response Body if it receives an error. +func (client HealthProbeSettingsClient) ListByFrontDoorSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByFrontDoorResponder handles the response to the ListByFrontDoor request. The method always +// closes the http.Response Body. +func (client HealthProbeSettingsClient) ListByFrontDoorResponder(resp *http.Response) (result HealthProbeSettingsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByFrontDoorNextResults retrieves the next set of results, if any. +func (client HealthProbeSettingsClient) listByFrontDoorNextResults(ctx context.Context, lastResults HealthProbeSettingsListResult) (result HealthProbeSettingsListResult, err error) { + req, err := lastResults.healthProbeSettingsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "listByFrontDoorNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "listByFrontDoorNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsClient", "listByFrontDoorNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByFrontDoorComplete enumerates all values, automatically crossing page boundaries as required. +func (client HealthProbeSettingsClient) ListByFrontDoorComplete(ctx context.Context, resourceGroupName string, frontDoorName string) (result HealthProbeSettingsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByFrontDoor(ctx, resourceGroupName, frontDoorName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/loadbalancingsettings.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/loadbalancingsettings.go new file mode 100644 index 000000000000..2c070dd36def --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/loadbalancingsettings.go @@ -0,0 +1,457 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// LoadBalancingSettingsClient is the frontDoor Client +type LoadBalancingSettingsClient struct { + BaseClient +} + +// NewLoadBalancingSettingsClient creates an instance of the LoadBalancingSettingsClient client. +func NewLoadBalancingSettingsClient(subscriptionID string) LoadBalancingSettingsClient { + return NewLoadBalancingSettingsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewLoadBalancingSettingsClientWithBaseURI creates an instance of the LoadBalancingSettingsClient client. +func NewLoadBalancingSettingsClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancingSettingsClient { + return LoadBalancingSettingsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new LoadBalancingSettings with the specified Rule name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// loadBalancingSettingsName - name of the load balancing settings which is unique within the Front Door. +// loadBalancingSettingsParameters - loadBalancingSettings properties needed to create a new Front Door. +func (client LoadBalancingSettingsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, frontDoorName string, loadBalancingSettingsName string, loadBalancingSettingsParameters LoadBalancingSettingsModel) (result LoadBalancingSettingsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: loadBalancingSettingsName, + Constraints: []validation.Constraint{{Target: "loadBalancingSettingsName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "loadBalancingSettingsName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "loadBalancingSettingsName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.LoadBalancingSettingsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, frontDoorName, loadBalancingSettingsName, loadBalancingSettingsParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client LoadBalancingSettingsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, loadBalancingSettingsName string, loadBalancingSettingsParameters LoadBalancingSettingsModel) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "loadBalancingSettingsName": autorest.Encode("path", loadBalancingSettingsName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + loadBalancingSettingsParameters.Type = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/loadBalancingSettings/{loadBalancingSettingsName}", pathParameters), + autorest.WithJSON(loadBalancingSettingsParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancingSettingsClient) CreateOrUpdateSender(req *http.Request) (future LoadBalancingSettingsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client LoadBalancingSettingsClient) CreateOrUpdateResponder(resp *http.Response) (result LoadBalancingSettingsModel, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing LoadBalancingSettings with the specified parameters. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// loadBalancingSettingsName - name of the load balancing settings which is unique within the Front Door. +func (client LoadBalancingSettingsClient) Delete(ctx context.Context, resourceGroupName string, frontDoorName string, loadBalancingSettingsName string) (result LoadBalancingSettingsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: loadBalancingSettingsName, + Constraints: []validation.Constraint{{Target: "loadBalancingSettingsName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "loadBalancingSettingsName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "loadBalancingSettingsName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.LoadBalancingSettingsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, frontDoorName, loadBalancingSettingsName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client LoadBalancingSettingsClient) DeletePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, loadBalancingSettingsName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "loadBalancingSettingsName": autorest.Encode("path", loadBalancingSettingsName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/loadBalancingSettings/{loadBalancingSettingsName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancingSettingsClient) DeleteSender(req *http.Request) (future LoadBalancingSettingsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client LoadBalancingSettingsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a LoadBalancingSettings with the specified Rule name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// loadBalancingSettingsName - name of the load balancing settings which is unique within the Front Door. +func (client LoadBalancingSettingsClient) Get(ctx context.Context, resourceGroupName string, frontDoorName string, loadBalancingSettingsName string) (result LoadBalancingSettingsModel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: loadBalancingSettingsName, + Constraints: []validation.Constraint{{Target: "loadBalancingSettingsName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "loadBalancingSettingsName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "loadBalancingSettingsName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.LoadBalancingSettingsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, frontDoorName, loadBalancingSettingsName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client LoadBalancingSettingsClient) GetPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, loadBalancingSettingsName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "loadBalancingSettingsName": autorest.Encode("path", loadBalancingSettingsName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/loadBalancingSettings/{loadBalancingSettingsName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancingSettingsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client LoadBalancingSettingsClient) GetResponder(resp *http.Response) (result LoadBalancingSettingsModel, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByFrontDoor lists all of the LoadBalancingSettings within a Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client LoadBalancingSettingsClient) ListByFrontDoor(ctx context.Context, resourceGroupName string, frontDoorName string) (result LoadBalancingSettingsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.lbslr.Response.Response != nil { + sc = result.lbslr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.LoadBalancingSettingsClient", "ListByFrontDoor", err.Error()) + } + + result.fn = client.listByFrontDoorNextResults + req, err := client.ListByFrontDoorPreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "ListByFrontDoor", nil, "Failure preparing request") + return + } + + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.lbslr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "ListByFrontDoor", resp, "Failure sending request") + return + } + + result.lbslr, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "ListByFrontDoor", resp, "Failure responding to request") + } + + return +} + +// ListByFrontDoorPreparer prepares the ListByFrontDoor request. +func (client LoadBalancingSettingsClient) ListByFrontDoorPreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/loadBalancingSettings", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByFrontDoorSender sends the ListByFrontDoor request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancingSettingsClient) ListByFrontDoorSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByFrontDoorResponder handles the response to the ListByFrontDoor request. The method always +// closes the http.Response Body. +func (client LoadBalancingSettingsClient) ListByFrontDoorResponder(resp *http.Response) (result LoadBalancingSettingsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByFrontDoorNextResults retrieves the next set of results, if any. +func (client LoadBalancingSettingsClient) listByFrontDoorNextResults(ctx context.Context, lastResults LoadBalancingSettingsListResult) (result LoadBalancingSettingsListResult, err error) { + req, err := lastResults.loadBalancingSettingsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "listByFrontDoorNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "listByFrontDoorNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsClient", "listByFrontDoorNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByFrontDoorComplete enumerates all values, automatically crossing page boundaries as required. +func (client LoadBalancingSettingsClient) ListByFrontDoorComplete(ctx context.Context, resourceGroupName string, frontDoorName string) (result LoadBalancingSettingsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByFrontDoor(ctx, resourceGroupName, frontDoorName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/managedrulesets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/managedrulesets.go new file mode 100644 index 000000000000..f7c74c4b0cfe --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/managedrulesets.go @@ -0,0 +1,151 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ManagedRuleSetsClient is the frontDoor Client +type ManagedRuleSetsClient struct { + BaseClient +} + +// NewManagedRuleSetsClient creates an instance of the ManagedRuleSetsClient client. +func NewManagedRuleSetsClient(subscriptionID string) ManagedRuleSetsClient { + return NewManagedRuleSetsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewManagedRuleSetsClientWithBaseURI creates an instance of the ManagedRuleSetsClient client. +func NewManagedRuleSetsClientWithBaseURI(baseURI string, subscriptionID string) ManagedRuleSetsClient { + return ManagedRuleSetsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all available managed rule sets. +func (client ManagedRuleSetsClient) List(ctx context.Context) (result ManagedRuleSetDefinitionListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedRuleSetsClient.List") + defer func() { + sc := -1 + if result.mrsdl.Response.Response != nil { + sc = result.mrsdl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.ManagedRuleSetsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.mrsdl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.ManagedRuleSetsClient", "List", resp, "Failure sending request") + return + } + + result.mrsdl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.ManagedRuleSetsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ManagedRuleSetsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/FrontDoorWebApplicationFirewallManagedRuleSets", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ManagedRuleSetsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ManagedRuleSetsClient) ListResponder(resp *http.Response) (result ManagedRuleSetDefinitionList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client ManagedRuleSetsClient) listNextResults(ctx context.Context, lastResults ManagedRuleSetDefinitionList) (result ManagedRuleSetDefinitionList, err error) { + req, err := lastResults.managedRuleSetDefinitionListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.ManagedRuleSetsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.ManagedRuleSetsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.ManagedRuleSetsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ManagedRuleSetsClient) ListComplete(ctx context.Context) (result ManagedRuleSetDefinitionListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedRuleSetsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/models.go new file mode 100644 index 000000000000..e9d82a887493 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/models.go @@ -0,0 +1,3832 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" + +// ActionType enumerates the values for action type. +type ActionType string + +const ( + // Allow ... + Allow ActionType = "Allow" + // Block ... + Block ActionType = "Block" + // Log ... + Log ActionType = "Log" + // Redirect ... + Redirect ActionType = "Redirect" +) + +// PossibleActionTypeValues returns an array of possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{Allow, Block, Log, Redirect} +} + +// Availability enumerates the values for availability. +type Availability string + +const ( + // Available ... + Available Availability = "Available" + // Unavailable ... + Unavailable Availability = "Unavailable" +) + +// PossibleAvailabilityValues returns an array of possible values for the Availability const type. +func PossibleAvailabilityValues() []Availability { + return []Availability{Available, Unavailable} +} + +// BackendEnabledState enumerates the values for backend enabled state. +type BackendEnabledState string + +const ( + // Disabled ... + Disabled BackendEnabledState = "Disabled" + // Enabled ... + Enabled BackendEnabledState = "Enabled" +) + +// PossibleBackendEnabledStateValues returns an array of possible values for the BackendEnabledState const type. +func PossibleBackendEnabledStateValues() []BackendEnabledState { + return []BackendEnabledState{Disabled, Enabled} +} + +// CertificateSource enumerates the values for certificate source. +type CertificateSource string + +const ( + // CertificateSourceAzureKeyVault ... + CertificateSourceAzureKeyVault CertificateSource = "AzureKeyVault" + // CertificateSourceFrontDoor ... + CertificateSourceFrontDoor CertificateSource = "FrontDoor" +) + +// PossibleCertificateSourceValues returns an array of possible values for the CertificateSource const type. +func PossibleCertificateSourceValues() []CertificateSource { + return []CertificateSource{CertificateSourceAzureKeyVault, CertificateSourceFrontDoor} +} + +// CertificateType enumerates the values for certificate type. +type CertificateType string + +const ( + // Dedicated ... + Dedicated CertificateType = "Dedicated" +) + +// PossibleCertificateTypeValues returns an array of possible values for the CertificateType const type. +func PossibleCertificateTypeValues() []CertificateType { + return []CertificateType{Dedicated} +} + +// CustomHTTPSProvisioningState enumerates the values for custom https provisioning state. +type CustomHTTPSProvisioningState string + +const ( + // CustomHTTPSProvisioningStateDisabled ... + CustomHTTPSProvisioningStateDisabled CustomHTTPSProvisioningState = "Disabled" + // CustomHTTPSProvisioningStateDisabling ... + CustomHTTPSProvisioningStateDisabling CustomHTTPSProvisioningState = "Disabling" + // CustomHTTPSProvisioningStateEnabled ... + CustomHTTPSProvisioningStateEnabled CustomHTTPSProvisioningState = "Enabled" + // CustomHTTPSProvisioningStateEnabling ... + CustomHTTPSProvisioningStateEnabling CustomHTTPSProvisioningState = "Enabling" + // CustomHTTPSProvisioningStateFailed ... + CustomHTTPSProvisioningStateFailed CustomHTTPSProvisioningState = "Failed" +) + +// PossibleCustomHTTPSProvisioningStateValues returns an array of possible values for the CustomHTTPSProvisioningState const type. +func PossibleCustomHTTPSProvisioningStateValues() []CustomHTTPSProvisioningState { + return []CustomHTTPSProvisioningState{CustomHTTPSProvisioningStateDisabled, CustomHTTPSProvisioningStateDisabling, CustomHTTPSProvisioningStateEnabled, CustomHTTPSProvisioningStateEnabling, CustomHTTPSProvisioningStateFailed} +} + +// CustomHTTPSProvisioningSubstate enumerates the values for custom https provisioning substate. +type CustomHTTPSProvisioningSubstate string + +const ( + // CertificateDeleted ... + CertificateDeleted CustomHTTPSProvisioningSubstate = "CertificateDeleted" + // CertificateDeployed ... + CertificateDeployed CustomHTTPSProvisioningSubstate = "CertificateDeployed" + // DeletingCertificate ... + DeletingCertificate CustomHTTPSProvisioningSubstate = "DeletingCertificate" + // DeployingCertificate ... + DeployingCertificate CustomHTTPSProvisioningSubstate = "DeployingCertificate" + // DomainControlValidationRequestApproved ... + DomainControlValidationRequestApproved CustomHTTPSProvisioningSubstate = "DomainControlValidationRequestApproved" + // DomainControlValidationRequestRejected ... + DomainControlValidationRequestRejected CustomHTTPSProvisioningSubstate = "DomainControlValidationRequestRejected" + // DomainControlValidationRequestTimedOut ... + DomainControlValidationRequestTimedOut CustomHTTPSProvisioningSubstate = "DomainControlValidationRequestTimedOut" + // IssuingCertificate ... + IssuingCertificate CustomHTTPSProvisioningSubstate = "IssuingCertificate" + // PendingDomainControlValidationREquestApproval ... + PendingDomainControlValidationREquestApproval CustomHTTPSProvisioningSubstate = "PendingDomainControlValidationREquestApproval" + // SubmittingDomainControlValidationRequest ... + SubmittingDomainControlValidationRequest CustomHTTPSProvisioningSubstate = "SubmittingDomainControlValidationRequest" +) + +// PossibleCustomHTTPSProvisioningSubstateValues returns an array of possible values for the CustomHTTPSProvisioningSubstate const type. +func PossibleCustomHTTPSProvisioningSubstateValues() []CustomHTTPSProvisioningSubstate { + return []CustomHTTPSProvisioningSubstate{CertificateDeleted, CertificateDeployed, DeletingCertificate, DeployingCertificate, DomainControlValidationRequestApproved, DomainControlValidationRequestRejected, DomainControlValidationRequestTimedOut, IssuingCertificate, PendingDomainControlValidationREquestApproval, SubmittingDomainControlValidationRequest} +} + +// CustomRuleEnabledState enumerates the values for custom rule enabled state. +type CustomRuleEnabledState string + +const ( + // CustomRuleEnabledStateDisabled ... + CustomRuleEnabledStateDisabled CustomRuleEnabledState = "Disabled" + // CustomRuleEnabledStateEnabled ... + CustomRuleEnabledStateEnabled CustomRuleEnabledState = "Enabled" +) + +// PossibleCustomRuleEnabledStateValues returns an array of possible values for the CustomRuleEnabledState const type. +func PossibleCustomRuleEnabledStateValues() []CustomRuleEnabledState { + return []CustomRuleEnabledState{CustomRuleEnabledStateDisabled, CustomRuleEnabledStateEnabled} +} + +// DynamicCompressionEnabled enumerates the values for dynamic compression enabled. +type DynamicCompressionEnabled string + +const ( + // DynamicCompressionEnabledDisabled ... + DynamicCompressionEnabledDisabled DynamicCompressionEnabled = "Disabled" + // DynamicCompressionEnabledEnabled ... + DynamicCompressionEnabledEnabled DynamicCompressionEnabled = "Enabled" +) + +// PossibleDynamicCompressionEnabledValues returns an array of possible values for the DynamicCompressionEnabled const type. +func PossibleDynamicCompressionEnabledValues() []DynamicCompressionEnabled { + return []DynamicCompressionEnabled{DynamicCompressionEnabledDisabled, DynamicCompressionEnabledEnabled} +} + +// EnabledState enumerates the values for enabled state. +type EnabledState string + +const ( + // EnabledStateDisabled ... + EnabledStateDisabled EnabledState = "Disabled" + // EnabledStateEnabled ... + EnabledStateEnabled EnabledState = "Enabled" +) + +// PossibleEnabledStateValues returns an array of possible values for the EnabledState const type. +func PossibleEnabledStateValues() []EnabledState { + return []EnabledState{EnabledStateDisabled, EnabledStateEnabled} +} + +// EnforceCertificateNameCheckEnabledState enumerates the values for enforce certificate name check enabled +// state. +type EnforceCertificateNameCheckEnabledState string + +const ( + // EnforceCertificateNameCheckEnabledStateDisabled ... + EnforceCertificateNameCheckEnabledStateDisabled EnforceCertificateNameCheckEnabledState = "Disabled" + // EnforceCertificateNameCheckEnabledStateEnabled ... + EnforceCertificateNameCheckEnabledStateEnabled EnforceCertificateNameCheckEnabledState = "Enabled" +) + +// PossibleEnforceCertificateNameCheckEnabledStateValues returns an array of possible values for the EnforceCertificateNameCheckEnabledState const type. +func PossibleEnforceCertificateNameCheckEnabledStateValues() []EnforceCertificateNameCheckEnabledState { + return []EnforceCertificateNameCheckEnabledState{EnforceCertificateNameCheckEnabledStateDisabled, EnforceCertificateNameCheckEnabledStateEnabled} +} + +// ForwardingProtocol enumerates the values for forwarding protocol. +type ForwardingProtocol string + +const ( + // HTTPOnly ... + HTTPOnly ForwardingProtocol = "HttpOnly" + // HTTPSOnly ... + HTTPSOnly ForwardingProtocol = "HttpsOnly" + // MatchRequest ... + MatchRequest ForwardingProtocol = "MatchRequest" +) + +// PossibleForwardingProtocolValues returns an array of possible values for the ForwardingProtocol const type. +func PossibleForwardingProtocolValues() []ForwardingProtocol { + return []ForwardingProtocol{HTTPOnly, HTTPSOnly, MatchRequest} +} + +// ManagedRuleEnabledState enumerates the values for managed rule enabled state. +type ManagedRuleEnabledState string + +const ( + // ManagedRuleEnabledStateDisabled ... + ManagedRuleEnabledStateDisabled ManagedRuleEnabledState = "Disabled" + // ManagedRuleEnabledStateEnabled ... + ManagedRuleEnabledStateEnabled ManagedRuleEnabledState = "Enabled" +) + +// PossibleManagedRuleEnabledStateValues returns an array of possible values for the ManagedRuleEnabledState const type. +func PossibleManagedRuleEnabledStateValues() []ManagedRuleEnabledState { + return []ManagedRuleEnabledState{ManagedRuleEnabledStateDisabled, ManagedRuleEnabledStateEnabled} +} + +// MatchVariable enumerates the values for match variable. +type MatchVariable string + +const ( + // Cookies ... + Cookies MatchVariable = "Cookies" + // PostArgs ... + PostArgs MatchVariable = "PostArgs" + // QueryString ... + QueryString MatchVariable = "QueryString" + // RemoteAddr ... + RemoteAddr MatchVariable = "RemoteAddr" + // RequestBody ... + RequestBody MatchVariable = "RequestBody" + // RequestHeader ... + RequestHeader MatchVariable = "RequestHeader" + // RequestMethod ... + RequestMethod MatchVariable = "RequestMethod" + // RequestURI ... + RequestURI MatchVariable = "RequestUri" +) + +// PossibleMatchVariableValues returns an array of possible values for the MatchVariable const type. +func PossibleMatchVariableValues() []MatchVariable { + return []MatchVariable{Cookies, PostArgs, QueryString, RemoteAddr, RequestBody, RequestHeader, RequestMethod, RequestURI} +} + +// NetworkOperationStatus enumerates the values for network operation status. +type NetworkOperationStatus string + +const ( + // Failed ... + Failed NetworkOperationStatus = "Failed" + // InProgress ... + InProgress NetworkOperationStatus = "InProgress" + // Succeeded ... + Succeeded NetworkOperationStatus = "Succeeded" +) + +// PossibleNetworkOperationStatusValues returns an array of possible values for the NetworkOperationStatus const type. +func PossibleNetworkOperationStatusValues() []NetworkOperationStatus { + return []NetworkOperationStatus{Failed, InProgress, Succeeded} +} + +// OdataType enumerates the values for odata type. +type OdataType string + +const ( + // OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration ... + OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration OdataType = "#Microsoft.Azure.FrontDoor.Models.FrontdoorForwardingConfiguration" + // OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration ... + OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration OdataType = "#Microsoft.Azure.FrontDoor.Models.FrontdoorRedirectConfiguration" + // OdataTypeRouteConfiguration ... + OdataTypeRouteConfiguration OdataType = "RouteConfiguration" +) + +// PossibleOdataTypeValues returns an array of possible values for the OdataType const type. +func PossibleOdataTypeValues() []OdataType { + return []OdataType{OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration, OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration, OdataTypeRouteConfiguration} +} + +// Operator enumerates the values for operator. +type Operator string + +const ( + // Any ... + Any Operator = "Any" + // BeginsWith ... + BeginsWith Operator = "BeginsWith" + // Contains ... + Contains Operator = "Contains" + // EndsWith ... + EndsWith Operator = "EndsWith" + // Equal ... + Equal Operator = "Equal" + // GeoMatch ... + GeoMatch Operator = "GeoMatch" + // GreaterThan ... + GreaterThan Operator = "GreaterThan" + // GreaterThanOrEqual ... + GreaterThanOrEqual Operator = "GreaterThanOrEqual" + // IPMatch ... + IPMatch Operator = "IPMatch" + // LessThan ... + LessThan Operator = "LessThan" + // LessThanOrEqual ... + LessThanOrEqual Operator = "LessThanOrEqual" + // RegEx ... + RegEx Operator = "RegEx" +) + +// PossibleOperatorValues returns an array of possible values for the Operator const type. +func PossibleOperatorValues() []Operator { + return []Operator{Any, BeginsWith, Contains, EndsWith, Equal, GeoMatch, GreaterThan, GreaterThanOrEqual, IPMatch, LessThan, LessThanOrEqual, RegEx} +} + +// PolicyEnabledState enumerates the values for policy enabled state. +type PolicyEnabledState string + +const ( + // PolicyEnabledStateDisabled ... + PolicyEnabledStateDisabled PolicyEnabledState = "Disabled" + // PolicyEnabledStateEnabled ... + PolicyEnabledStateEnabled PolicyEnabledState = "Enabled" +) + +// PossiblePolicyEnabledStateValues returns an array of possible values for the PolicyEnabledState const type. +func PossiblePolicyEnabledStateValues() []PolicyEnabledState { + return []PolicyEnabledState{PolicyEnabledStateDisabled, PolicyEnabledStateEnabled} +} + +// PolicyMode enumerates the values for policy mode. +type PolicyMode string + +const ( + // Detection ... + Detection PolicyMode = "Detection" + // Prevention ... + Prevention PolicyMode = "Prevention" +) + +// PossiblePolicyModeValues returns an array of possible values for the PolicyMode const type. +func PossiblePolicyModeValues() []PolicyMode { + return []PolicyMode{Detection, Prevention} +} + +// PolicyResourceState enumerates the values for policy resource state. +type PolicyResourceState string + +const ( + // PolicyResourceStateCreating ... + PolicyResourceStateCreating PolicyResourceState = "Creating" + // PolicyResourceStateDeleting ... + PolicyResourceStateDeleting PolicyResourceState = "Deleting" + // PolicyResourceStateDisabled ... + PolicyResourceStateDisabled PolicyResourceState = "Disabled" + // PolicyResourceStateDisabling ... + PolicyResourceStateDisabling PolicyResourceState = "Disabling" + // PolicyResourceStateEnabled ... + PolicyResourceStateEnabled PolicyResourceState = "Enabled" + // PolicyResourceStateEnabling ... + PolicyResourceStateEnabling PolicyResourceState = "Enabling" +) + +// PossiblePolicyResourceStateValues returns an array of possible values for the PolicyResourceState const type. +func PossiblePolicyResourceStateValues() []PolicyResourceState { + return []PolicyResourceState{PolicyResourceStateCreating, PolicyResourceStateDeleting, PolicyResourceStateDisabled, PolicyResourceStateDisabling, PolicyResourceStateEnabled, PolicyResourceStateEnabling} +} + +// Protocol enumerates the values for protocol. +type Protocol string + +const ( + // HTTP ... + HTTP Protocol = "Http" + // HTTPS ... + HTTPS Protocol = "Https" +) + +// PossibleProtocolValues returns an array of possible values for the Protocol const type. +func PossibleProtocolValues() []Protocol { + return []Protocol{HTTP, HTTPS} +} + +// Query enumerates the values for query. +type Query string + +const ( + // StripAll ... + StripAll Query = "StripAll" + // StripNone ... + StripNone Query = "StripNone" +) + +// PossibleQueryValues returns an array of possible values for the Query const type. +func PossibleQueryValues() []Query { + return []Query{StripAll, StripNone} +} + +// RedirectProtocol enumerates the values for redirect protocol. +type RedirectProtocol string + +const ( + // RedirectProtocolHTTPOnly ... + RedirectProtocolHTTPOnly RedirectProtocol = "HttpOnly" + // RedirectProtocolHTTPSOnly ... + RedirectProtocolHTTPSOnly RedirectProtocol = "HttpsOnly" + // RedirectProtocolMatchRequest ... + RedirectProtocolMatchRequest RedirectProtocol = "MatchRequest" +) + +// PossibleRedirectProtocolValues returns an array of possible values for the RedirectProtocol const type. +func PossibleRedirectProtocolValues() []RedirectProtocol { + return []RedirectProtocol{RedirectProtocolHTTPOnly, RedirectProtocolHTTPSOnly, RedirectProtocolMatchRequest} +} + +// RedirectType enumerates the values for redirect type. +type RedirectType string + +const ( + // Found ... + Found RedirectType = "Found" + // Moved ... + Moved RedirectType = "Moved" + // PermanentRedirect ... + PermanentRedirect RedirectType = "PermanentRedirect" + // TemporaryRedirect ... + TemporaryRedirect RedirectType = "TemporaryRedirect" +) + +// PossibleRedirectTypeValues returns an array of possible values for the RedirectType const type. +func PossibleRedirectTypeValues() []RedirectType { + return []RedirectType{Found, Moved, PermanentRedirect, TemporaryRedirect} +} + +// ResourceState enumerates the values for resource state. +type ResourceState string + +const ( + // ResourceStateCreating ... + ResourceStateCreating ResourceState = "Creating" + // ResourceStateDeleting ... + ResourceStateDeleting ResourceState = "Deleting" + // ResourceStateDisabled ... + ResourceStateDisabled ResourceState = "Disabled" + // ResourceStateDisabling ... + ResourceStateDisabling ResourceState = "Disabling" + // ResourceStateEnabled ... + ResourceStateEnabled ResourceState = "Enabled" + // ResourceStateEnabling ... + ResourceStateEnabling ResourceState = "Enabling" +) + +// PossibleResourceStateValues returns an array of possible values for the ResourceState const type. +func PossibleResourceStateValues() []ResourceState { + return []ResourceState{ResourceStateCreating, ResourceStateDeleting, ResourceStateDisabled, ResourceStateDisabling, ResourceStateEnabled, ResourceStateEnabling} +} + +// ResourceType enumerates the values for resource type. +type ResourceType string + +const ( + // MicrosoftNetworkfrontDoors ... + MicrosoftNetworkfrontDoors ResourceType = "Microsoft.Network/frontDoors" + // MicrosoftNetworkfrontDoorsfrontendEndpoints ... + MicrosoftNetworkfrontDoorsfrontendEndpoints ResourceType = "Microsoft.Network/frontDoors/frontendEndpoints" +) + +// PossibleResourceTypeValues returns an array of possible values for the ResourceType const type. +func PossibleResourceTypeValues() []ResourceType { + return []ResourceType{MicrosoftNetworkfrontDoors, MicrosoftNetworkfrontDoorsfrontendEndpoints} +} + +// RoutingRuleEnabledState enumerates the values for routing rule enabled state. +type RoutingRuleEnabledState string + +const ( + // RoutingRuleEnabledStateDisabled ... + RoutingRuleEnabledStateDisabled RoutingRuleEnabledState = "Disabled" + // RoutingRuleEnabledStateEnabled ... + RoutingRuleEnabledStateEnabled RoutingRuleEnabledState = "Enabled" +) + +// PossibleRoutingRuleEnabledStateValues returns an array of possible values for the RoutingRuleEnabledState const type. +func PossibleRoutingRuleEnabledStateValues() []RoutingRuleEnabledState { + return []RoutingRuleEnabledState{RoutingRuleEnabledStateDisabled, RoutingRuleEnabledStateEnabled} +} + +// RuleType enumerates the values for rule type. +type RuleType string + +const ( + // MatchRule ... + MatchRule RuleType = "MatchRule" + // RateLimitRule ... + RateLimitRule RuleType = "RateLimitRule" +) + +// PossibleRuleTypeValues returns an array of possible values for the RuleType const type. +func PossibleRuleTypeValues() []RuleType { + return []RuleType{MatchRule, RateLimitRule} +} + +// SessionAffinityEnabledState enumerates the values for session affinity enabled state. +type SessionAffinityEnabledState string + +const ( + // SessionAffinityEnabledStateDisabled ... + SessionAffinityEnabledStateDisabled SessionAffinityEnabledState = "Disabled" + // SessionAffinityEnabledStateEnabled ... + SessionAffinityEnabledStateEnabled SessionAffinityEnabledState = "Enabled" +) + +// PossibleSessionAffinityEnabledStateValues returns an array of possible values for the SessionAffinityEnabledState const type. +func PossibleSessionAffinityEnabledStateValues() []SessionAffinityEnabledState { + return []SessionAffinityEnabledState{SessionAffinityEnabledStateDisabled, SessionAffinityEnabledStateEnabled} +} + +// TLSProtocolType enumerates the values for tls protocol type. +type TLSProtocolType string + +const ( + // ServerNameIndication ... + ServerNameIndication TLSProtocolType = "ServerNameIndication" +) + +// PossibleTLSProtocolTypeValues returns an array of possible values for the TLSProtocolType const type. +func PossibleTLSProtocolTypeValues() []TLSProtocolType { + return []TLSProtocolType{ServerNameIndication} +} + +// TransformType enumerates the values for transform type. +type TransformType string + +const ( + // Lowercase ... + Lowercase TransformType = "Lowercase" + // RemoveNulls ... + RemoveNulls TransformType = "RemoveNulls" + // Trim ... + Trim TransformType = "Trim" + // Uppercase ... + Uppercase TransformType = "Uppercase" + // URLDecode ... + URLDecode TransformType = "UrlDecode" + // URLEncode ... + URLEncode TransformType = "UrlEncode" +) + +// PossibleTransformTypeValues returns an array of possible values for the TransformType const type. +func PossibleTransformTypeValues() []TransformType { + return []TransformType{Lowercase, RemoveNulls, Trim, Uppercase, URLDecode, URLEncode} +} + +// AzureAsyncOperationResult the response body contains the status of the specified asynchronous operation, +// indicating whether it has succeeded, is in progress, or has failed. Note that this status is distinct +// from the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous +// operation succeeded, the response body includes the HTTP status code for the successful request. If the +// asynchronous operation failed, the response body includes the HTTP status code for the failed request +// and error information regarding the failure. +type AzureAsyncOperationResult struct { + // Status - Status of the Azure async operation. Possible values are: 'InProgress', 'Succeeded', and 'Failed'. Possible values include: 'InProgress', 'Succeeded', 'Failed' + Status NetworkOperationStatus `json:"status,omitempty"` + Error *Error `json:"error,omitempty"` +} + +// Backend backend address of a frontDoor load balancer. +type Backend struct { + // Address - Location of the backend (IP address or FQDN) + Address *string `json:"address,omitempty"` + // HTTPPort - The HTTP TCP port number. Must be between 1 and 65535. + HTTPPort *int32 `json:"httpPort,omitempty"` + // HTTPSPort - The HTTPS TCP port number. Must be between 1 and 65535. + HTTPSPort *int32 `json:"httpsPort,omitempty"` + // EnabledState - Whether to enable use of this backend. Permitted values are 'Enabled' or 'Disabled'. Possible values include: 'Enabled', 'Disabled' + EnabledState BackendEnabledState `json:"enabledState,omitempty"` + // Priority - Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy. + Priority *int32 `json:"priority,omitempty"` + // Weight - Weight of this endpoint for load balancing purposes. + Weight *int32 `json:"weight,omitempty"` + // BackendHostHeader - The value to use as the host header sent to the backend. If blank or unspecified, this defaults to the incoming host. + BackendHostHeader *string `json:"backendHostHeader,omitempty"` +} + +// BackendPool a backend pool is a collection of backends that can be routed to. +type BackendPool struct { + autorest.Response `json:"-"` + // BackendPoolProperties - Properties of the Front Door Backend Pool + *BackendPoolProperties `json:"properties,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// MarshalJSON is the custom marshaler for BackendPool. +func (bp BackendPool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if bp.BackendPoolProperties != nil { + objectMap["properties"] = bp.BackendPoolProperties + } + if bp.Name != nil { + objectMap["name"] = bp.Name + } + if bp.ID != nil { + objectMap["id"] = bp.ID + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for BackendPool struct. +func (bp *BackendPool) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var backendPoolProperties BackendPoolProperties + err = json.Unmarshal(*v, &backendPoolProperties) + if err != nil { + return err + } + bp.BackendPoolProperties = &backendPoolProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + bp.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + bp.Type = &typeVar + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + bp.ID = &ID + } + } + } + + return nil +} + +// BackendPoolListResult result of the request to list Backend Pools. It contains a list of Backend Pools +// objects and a URL link to get the next set of results. +type BackendPoolListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of Backend Pools within a Front Door. + Value *[]BackendPool `json:"value,omitempty"` + // NextLink - URL to get the next set of BackendPool objects if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// BackendPoolListResultIterator provides access to a complete listing of BackendPool values. +type BackendPoolListResultIterator struct { + i int + page BackendPoolListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *BackendPoolListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *BackendPoolListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter BackendPoolListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter BackendPoolListResultIterator) Response() BackendPoolListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter BackendPoolListResultIterator) Value() BackendPool { + if !iter.page.NotDone() { + return BackendPool{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the BackendPoolListResultIterator type. +func NewBackendPoolListResultIterator(page BackendPoolListResultPage) BackendPoolListResultIterator { + return BackendPoolListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (bplr BackendPoolListResult) IsEmpty() bool { + return bplr.Value == nil || len(*bplr.Value) == 0 +} + +// backendPoolListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (bplr BackendPoolListResult) backendPoolListResultPreparer(ctx context.Context) (*http.Request, error) { + if bplr.NextLink == nil || len(to.String(bplr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(bplr.NextLink))) +} + +// BackendPoolListResultPage contains a page of BackendPool values. +type BackendPoolListResultPage struct { + fn func(context.Context, BackendPoolListResult) (BackendPoolListResult, error) + bplr BackendPoolListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *BackendPoolListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/BackendPoolListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.bplr) + if err != nil { + return err + } + page.bplr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *BackendPoolListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page BackendPoolListResultPage) NotDone() bool { + return !page.bplr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page BackendPoolListResultPage) Response() BackendPoolListResult { + return page.bplr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page BackendPoolListResultPage) Values() []BackendPool { + if page.bplr.IsEmpty() { + return nil + } + return *page.bplr.Value +} + +// Creates a new instance of the BackendPoolListResultPage type. +func NewBackendPoolListResultPage(getNextPage func(context.Context, BackendPoolListResult) (BackendPoolListResult, error)) BackendPoolListResultPage { + return BackendPoolListResultPage{fn: getNextPage} +} + +// BackendPoolProperties the JSON object that contains the properties required to create a routing rule. +type BackendPoolProperties struct { + // ResourceState - Resource status. Possible values include: 'ResourceStateCreating', 'ResourceStateEnabling', 'ResourceStateEnabled', 'ResourceStateDisabling', 'ResourceStateDisabled', 'ResourceStateDeleting' + ResourceState ResourceState `json:"resourceState,omitempty"` + // Backends - The set of backends for this pool + Backends *[]Backend `json:"backends,omitempty"` + // LoadBalancingSettings - Load balancing settings for a backend pool + LoadBalancingSettings *SubResource `json:"loadBalancingSettings,omitempty"` + // HealthProbeSettings - L7 health probe settings for a backend pool + HealthProbeSettings *SubResource `json:"healthProbeSettings,omitempty"` +} + +// BackendPoolsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type BackendPoolsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *BackendPoolsCreateOrUpdateFuture) Result(client BackendPoolsClient) (bp BackendPool, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.BackendPoolsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if bp.Response.Response, err = future.GetResult(sender); err == nil && bp.Response.Response.StatusCode != http.StatusNoContent { + bp, err = client.CreateOrUpdateResponder(bp.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsCreateOrUpdateFuture", "Result", bp.Response.Response, "Failure responding to request") + } + } + return +} + +// BackendPoolsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type BackendPoolsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *BackendPoolsDeleteFuture) Result(client BackendPoolsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.BackendPoolsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.BackendPoolsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// BackendPoolsSettings settings that apply to all backend pools. +type BackendPoolsSettings struct { + // EnforceCertificateNameCheck - Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests. Possible values include: 'EnforceCertificateNameCheckEnabledStateEnabled', 'EnforceCertificateNameCheckEnabledStateDisabled' + EnforceCertificateNameCheck EnforceCertificateNameCheckEnabledState `json:"enforceCertificateNameCheck,omitempty"` +} + +// BackendPoolUpdateParameters a collection of backends that can be routed to. +type BackendPoolUpdateParameters struct { + // Backends - The set of backends for this pool + Backends *[]Backend `json:"backends,omitempty"` + // LoadBalancingSettings - Load balancing settings for a backend pool + LoadBalancingSettings *SubResource `json:"loadBalancingSettings,omitempty"` + // HealthProbeSettings - L7 health probe settings for a backend pool + HealthProbeSettings *SubResource `json:"healthProbeSettings,omitempty"` +} + +// CacheConfiguration caching settings for a caching-type route. To disable caching, do not provide a +// cacheConfiguration object. +type CacheConfiguration struct { + // QueryParameterStripDirective - Treatment of URL query terms when forming the cache key. Possible values include: 'StripNone', 'StripAll' + QueryParameterStripDirective Query `json:"queryParameterStripDirective,omitempty"` + // DynamicCompression - Whether to use dynamic compression for cached content. Possible values include: 'DynamicCompressionEnabledEnabled', 'DynamicCompressionEnabledDisabled' + DynamicCompression DynamicCompressionEnabled `json:"dynamicCompression,omitempty"` +} + +// CertificateSourceParameters parameters required for enabling SSL with Front Door-managed certificates +type CertificateSourceParameters struct { + // CertificateType - Defines the type of the certificate used for secure connections to a frontendEndpoint. Possible values include: 'Dedicated' + CertificateType CertificateType `json:"certificateType,omitempty"` +} + +// CheckNameAvailabilityInput input of CheckNameAvailability API. +type CheckNameAvailabilityInput struct { + // Name - The resource name to validate. + Name *string `json:"name,omitempty"` + // Type - The type of the resource whose name is to be validated. Possible values include: 'MicrosoftNetworkfrontDoors', 'MicrosoftNetworkfrontDoorsfrontendEndpoints' + Type ResourceType `json:"type,omitempty"` +} + +// CheckNameAvailabilityOutput output of check name availability API. +type CheckNameAvailabilityOutput struct { + autorest.Response `json:"-"` + // NameAvailability - READ-ONLY; Indicates whether the name is available. Possible values include: 'Available', 'Unavailable' + NameAvailability Availability `json:"nameAvailability,omitempty"` + // Reason - READ-ONLY; The reason why the name is not available. + Reason *string `json:"reason,omitempty"` + // Message - READ-ONLY; The detailed error message describing why the name is not available. + Message *string `json:"message,omitempty"` +} + +// CustomHTTPSConfiguration https settings for a domain +type CustomHTTPSConfiguration struct { + // CertificateSource - Defines the source of the SSL certificate. Possible values include: 'CertificateSourceAzureKeyVault', 'CertificateSourceFrontDoor' + CertificateSource CertificateSource `json:"certificateSource,omitempty"` + // ProtocolType - Defines the TLS extension protocol that is used for secure delivery. Possible values include: 'ServerNameIndication' + ProtocolType TLSProtocolType `json:"protocolType,omitempty"` + // KeyVaultCertificateSourceParameters - KeyVault certificate source parameters (if certificateSource=AzureKeyVault) + *KeyVaultCertificateSourceParameters `json:"keyVaultCertificateSourceParameters,omitempty"` + // CertificateSourceParameters - Parameters required for enabling SSL with Front Door-managed certificates (if certificateSource=FrontDoor) + *CertificateSourceParameters `json:"frontDoorCertificateSourceParameters,omitempty"` +} + +// MarshalJSON is the custom marshaler for CustomHTTPSConfiguration. +func (chc CustomHTTPSConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if chc.CertificateSource != "" { + objectMap["certificateSource"] = chc.CertificateSource + } + if chc.ProtocolType != "" { + objectMap["protocolType"] = chc.ProtocolType + } + if chc.KeyVaultCertificateSourceParameters != nil { + objectMap["keyVaultCertificateSourceParameters"] = chc.KeyVaultCertificateSourceParameters + } + if chc.CertificateSourceParameters != nil { + objectMap["frontDoorCertificateSourceParameters"] = chc.CertificateSourceParameters + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CustomHTTPSConfiguration struct. +func (chc *CustomHTTPSConfiguration) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "certificateSource": + if v != nil { + var certificateSource CertificateSource + err = json.Unmarshal(*v, &certificateSource) + if err != nil { + return err + } + chc.CertificateSource = certificateSource + } + case "protocolType": + if v != nil { + var protocolType TLSProtocolType + err = json.Unmarshal(*v, &protocolType) + if err != nil { + return err + } + chc.ProtocolType = protocolType + } + case "keyVaultCertificateSourceParameters": + if v != nil { + var keyVaultCertificateSourceParameters KeyVaultCertificateSourceParameters + err = json.Unmarshal(*v, &keyVaultCertificateSourceParameters) + if err != nil { + return err + } + chc.KeyVaultCertificateSourceParameters = &keyVaultCertificateSourceParameters + } + case "frontDoorCertificateSourceParameters": + if v != nil { + var certificateSourceParameters CertificateSourceParameters + err = json.Unmarshal(*v, &certificateSourceParameters) + if err != nil { + return err + } + chc.CertificateSourceParameters = &certificateSourceParameters + } + } + } + + return nil +} + +// CustomRule defines contents of a web application rule +type CustomRule struct { + // Name - Describes the name of the rule. + Name *string `json:"name,omitempty"` + // Priority - Describes priority of the rule. Rules with a lower value will be evaluated before rules with a higher value. + Priority *int32 `json:"priority,omitempty"` + // EnabledState - Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not specified. Possible values include: 'CustomRuleEnabledStateDisabled', 'CustomRuleEnabledStateEnabled' + EnabledState CustomRuleEnabledState `json:"enabledState,omitempty"` + // RuleType - Describes type of rule. Possible values include: 'MatchRule', 'RateLimitRule' + RuleType RuleType `json:"ruleType,omitempty"` + // RateLimitDurationInMinutes - Defines rate limit duration. Default is 1 minute. + RateLimitDurationInMinutes *int32 `json:"rateLimitDurationInMinutes,omitempty"` + // RateLimitThreshold - Defines rate limit threshold. + RateLimitThreshold *int32 `json:"rateLimitThreshold,omitempty"` + // MatchConditions - List of match conditions. + MatchConditions *[]MatchCondition `json:"matchConditions,omitempty"` + // Action - Describes what action to be applied when rule matches. Possible values include: 'Allow', 'Block', 'Log', 'Redirect' + Action ActionType `json:"action,omitempty"` +} + +// CustomRuleList defines contents of custom rules +type CustomRuleList struct { + // Rules - List of rules + Rules *[]CustomRule `json:"rules,omitempty"` +} + +// EndpointsPurgeContentFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type EndpointsPurgeContentFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EndpointsPurgeContentFuture) Result(client EndpointsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.EndpointsPurgeContentFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.EndpointsPurgeContentFuture") + return + } + ar.Response = future.Response() + return +} + +// Error ... +type Error struct { + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Target *string `json:"target,omitempty"` + Details *[]ErrorDetails `json:"details,omitempty"` + InnerError *string `json:"innerError,omitempty"` +} + +// ErrorDetails ... +type ErrorDetails struct { + Code *string `json:"code,omitempty"` + Target *string `json:"target,omitempty"` + Message *string `json:"message,omitempty"` +} + +// ErrorResponse error response indicates Front Door service is not able to process the incoming request. +// The reason is provided in the error message. +type ErrorResponse struct { + // Code - READ-ONLY; Error code. + Code *string `json:"code,omitempty"` + // Message - READ-ONLY; Error message indicating why the operation failed. + Message *string `json:"message,omitempty"` +} + +// ForwardingConfiguration describes Forwarding Route. +type ForwardingConfiguration struct { + // CustomForwardingPath - A custom path used to rewrite resource paths matched by this rule. Leave empty to use incoming path. + CustomForwardingPath *string `json:"customForwardingPath,omitempty"` + // ForwardingProtocol - Protocol this rule will use when forwarding traffic to backends. Possible values include: 'HTTPOnly', 'HTTPSOnly', 'MatchRequest' + ForwardingProtocol ForwardingProtocol `json:"forwardingProtocol,omitempty"` + // CacheConfiguration - The caching configuration associated with this rule. + CacheConfiguration *CacheConfiguration `json:"cacheConfiguration,omitempty"` + // BackendPool - A reference to the BackendPool which this rule routes to. + BackendPool *SubResource `json:"backendPool,omitempty"` + // OdataType - Possible values include: 'OdataTypeRouteConfiguration', 'OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration', 'OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration' + OdataType OdataType `json:"@odata.type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ForwardingConfiguration. +func (fc ForwardingConfiguration) MarshalJSON() ([]byte, error) { + fc.OdataType = OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration + objectMap := make(map[string]interface{}) + if fc.CustomForwardingPath != nil { + objectMap["customForwardingPath"] = fc.CustomForwardingPath + } + if fc.ForwardingProtocol != "" { + objectMap["forwardingProtocol"] = fc.ForwardingProtocol + } + if fc.CacheConfiguration != nil { + objectMap["cacheConfiguration"] = fc.CacheConfiguration + } + if fc.BackendPool != nil { + objectMap["backendPool"] = fc.BackendPool + } + if fc.OdataType != "" { + objectMap["@odata.type"] = fc.OdataType + } + return json.Marshal(objectMap) +} + +// AsForwardingConfiguration is the BasicRouteConfiguration implementation for ForwardingConfiguration. +func (fc ForwardingConfiguration) AsForwardingConfiguration() (*ForwardingConfiguration, bool) { + return &fc, true +} + +// AsRedirectConfiguration is the BasicRouteConfiguration implementation for ForwardingConfiguration. +func (fc ForwardingConfiguration) AsRedirectConfiguration() (*RedirectConfiguration, bool) { + return nil, false +} + +// AsRouteConfiguration is the BasicRouteConfiguration implementation for ForwardingConfiguration. +func (fc ForwardingConfiguration) AsRouteConfiguration() (*RouteConfiguration, bool) { + return nil, false +} + +// AsBasicRouteConfiguration is the BasicRouteConfiguration implementation for ForwardingConfiguration. +func (fc ForwardingConfiguration) AsBasicRouteConfiguration() (BasicRouteConfiguration, bool) { + return &fc, true +} + +// FrontDoor front Door represents a collection of backend endpoints to route traffic to along with rules +// that specify how traffic is sent there. +type FrontDoor struct { + autorest.Response `json:"-"` + // Properties - Properties of the Front Door Load Balancer + *Properties `json:"properties,omitempty"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for FrontDoor. +func (fd FrontDoor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if fd.Properties != nil { + objectMap["properties"] = fd.Properties + } + if fd.Location != nil { + objectMap["location"] = fd.Location + } + if fd.Tags != nil { + objectMap["tags"] = fd.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for FrontDoor struct. +func (fd *FrontDoor) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var properties Properties + err = json.Unmarshal(*v, &properties) + if err != nil { + return err + } + fd.Properties = &properties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + fd.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + fd.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + fd.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + fd.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + fd.Tags = tags + } + } + } + + return nil +} + +// FrontDoorsCreateOrUpdateFutureType an abstraction for monitoring and retrieving the results of a +// long-running operation. +type FrontDoorsCreateOrUpdateFutureType struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FrontDoorsCreateOrUpdateFutureType) Result(client FrontDoorsClient) (fd FrontDoor, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsCreateOrUpdateFutureType", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.FrontDoorsCreateOrUpdateFutureType") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if fd.Response.Response, err = future.GetResult(sender); err == nil && fd.Response.Response.StatusCode != http.StatusNoContent { + fd, err = client.CreateOrUpdateResponder(fd.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsCreateOrUpdateFutureType", "Result", fd.Response.Response, "Failure responding to request") + } + } + return +} + +// FrontDoorsDeleteFutureType an abstraction for monitoring and retrieving the results of a long-running +// operation. +type FrontDoorsDeleteFutureType struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FrontDoorsDeleteFutureType) Result(client FrontDoorsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontDoorsDeleteFutureType", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.FrontDoorsDeleteFutureType") + return + } + ar.Response = future.Response() + return +} + +// FrontendEndpoint a frontend endpoint used for routing. +type FrontendEndpoint struct { + autorest.Response `json:"-"` + // FrontendEndpointProperties - Properties of the Frontend endpoint + *FrontendEndpointProperties `json:"properties,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// MarshalJSON is the custom marshaler for FrontendEndpoint. +func (fe FrontendEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if fe.FrontendEndpointProperties != nil { + objectMap["properties"] = fe.FrontendEndpointProperties + } + if fe.Name != nil { + objectMap["name"] = fe.Name + } + if fe.ID != nil { + objectMap["id"] = fe.ID + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for FrontendEndpoint struct. +func (fe *FrontendEndpoint) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var frontendEndpointProperties FrontendEndpointProperties + err = json.Unmarshal(*v, &frontendEndpointProperties) + if err != nil { + return err + } + fe.FrontendEndpointProperties = &frontendEndpointProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + fe.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + fe.Type = &typeVar + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + fe.ID = &ID + } + } + } + + return nil +} + +// FrontendEndpointLink defines the Resource ID for a Frontend Endpoint. +type FrontendEndpointLink struct { + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// FrontendEndpointProperties the JSON object that contains the properties required to create a frontend +// endpoint. +type FrontendEndpointProperties struct { + // ResourceState - Resource status. Possible values include: 'ResourceStateCreating', 'ResourceStateEnabling', 'ResourceStateEnabled', 'ResourceStateDisabling', 'ResourceStateDisabled', 'ResourceStateDeleting' + ResourceState ResourceState `json:"resourceState,omitempty"` + // CustomHTTPSProvisioningState - READ-ONLY; Provisioning status of Custom Https of the frontendEndpoint. Possible values include: 'CustomHTTPSProvisioningStateEnabling', 'CustomHTTPSProvisioningStateEnabled', 'CustomHTTPSProvisioningStateDisabling', 'CustomHTTPSProvisioningStateDisabled', 'CustomHTTPSProvisioningStateFailed' + CustomHTTPSProvisioningState CustomHTTPSProvisioningState `json:"customHttpsProvisioningState,omitempty"` + // CustomHTTPSProvisioningSubstate - READ-ONLY; Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by step. Possible values include: 'SubmittingDomainControlValidationRequest', 'PendingDomainControlValidationREquestApproval', 'DomainControlValidationRequestApproved', 'DomainControlValidationRequestRejected', 'DomainControlValidationRequestTimedOut', 'IssuingCertificate', 'DeployingCertificate', 'CertificateDeployed', 'DeletingCertificate', 'CertificateDeleted' + CustomHTTPSProvisioningSubstate CustomHTTPSProvisioningSubstate `json:"customHttpsProvisioningSubstate,omitempty"` + // CustomHTTPSConfiguration - READ-ONLY; The configuration specifying how to enable HTTPS + CustomHTTPSConfiguration *CustomHTTPSConfiguration `json:"customHttpsConfiguration,omitempty"` + // HostName - The host name of the frontendEndpoint. Must be a domain name. + HostName *string `json:"hostName,omitempty"` + // SessionAffinityEnabledState - Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled'. Possible values include: 'SessionAffinityEnabledStateEnabled', 'SessionAffinityEnabledStateDisabled' + SessionAffinityEnabledState SessionAffinityEnabledState `json:"sessionAffinityEnabledState,omitempty"` + // SessionAffinityTTLSeconds - UNUSED. This field will be ignored. The TTL to use in seconds for session affinity, if applicable. + SessionAffinityTTLSeconds *int32 `json:"sessionAffinityTtlSeconds,omitempty"` + // WebApplicationFirewallPolicyLink - Defines the Web Application Firewall policy for each host (if applicable) + WebApplicationFirewallPolicyLink *FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink `json:"webApplicationFirewallPolicyLink,omitempty"` +} + +// FrontendEndpointsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type FrontendEndpointsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FrontendEndpointsCreateOrUpdateFuture) Result(client FrontendEndpointsClient) (fe FrontendEndpoint, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.FrontendEndpointsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if fe.Response.Response, err = future.GetResult(sender); err == nil && fe.Response.Response.StatusCode != http.StatusNoContent { + fe, err = client.CreateOrUpdateResponder(fe.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsCreateOrUpdateFuture", "Result", fe.Response.Response, "Failure responding to request") + } + } + return +} + +// FrontendEndpointsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type FrontendEndpointsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FrontendEndpointsDeleteFuture) Result(client FrontendEndpointsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.FrontendEndpointsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// FrontendEndpointsDisableHTTPSFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type FrontendEndpointsDisableHTTPSFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FrontendEndpointsDisableHTTPSFuture) Result(client FrontendEndpointsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsDisableHTTPSFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.FrontendEndpointsDisableHTTPSFuture") + return + } + ar.Response = future.Response() + return +} + +// FrontendEndpointsEnableHTTPSFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type FrontendEndpointsEnableHTTPSFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FrontendEndpointsEnableHTTPSFuture) Result(client FrontendEndpointsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.FrontendEndpointsEnableHTTPSFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.FrontendEndpointsEnableHTTPSFuture") + return + } + ar.Response = future.Response() + return +} + +// FrontendEndpointsListResult result of the request to list frontend endpoints. It contains a list of +// Frontend endpoint objects and a URL link to get the next set of results. +type FrontendEndpointsListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of Frontend endpoints within a Front Door. + Value *[]FrontendEndpoint `json:"value,omitempty"` + // NextLink - URL to get the next set of frontend endpoints if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// FrontendEndpointsListResultIterator provides access to a complete listing of FrontendEndpoint values. +type FrontendEndpointsListResultIterator struct { + i int + page FrontendEndpointsListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *FrontendEndpointsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *FrontendEndpointsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter FrontendEndpointsListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter FrontendEndpointsListResultIterator) Response() FrontendEndpointsListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter FrontendEndpointsListResultIterator) Value() FrontendEndpoint { + if !iter.page.NotDone() { + return FrontendEndpoint{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the FrontendEndpointsListResultIterator type. +func NewFrontendEndpointsListResultIterator(page FrontendEndpointsListResultPage) FrontendEndpointsListResultIterator { + return FrontendEndpointsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (felr FrontendEndpointsListResult) IsEmpty() bool { + return felr.Value == nil || len(*felr.Value) == 0 +} + +// frontendEndpointsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (felr FrontendEndpointsListResult) frontendEndpointsListResultPreparer(ctx context.Context) (*http.Request, error) { + if felr.NextLink == nil || len(to.String(felr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(felr.NextLink))) +} + +// FrontendEndpointsListResultPage contains a page of FrontendEndpoint values. +type FrontendEndpointsListResultPage struct { + fn func(context.Context, FrontendEndpointsListResult) (FrontendEndpointsListResult, error) + felr FrontendEndpointsListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *FrontendEndpointsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FrontendEndpointsListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.felr) + if err != nil { + return err + } + page.felr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *FrontendEndpointsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page FrontendEndpointsListResultPage) NotDone() bool { + return !page.felr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page FrontendEndpointsListResultPage) Response() FrontendEndpointsListResult { + return page.felr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page FrontendEndpointsListResultPage) Values() []FrontendEndpoint { + if page.felr.IsEmpty() { + return nil + } + return *page.felr.Value +} + +// Creates a new instance of the FrontendEndpointsListResultPage type. +func NewFrontendEndpointsListResultPage(getNextPage func(context.Context, FrontendEndpointsListResult) (FrontendEndpointsListResult, error)) FrontendEndpointsListResultPage { + return FrontendEndpointsListResultPage{fn: getNextPage} +} + +// FrontendEndpointUpdateParameters frontend endpoint used in routing rule +type FrontendEndpointUpdateParameters struct { + // HostName - The host name of the frontendEndpoint. Must be a domain name. + HostName *string `json:"hostName,omitempty"` + // SessionAffinityEnabledState - Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled'. Possible values include: 'SessionAffinityEnabledStateEnabled', 'SessionAffinityEnabledStateDisabled' + SessionAffinityEnabledState SessionAffinityEnabledState `json:"sessionAffinityEnabledState,omitempty"` + // SessionAffinityTTLSeconds - UNUSED. This field will be ignored. The TTL to use in seconds for session affinity, if applicable. + SessionAffinityTTLSeconds *int32 `json:"sessionAffinityTtlSeconds,omitempty"` + // WebApplicationFirewallPolicyLink - Defines the Web Application Firewall policy for each host (if applicable) + WebApplicationFirewallPolicyLink *FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink `json:"webApplicationFirewallPolicyLink,omitempty"` +} + +// FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink defines the Web Application Firewall +// policy for each host (if applicable) +type FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink struct { + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// HealthProbeSettingsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type HealthProbeSettingsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *HealthProbeSettingsCreateOrUpdateFuture) Result(client HealthProbeSettingsClient) (hpsm HealthProbeSettingsModel, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.HealthProbeSettingsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if hpsm.Response.Response, err = future.GetResult(sender); err == nil && hpsm.Response.Response.StatusCode != http.StatusNoContent { + hpsm, err = client.CreateOrUpdateResponder(hpsm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsCreateOrUpdateFuture", "Result", hpsm.Response.Response, "Failure responding to request") + } + } + return +} + +// HealthProbeSettingsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type HealthProbeSettingsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *HealthProbeSettingsDeleteFuture) Result(client HealthProbeSettingsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.HealthProbeSettingsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.HealthProbeSettingsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// HealthProbeSettingsListResult result of the request to list HealthProbeSettings. It contains a list of +// HealthProbeSettings objects and a URL link to get the next set of results. +type HealthProbeSettingsListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of HealthProbeSettings within a Front Door. + Value *[]HealthProbeSettingsModel `json:"value,omitempty"` + // NextLink - URL to get the next set of HealthProbeSettings objects if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// HealthProbeSettingsListResultIterator provides access to a complete listing of HealthProbeSettingsModel +// values. +type HealthProbeSettingsListResultIterator struct { + i int + page HealthProbeSettingsListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *HealthProbeSettingsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *HealthProbeSettingsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter HealthProbeSettingsListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter HealthProbeSettingsListResultIterator) Response() HealthProbeSettingsListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter HealthProbeSettingsListResultIterator) Value() HealthProbeSettingsModel { + if !iter.page.NotDone() { + return HealthProbeSettingsModel{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the HealthProbeSettingsListResultIterator type. +func NewHealthProbeSettingsListResultIterator(page HealthProbeSettingsListResultPage) HealthProbeSettingsListResultIterator { + return HealthProbeSettingsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (hpslr HealthProbeSettingsListResult) IsEmpty() bool { + return hpslr.Value == nil || len(*hpslr.Value) == 0 +} + +// healthProbeSettingsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (hpslr HealthProbeSettingsListResult) healthProbeSettingsListResultPreparer(ctx context.Context) (*http.Request, error) { + if hpslr.NextLink == nil || len(to.String(hpslr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(hpslr.NextLink))) +} + +// HealthProbeSettingsListResultPage contains a page of HealthProbeSettingsModel values. +type HealthProbeSettingsListResultPage struct { + fn func(context.Context, HealthProbeSettingsListResult) (HealthProbeSettingsListResult, error) + hpslr HealthProbeSettingsListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *HealthProbeSettingsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/HealthProbeSettingsListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.hpslr) + if err != nil { + return err + } + page.hpslr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *HealthProbeSettingsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page HealthProbeSettingsListResultPage) NotDone() bool { + return !page.hpslr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page HealthProbeSettingsListResultPage) Response() HealthProbeSettingsListResult { + return page.hpslr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page HealthProbeSettingsListResultPage) Values() []HealthProbeSettingsModel { + if page.hpslr.IsEmpty() { + return nil + } + return *page.hpslr.Value +} + +// Creates a new instance of the HealthProbeSettingsListResultPage type. +func NewHealthProbeSettingsListResultPage(getNextPage func(context.Context, HealthProbeSettingsListResult) (HealthProbeSettingsListResult, error)) HealthProbeSettingsListResultPage { + return HealthProbeSettingsListResultPage{fn: getNextPage} +} + +// HealthProbeSettingsModel load balancing settings for a backend pool +type HealthProbeSettingsModel struct { + autorest.Response `json:"-"` + // HealthProbeSettingsProperties - Properties of the health probe settings + *HealthProbeSettingsProperties `json:"properties,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// MarshalJSON is the custom marshaler for HealthProbeSettingsModel. +func (hpsm HealthProbeSettingsModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if hpsm.HealthProbeSettingsProperties != nil { + objectMap["properties"] = hpsm.HealthProbeSettingsProperties + } + if hpsm.Name != nil { + objectMap["name"] = hpsm.Name + } + if hpsm.ID != nil { + objectMap["id"] = hpsm.ID + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for HealthProbeSettingsModel struct. +func (hpsm *HealthProbeSettingsModel) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var healthProbeSettingsProperties HealthProbeSettingsProperties + err = json.Unmarshal(*v, &healthProbeSettingsProperties) + if err != nil { + return err + } + hpsm.HealthProbeSettingsProperties = &healthProbeSettingsProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + hpsm.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + hpsm.Type = &typeVar + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + hpsm.ID = &ID + } + } + } + + return nil +} + +// HealthProbeSettingsProperties the JSON object that contains the properties required to create a health +// probe settings. +type HealthProbeSettingsProperties struct { + // ResourceState - Resource status. Possible values include: 'ResourceStateCreating', 'ResourceStateEnabling', 'ResourceStateEnabled', 'ResourceStateDisabling', 'ResourceStateDisabled', 'ResourceStateDeleting' + ResourceState ResourceState `json:"resourceState,omitempty"` + // Path - The path to use for the health probe. Default is / + Path *string `json:"path,omitempty"` + // Protocol - Protocol scheme to use for this probe. Possible values include: 'HTTP', 'HTTPS' + Protocol Protocol `json:"protocol,omitempty"` + // IntervalInSeconds - The number of seconds between health probes. + IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` +} + +// HealthProbeSettingsUpdateParameters l7 health probe settings for a backend pool +type HealthProbeSettingsUpdateParameters struct { + // Path - The path to use for the health probe. Default is / + Path *string `json:"path,omitempty"` + // Protocol - Protocol scheme to use for this probe. Possible values include: 'HTTP', 'HTTPS' + Protocol Protocol `json:"protocol,omitempty"` + // IntervalInSeconds - The number of seconds between health probes. + IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` +} + +// KeyVaultCertificateSourceParameters parameters required for bring-your-own-certification via Key Vault +type KeyVaultCertificateSourceParameters struct { + // Vault - The Key Vault containing the SSL certificate + Vault *KeyVaultCertificateSourceParametersVault `json:"vault,omitempty"` + // SecretName - The name of the Key Vault secret representing the full certificate PFX + SecretName *string `json:"secretName,omitempty"` + // SecretVersion - The version of the Key Vault secret representing the full certificate PFX + SecretVersion *string `json:"secretVersion,omitempty"` +} + +// KeyVaultCertificateSourceParametersVault the Key Vault containing the SSL certificate +type KeyVaultCertificateSourceParametersVault struct { + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// ListResult result of the request to list Front Doors. It contains a list of Front Door objects and a URL +// link to get the next set of results. +type ListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of Front Doors within a resource group. + Value *[]FrontDoor `json:"value,omitempty"` + // NextLink - URL to get the next set of Front Door objects if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// ListResultIterator provides access to a complete listing of FrontDoor values. +type ListResultIterator struct { + i int + page ListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ListResultIterator) Response() ListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ListResultIterator) Value() FrontDoor { + if !iter.page.NotDone() { + return FrontDoor{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ListResultIterator type. +func NewListResultIterator(page ListResultPage) ListResultIterator { + return ListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (lr ListResult) IsEmpty() bool { + return lr.Value == nil || len(*lr.Value) == 0 +} + +// listResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lr ListResult) listResultPreparer(ctx context.Context) (*http.Request, error) { + if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lr.NextLink))) +} + +// ListResultPage contains a page of FrontDoor values. +type ListResultPage struct { + fn func(context.Context, ListResult) (ListResult, error) + lr ListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.lr) + if err != nil { + return err + } + page.lr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ListResultPage) NotDone() bool { + return !page.lr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ListResultPage) Response() ListResult { + return page.lr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ListResultPage) Values() []FrontDoor { + if page.lr.IsEmpty() { + return nil + } + return *page.lr.Value +} + +// Creates a new instance of the ListResultPage type. +func NewListResultPage(getNextPage func(context.Context, ListResult) (ListResult, error)) ListResultPage { + return ListResultPage{fn: getNextPage} +} + +// LoadBalancingSettingsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type LoadBalancingSettingsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LoadBalancingSettingsCreateOrUpdateFuture) Result(client LoadBalancingSettingsClient) (lbsm LoadBalancingSettingsModel, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.LoadBalancingSettingsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if lbsm.Response.Response, err = future.GetResult(sender); err == nil && lbsm.Response.Response.StatusCode != http.StatusNoContent { + lbsm, err = client.CreateOrUpdateResponder(lbsm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsCreateOrUpdateFuture", "Result", lbsm.Response.Response, "Failure responding to request") + } + } + return +} + +// LoadBalancingSettingsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type LoadBalancingSettingsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LoadBalancingSettingsDeleteFuture) Result(client LoadBalancingSettingsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.LoadBalancingSettingsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.LoadBalancingSettingsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// LoadBalancingSettingsListResult result of the request to list load balancing settings. It contains a +// list of load balancing settings objects and a URL link to get the next set of results. +type LoadBalancingSettingsListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of Backend Pools within a Front Door. + Value *[]LoadBalancingSettingsModel `json:"value,omitempty"` + // NextLink - URL to get the next set of LoadBalancingSettings objects if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// LoadBalancingSettingsListResultIterator provides access to a complete listing of +// LoadBalancingSettingsModel values. +type LoadBalancingSettingsListResultIterator struct { + i int + page LoadBalancingSettingsListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *LoadBalancingSettingsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *LoadBalancingSettingsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter LoadBalancingSettingsListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter LoadBalancingSettingsListResultIterator) Response() LoadBalancingSettingsListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter LoadBalancingSettingsListResultIterator) Value() LoadBalancingSettingsModel { + if !iter.page.NotDone() { + return LoadBalancingSettingsModel{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the LoadBalancingSettingsListResultIterator type. +func NewLoadBalancingSettingsListResultIterator(page LoadBalancingSettingsListResultPage) LoadBalancingSettingsListResultIterator { + return LoadBalancingSettingsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (lbslr LoadBalancingSettingsListResult) IsEmpty() bool { + return lbslr.Value == nil || len(*lbslr.Value) == 0 +} + +// loadBalancingSettingsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lbslr LoadBalancingSettingsListResult) loadBalancingSettingsListResultPreparer(ctx context.Context) (*http.Request, error) { + if lbslr.NextLink == nil || len(to.String(lbslr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lbslr.NextLink))) +} + +// LoadBalancingSettingsListResultPage contains a page of LoadBalancingSettingsModel values. +type LoadBalancingSettingsListResultPage struct { + fn func(context.Context, LoadBalancingSettingsListResult) (LoadBalancingSettingsListResult, error) + lbslr LoadBalancingSettingsListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *LoadBalancingSettingsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LoadBalancingSettingsListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.lbslr) + if err != nil { + return err + } + page.lbslr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *LoadBalancingSettingsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page LoadBalancingSettingsListResultPage) NotDone() bool { + return !page.lbslr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page LoadBalancingSettingsListResultPage) Response() LoadBalancingSettingsListResult { + return page.lbslr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page LoadBalancingSettingsListResultPage) Values() []LoadBalancingSettingsModel { + if page.lbslr.IsEmpty() { + return nil + } + return *page.lbslr.Value +} + +// Creates a new instance of the LoadBalancingSettingsListResultPage type. +func NewLoadBalancingSettingsListResultPage(getNextPage func(context.Context, LoadBalancingSettingsListResult) (LoadBalancingSettingsListResult, error)) LoadBalancingSettingsListResultPage { + return LoadBalancingSettingsListResultPage{fn: getNextPage} +} + +// LoadBalancingSettingsModel load balancing settings for a backend pool +type LoadBalancingSettingsModel struct { + autorest.Response `json:"-"` + // LoadBalancingSettingsProperties - Properties of the load balancing settings + *LoadBalancingSettingsProperties `json:"properties,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// MarshalJSON is the custom marshaler for LoadBalancingSettingsModel. +func (lbsm LoadBalancingSettingsModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lbsm.LoadBalancingSettingsProperties != nil { + objectMap["properties"] = lbsm.LoadBalancingSettingsProperties + } + if lbsm.Name != nil { + objectMap["name"] = lbsm.Name + } + if lbsm.ID != nil { + objectMap["id"] = lbsm.ID + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LoadBalancingSettingsModel struct. +func (lbsm *LoadBalancingSettingsModel) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var loadBalancingSettingsProperties LoadBalancingSettingsProperties + err = json.Unmarshal(*v, &loadBalancingSettingsProperties) + if err != nil { + return err + } + lbsm.LoadBalancingSettingsProperties = &loadBalancingSettingsProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + lbsm.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + lbsm.Type = &typeVar + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + lbsm.ID = &ID + } + } + } + + return nil +} + +// LoadBalancingSettingsProperties the JSON object that contains the properties required to create load +// balancing settings +type LoadBalancingSettingsProperties struct { + // ResourceState - Resource status. Possible values include: 'ResourceStateCreating', 'ResourceStateEnabling', 'ResourceStateEnabled', 'ResourceStateDisabling', 'ResourceStateDisabled', 'ResourceStateDeleting' + ResourceState ResourceState `json:"resourceState,omitempty"` + // SampleSize - The number of samples to consider for load balancing decisions + SampleSize *int32 `json:"sampleSize,omitempty"` + // SuccessfulSamplesRequired - The number of samples within the sample period that must succeed + SuccessfulSamplesRequired *int32 `json:"successfulSamplesRequired,omitempty"` + // AdditionalLatencyMilliseconds - The additional latency in milliseconds for probes to fall into the lowest latency bucket + AdditionalLatencyMilliseconds *int32 `json:"additionalLatencyMilliseconds,omitempty"` +} + +// LoadBalancingSettingsUpdateParameters round-Robin load balancing settings for a backend pool +type LoadBalancingSettingsUpdateParameters struct { + // SampleSize - The number of samples to consider for load balancing decisions + SampleSize *int32 `json:"sampleSize,omitempty"` + // SuccessfulSamplesRequired - The number of samples within the sample period that must succeed + SuccessfulSamplesRequired *int32 `json:"successfulSamplesRequired,omitempty"` + // AdditionalLatencyMilliseconds - The additional latency in milliseconds for probes to fall into the lowest latency bucket + AdditionalLatencyMilliseconds *int32 `json:"additionalLatencyMilliseconds,omitempty"` +} + +// ManagedRuleDefinition describes a managed rule definition. +type ManagedRuleDefinition struct { + // RuleID - READ-ONLY; Identifier for the managed rule. + RuleID *string `json:"ruleId,omitempty"` + // Description - READ-ONLY; Describes the functionality of the managed rule. + Description *string `json:"description,omitempty"` +} + +// ManagedRuleGroupDefinition describes a managed rule group. +type ManagedRuleGroupDefinition struct { + // RuleGroupName - READ-ONLY; Name of the managed rule group. + RuleGroupName *string `json:"ruleGroupName,omitempty"` + // Description - READ-ONLY; Description of the managed rule group. + Description *string `json:"description,omitempty"` + // Rules - READ-ONLY; List of rules within the managed rule group. + Rules *[]ManagedRuleDefinition `json:"rules,omitempty"` +} + +// ManagedRuleGroupOverride defines a managed rule group override setting. +type ManagedRuleGroupOverride struct { + // RuleGroupName - Describes the managed rule group to override. + RuleGroupName *string `json:"ruleGroupName,omitempty"` + // Rules - List of rules that will be disabled. If none specified, all rules in the group will be disabled. + Rules *[]ManagedRuleOverride `json:"rules,omitempty"` +} + +// ManagedRuleOverride defines a managed rule group override setting. +type ManagedRuleOverride struct { + // RuleID - Identifier for the managed rule. + RuleID *string `json:"ruleId,omitempty"` + // EnabledState - Describes if the managed rule is in enabled or disabled state. Defaults to Disabled if not specified. Possible values include: 'ManagedRuleEnabledStateDisabled', 'ManagedRuleEnabledStateEnabled' + EnabledState ManagedRuleEnabledState `json:"enabledState,omitempty"` + // Action - Describes the override action to be applied when rule matches. Possible values include: 'Allow', 'Block', 'Log', 'Redirect' + Action ActionType `json:"action,omitempty"` +} + +// ManagedRuleSet defines a managed rule set. +type ManagedRuleSet struct { + // RuleSetType - Defines the rule set type to use. + RuleSetType *string `json:"ruleSetType,omitempty"` + // RuleSetVersion - Defines the version of the rule set to use. + RuleSetVersion *string `json:"ruleSetVersion,omitempty"` + // RuleGroupOverrides - Defines the rule group overrides to apply to the rule set. + RuleGroupOverrides *[]ManagedRuleGroupOverride `json:"ruleGroupOverrides,omitempty"` +} + +// ManagedRuleSetDefinition describes the a managed rule set definition. +type ManagedRuleSetDefinition struct { + *ManagedRuleSetDefinitionProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ManagedRuleSetDefinition. +func (mrsd ManagedRuleSetDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mrsd.ManagedRuleSetDefinitionProperties != nil { + objectMap["properties"] = mrsd.ManagedRuleSetDefinitionProperties + } + if mrsd.Location != nil { + objectMap["location"] = mrsd.Location + } + if mrsd.Tags != nil { + objectMap["tags"] = mrsd.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ManagedRuleSetDefinition struct. +func (mrsd *ManagedRuleSetDefinition) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var managedRuleSetDefinitionProperties ManagedRuleSetDefinitionProperties + err = json.Unmarshal(*v, &managedRuleSetDefinitionProperties) + if err != nil { + return err + } + mrsd.ManagedRuleSetDefinitionProperties = &managedRuleSetDefinitionProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + mrsd.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + mrsd.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + mrsd.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + mrsd.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + mrsd.Tags = tags + } + } + } + + return nil +} + +// ManagedRuleSetDefinitionList list of managed rule set definitions available for use in a policy. +type ManagedRuleSetDefinitionList struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of managed rule set definitions. + Value *[]ManagedRuleSetDefinition `json:"value,omitempty"` + // NextLink - URL to retrieve next set of managed rule set definitions. + NextLink *string `json:"nextLink,omitempty"` +} + +// ManagedRuleSetDefinitionListIterator provides access to a complete listing of ManagedRuleSetDefinition +// values. +type ManagedRuleSetDefinitionListIterator struct { + i int + page ManagedRuleSetDefinitionListPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ManagedRuleSetDefinitionListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedRuleSetDefinitionListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ManagedRuleSetDefinitionListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ManagedRuleSetDefinitionListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ManagedRuleSetDefinitionListIterator) Response() ManagedRuleSetDefinitionList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ManagedRuleSetDefinitionListIterator) Value() ManagedRuleSetDefinition { + if !iter.page.NotDone() { + return ManagedRuleSetDefinition{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ManagedRuleSetDefinitionListIterator type. +func NewManagedRuleSetDefinitionListIterator(page ManagedRuleSetDefinitionListPage) ManagedRuleSetDefinitionListIterator { + return ManagedRuleSetDefinitionListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (mrsdl ManagedRuleSetDefinitionList) IsEmpty() bool { + return mrsdl.Value == nil || len(*mrsdl.Value) == 0 +} + +// managedRuleSetDefinitionListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (mrsdl ManagedRuleSetDefinitionList) managedRuleSetDefinitionListPreparer(ctx context.Context) (*http.Request, error) { + if mrsdl.NextLink == nil || len(to.String(mrsdl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(mrsdl.NextLink))) +} + +// ManagedRuleSetDefinitionListPage contains a page of ManagedRuleSetDefinition values. +type ManagedRuleSetDefinitionListPage struct { + fn func(context.Context, ManagedRuleSetDefinitionList) (ManagedRuleSetDefinitionList, error) + mrsdl ManagedRuleSetDefinitionList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ManagedRuleSetDefinitionListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ManagedRuleSetDefinitionListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.mrsdl) + if err != nil { + return err + } + page.mrsdl = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ManagedRuleSetDefinitionListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ManagedRuleSetDefinitionListPage) NotDone() bool { + return !page.mrsdl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ManagedRuleSetDefinitionListPage) Response() ManagedRuleSetDefinitionList { + return page.mrsdl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ManagedRuleSetDefinitionListPage) Values() []ManagedRuleSetDefinition { + if page.mrsdl.IsEmpty() { + return nil + } + return *page.mrsdl.Value +} + +// Creates a new instance of the ManagedRuleSetDefinitionListPage type. +func NewManagedRuleSetDefinitionListPage(getNextPage func(context.Context, ManagedRuleSetDefinitionList) (ManagedRuleSetDefinitionList, error)) ManagedRuleSetDefinitionListPage { + return ManagedRuleSetDefinitionListPage{fn: getNextPage} +} + +// ManagedRuleSetDefinitionProperties properties for a managed rule set definition. +type ManagedRuleSetDefinitionProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state of the managed rule set. + ProvisioningState *string `json:"provisioningState,omitempty"` + // RuleSetType - READ-ONLY; Type of the managed rule set. + RuleSetType *string `json:"ruleSetType,omitempty"` + // RuleSetVersion - READ-ONLY; Version of the managed rule set type. + RuleSetVersion *string `json:"ruleSetVersion,omitempty"` + // RuleGroups - READ-ONLY; Rule groups of the managed rule set. + RuleGroups *[]ManagedRuleGroupDefinition `json:"ruleGroups,omitempty"` +} + +// ManagedRuleSetList defines the list of managed rule sets for the policy. +type ManagedRuleSetList struct { + // ManagedRuleSets - List of rule sets. + ManagedRuleSets *[]ManagedRuleSet `json:"managedRuleSets,omitempty"` +} + +// MatchCondition define a match condition. +type MatchCondition struct { + // MatchVariable - Match variable to compare against. Possible values include: 'RemoteAddr', 'RequestMethod', 'QueryString', 'PostArgs', 'RequestURI', 'RequestHeader', 'RequestBody', 'Cookies' + MatchVariable MatchVariable `json:"matchVariable,omitempty"` + // Selector - Selector can used to match against a specific key from QueryString, PostArgs, RequestHeader or Cookies. + Selector *string `json:"selector,omitempty"` + // Operator - Describes operator to be matched. Possible values include: 'Any', 'IPMatch', 'GeoMatch', 'Equal', 'Contains', 'LessThan', 'GreaterThan', 'LessThanOrEqual', 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith', 'RegEx' + Operator Operator `json:"operator,omitempty"` + // NegateCondition - Describes if the result of this condition should be negated. + NegateCondition *bool `json:"negateCondition,omitempty"` + // MatchValue - List of possible match values. + MatchValue *[]string `json:"matchValue,omitempty"` + // Transforms - List of transforms. + Transforms *[]TransformType `json:"transforms,omitempty"` +} + +// PoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type PoliciesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PoliciesCreateOrUpdateFuture) Result(client PoliciesClient) (wafp WebApplicationFirewallPolicy, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.PoliciesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if wafp.Response.Response, err = future.GetResult(sender); err == nil && wafp.Response.Response.StatusCode != http.StatusNoContent { + wafp, err = client.CreateOrUpdateResponder(wafp.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesCreateOrUpdateFuture", "Result", wafp.Response.Response, "Failure responding to request") + } + } + return +} + +// PoliciesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type PoliciesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PoliciesDeleteFuture) Result(client PoliciesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.PoliciesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PolicySettings defines top-level WebApplicationFirewallPolicy configuration settings. +type PolicySettings struct { + // EnabledState - Describes if the policy is in enabled or disabled state. Defaults to Enabled if not specified. Possible values include: 'PolicyEnabledStateDisabled', 'PolicyEnabledStateEnabled' + EnabledState PolicyEnabledState `json:"enabledState,omitempty"` + // Mode - Describes if it is in detection mode or prevention mode at policy level. Possible values include: 'Prevention', 'Detection' + Mode PolicyMode `json:"mode,omitempty"` + // RedirectURL - If action type is redirect, this field represents redirect URL for the client. + RedirectURL *string `json:"redirectUrl,omitempty"` + // CustomBlockResponseStatusCode - If the action type is block, customer can override the response status code. + CustomBlockResponseStatusCode *int32 `json:"customBlockResponseStatusCode,omitempty"` + // CustomBlockResponseBody - If the action type is block, customer can override the response body. The body must be specified in base64 encoding. + CustomBlockResponseBody *string `json:"customBlockResponseBody,omitempty"` +} + +// Properties the JSON object that contains the properties required to create an endpoint. +type Properties struct { + // ResourceState - Resource status of the Front Door. Possible values include: 'ResourceStateCreating', 'ResourceStateEnabling', 'ResourceStateEnabled', 'ResourceStateDisabling', 'ResourceStateDisabled', 'ResourceStateDeleting' + ResourceState ResourceState `json:"resourceState,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the Front Door. + ProvisioningState *string `json:"provisioningState,omitempty"` + // Cname - READ-ONLY; The host that each frontendEndpoint must CNAME to. + Cname *string `json:"cname,omitempty"` + // FriendlyName - A friendly name for the frontDoor + FriendlyName *string `json:"friendlyName,omitempty"` + // RoutingRules - Routing rules associated with this Front Door. + RoutingRules *[]RoutingRule `json:"routingRules,omitempty"` + // LoadBalancingSettings - Load balancing settings associated with this Front Door instance. + LoadBalancingSettings *[]LoadBalancingSettingsModel `json:"loadBalancingSettings,omitempty"` + // HealthProbeSettings - Health probe settings associated with this Front Door instance. + HealthProbeSettings *[]HealthProbeSettingsModel `json:"healthProbeSettings,omitempty"` + // BackendPools - Backend pools available to routing rules. + BackendPools *[]BackendPool `json:"backendPools,omitempty"` + // FrontendEndpoints - Frontend endpoints available to routing rules. + FrontendEndpoints *[]FrontendEndpoint `json:"frontendEndpoints,omitempty"` + // BackendPoolsSettings - Settings for all backendPools + BackendPoolsSettings *BackendPoolsSettings `json:"backendPoolsSettings,omitempty"` + // EnabledState - Operational status of the Front Door load balancer. Permitted values are 'Enabled' or 'Disabled'. Possible values include: 'EnabledStateEnabled', 'EnabledStateDisabled' + EnabledState EnabledState `json:"enabledState,omitempty"` +} + +// PurgeParameters parameters required for content purge. +type PurgeParameters struct { + // ContentPaths - The path to the content to be purged. Can describe a file path or a wild card directory. + ContentPaths *[]string `json:"contentPaths,omitempty"` +} + +// RedirectConfiguration describes Redirect Route. +type RedirectConfiguration struct { + // RedirectType - The redirect type the rule will use when redirecting traffic. Possible values include: 'Moved', 'Found', 'TemporaryRedirect', 'PermanentRedirect' + RedirectType RedirectType `json:"redirectType,omitempty"` + // RedirectProtocol - The protocol of the destination to where the traffic is redirected. Possible values include: 'RedirectProtocolHTTPOnly', 'RedirectProtocolHTTPSOnly', 'RedirectProtocolMatchRequest' + RedirectProtocol RedirectProtocol `json:"redirectProtocol,omitempty"` + // CustomHost - Host to redirect. Leave empty to use the incoming host as the destination host. + CustomHost *string `json:"customHost,omitempty"` + // CustomPath - The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the incoming path as destination path. + CustomPath *string `json:"customPath,omitempty"` + // CustomFragment - Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do not include the #. + CustomFragment *string `json:"customFragment,omitempty"` + // CustomQueryString - The set of query strings to be placed in the redirect URL. Setting this value would replace any existing query string; leave empty to preserve the incoming query string. Query string must be in = format. The first ? and & will be added automatically so do not include them in the front, but do separate multiple query strings with &. + CustomQueryString *string `json:"customQueryString,omitempty"` + // OdataType - Possible values include: 'OdataTypeRouteConfiguration', 'OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration', 'OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration' + OdataType OdataType `json:"@odata.type,omitempty"` +} + +// MarshalJSON is the custom marshaler for RedirectConfiguration. +func (rc RedirectConfiguration) MarshalJSON() ([]byte, error) { + rc.OdataType = OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration + objectMap := make(map[string]interface{}) + if rc.RedirectType != "" { + objectMap["redirectType"] = rc.RedirectType + } + if rc.RedirectProtocol != "" { + objectMap["redirectProtocol"] = rc.RedirectProtocol + } + if rc.CustomHost != nil { + objectMap["customHost"] = rc.CustomHost + } + if rc.CustomPath != nil { + objectMap["customPath"] = rc.CustomPath + } + if rc.CustomFragment != nil { + objectMap["customFragment"] = rc.CustomFragment + } + if rc.CustomQueryString != nil { + objectMap["customQueryString"] = rc.CustomQueryString + } + if rc.OdataType != "" { + objectMap["@odata.type"] = rc.OdataType + } + return json.Marshal(objectMap) +} + +// AsForwardingConfiguration is the BasicRouteConfiguration implementation for RedirectConfiguration. +func (rc RedirectConfiguration) AsForwardingConfiguration() (*ForwardingConfiguration, bool) { + return nil, false +} + +// AsRedirectConfiguration is the BasicRouteConfiguration implementation for RedirectConfiguration. +func (rc RedirectConfiguration) AsRedirectConfiguration() (*RedirectConfiguration, bool) { + return &rc, true +} + +// AsRouteConfiguration is the BasicRouteConfiguration implementation for RedirectConfiguration. +func (rc RedirectConfiguration) AsRouteConfiguration() (*RouteConfiguration, bool) { + return nil, false +} + +// AsBasicRouteConfiguration is the BasicRouteConfiguration implementation for RedirectConfiguration. +func (rc RedirectConfiguration) AsBasicRouteConfiguration() (BasicRouteConfiguration, bool) { + return &rc, true +} + +// Resource common resource representation. +type Resource struct { + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if r.Location != nil { + objectMap["location"] = r.Location + } + if r.Tags != nil { + objectMap["tags"] = r.Tags + } + return json.Marshal(objectMap) +} + +// BasicRouteConfiguration base class for all types of Route. +type BasicRouteConfiguration interface { + AsForwardingConfiguration() (*ForwardingConfiguration, bool) + AsRedirectConfiguration() (*RedirectConfiguration, bool) + AsRouteConfiguration() (*RouteConfiguration, bool) +} + +// RouteConfiguration base class for all types of Route. +type RouteConfiguration struct { + // OdataType - Possible values include: 'OdataTypeRouteConfiguration', 'OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration', 'OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration' + OdataType OdataType `json:"@odata.type,omitempty"` +} + +func unmarshalBasicRouteConfiguration(body []byte) (BasicRouteConfiguration, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["@odata.type"] { + case string(OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration): + var fc ForwardingConfiguration + err := json.Unmarshal(body, &fc) + return fc, err + case string(OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration): + var rc RedirectConfiguration + err := json.Unmarshal(body, &rc) + return rc, err + default: + var rc RouteConfiguration + err := json.Unmarshal(body, &rc) + return rc, err + } +} +func unmarshalBasicRouteConfigurationArray(body []byte) ([]BasicRouteConfiguration, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + rcArray := make([]BasicRouteConfiguration, len(rawMessages)) + + for index, rawMessage := range rawMessages { + rc, err := unmarshalBasicRouteConfiguration(*rawMessage) + if err != nil { + return nil, err + } + rcArray[index] = rc + } + return rcArray, nil +} + +// MarshalJSON is the custom marshaler for RouteConfiguration. +func (rc RouteConfiguration) MarshalJSON() ([]byte, error) { + rc.OdataType = OdataTypeRouteConfiguration + objectMap := make(map[string]interface{}) + if rc.OdataType != "" { + objectMap["@odata.type"] = rc.OdataType + } + return json.Marshal(objectMap) +} + +// AsForwardingConfiguration is the BasicRouteConfiguration implementation for RouteConfiguration. +func (rc RouteConfiguration) AsForwardingConfiguration() (*ForwardingConfiguration, bool) { + return nil, false +} + +// AsRedirectConfiguration is the BasicRouteConfiguration implementation for RouteConfiguration. +func (rc RouteConfiguration) AsRedirectConfiguration() (*RedirectConfiguration, bool) { + return nil, false +} + +// AsRouteConfiguration is the BasicRouteConfiguration implementation for RouteConfiguration. +func (rc RouteConfiguration) AsRouteConfiguration() (*RouteConfiguration, bool) { + return &rc, true +} + +// AsBasicRouteConfiguration is the BasicRouteConfiguration implementation for RouteConfiguration. +func (rc RouteConfiguration) AsBasicRouteConfiguration() (BasicRouteConfiguration, bool) { + return &rc, true +} + +// RoutingRule a routing rule represents a specification for traffic to treat and where to send it, along +// with health probe information. +type RoutingRule struct { + autorest.Response `json:"-"` + // RoutingRuleProperties - Properties of the Front Door Routing Rule + *RoutingRuleProperties `json:"properties,omitempty"` + // Name - Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// MarshalJSON is the custom marshaler for RoutingRule. +func (rr RoutingRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if rr.RoutingRuleProperties != nil { + objectMap["properties"] = rr.RoutingRuleProperties + } + if rr.Name != nil { + objectMap["name"] = rr.Name + } + if rr.ID != nil { + objectMap["id"] = rr.ID + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for RoutingRule struct. +func (rr *RoutingRule) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var routingRuleProperties RoutingRuleProperties + err = json.Unmarshal(*v, &routingRuleProperties) + if err != nil { + return err + } + rr.RoutingRuleProperties = &routingRuleProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + rr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + rr.Type = &typeVar + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + rr.ID = &ID + } + } + } + + return nil +} + +// RoutingRuleListResult result of the request to list Routing Rules. It contains a list of Routing Rule +// objects and a URL link to get the next set of results. +type RoutingRuleListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of Routing Rules within a Front Door. + Value *[]RoutingRule `json:"value,omitempty"` + // NextLink - URL to get the next set of RoutingRule objects if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// RoutingRuleListResultIterator provides access to a complete listing of RoutingRule values. +type RoutingRuleListResultIterator struct { + i int + page RoutingRuleListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *RoutingRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRuleListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *RoutingRuleListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter RoutingRuleListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter RoutingRuleListResultIterator) Response() RoutingRuleListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter RoutingRuleListResultIterator) Value() RoutingRule { + if !iter.page.NotDone() { + return RoutingRule{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the RoutingRuleListResultIterator type. +func NewRoutingRuleListResultIterator(page RoutingRuleListResultPage) RoutingRuleListResultIterator { + return RoutingRuleListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (rrlr RoutingRuleListResult) IsEmpty() bool { + return rrlr.Value == nil || len(*rrlr.Value) == 0 +} + +// routingRuleListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (rrlr RoutingRuleListResult) routingRuleListResultPreparer(ctx context.Context) (*http.Request, error) { + if rrlr.NextLink == nil || len(to.String(rrlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(rrlr.NextLink))) +} + +// RoutingRuleListResultPage contains a page of RoutingRule values. +type RoutingRuleListResultPage struct { + fn func(context.Context, RoutingRuleListResult) (RoutingRuleListResult, error) + rrlr RoutingRuleListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *RoutingRuleListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRuleListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.rrlr) + if err != nil { + return err + } + page.rrlr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *RoutingRuleListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page RoutingRuleListResultPage) NotDone() bool { + return !page.rrlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page RoutingRuleListResultPage) Response() RoutingRuleListResult { + return page.rrlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page RoutingRuleListResultPage) Values() []RoutingRule { + if page.rrlr.IsEmpty() { + return nil + } + return *page.rrlr.Value +} + +// Creates a new instance of the RoutingRuleListResultPage type. +func NewRoutingRuleListResultPage(getNextPage func(context.Context, RoutingRuleListResult) (RoutingRuleListResult, error)) RoutingRuleListResultPage { + return RoutingRuleListResultPage{fn: getNextPage} +} + +// RoutingRuleProperties the JSON object that contains the properties required to create a routing rule. +type RoutingRuleProperties struct { + // ResourceState - Resource status. Possible values include: 'ResourceStateCreating', 'ResourceStateEnabling', 'ResourceStateEnabled', 'ResourceStateDisabling', 'ResourceStateDisabled', 'ResourceStateDeleting' + ResourceState ResourceState `json:"resourceState,omitempty"` + // FrontendEndpoints - Frontend endpoints associated with this rule + FrontendEndpoints *[]SubResource `json:"frontendEndpoints,omitempty"` + // AcceptedProtocols - Protocol schemes to match for this rule + AcceptedProtocols *[]Protocol `json:"acceptedProtocols,omitempty"` + // PatternsToMatch - The route patterns of the rule. + PatternsToMatch *[]string `json:"patternsToMatch,omitempty"` + // EnabledState - Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'. Possible values include: 'RoutingRuleEnabledStateEnabled', 'RoutingRuleEnabledStateDisabled' + EnabledState RoutingRuleEnabledState `json:"enabledState,omitempty"` + // RouteConfiguration - A reference to the routing configuration. + RouteConfiguration BasicRouteConfiguration `json:"routeConfiguration,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for RoutingRuleProperties struct. +func (rrp *RoutingRuleProperties) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "resourceState": + if v != nil { + var resourceState ResourceState + err = json.Unmarshal(*v, &resourceState) + if err != nil { + return err + } + rrp.ResourceState = resourceState + } + case "frontendEndpoints": + if v != nil { + var frontendEndpoints []SubResource + err = json.Unmarshal(*v, &frontendEndpoints) + if err != nil { + return err + } + rrp.FrontendEndpoints = &frontendEndpoints + } + case "acceptedProtocols": + if v != nil { + var acceptedProtocols []Protocol + err = json.Unmarshal(*v, &acceptedProtocols) + if err != nil { + return err + } + rrp.AcceptedProtocols = &acceptedProtocols + } + case "patternsToMatch": + if v != nil { + var patternsToMatch []string + err = json.Unmarshal(*v, &patternsToMatch) + if err != nil { + return err + } + rrp.PatternsToMatch = &patternsToMatch + } + case "enabledState": + if v != nil { + var enabledState RoutingRuleEnabledState + err = json.Unmarshal(*v, &enabledState) + if err != nil { + return err + } + rrp.EnabledState = enabledState + } + case "routeConfiguration": + if v != nil { + routeConfiguration, err := unmarshalBasicRouteConfiguration(*v) + if err != nil { + return err + } + rrp.RouteConfiguration = routeConfiguration + } + } + } + + return nil +} + +// RoutingRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type RoutingRulesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *RoutingRulesCreateOrUpdateFuture) Result(client RoutingRulesClient) (rr RoutingRule, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.RoutingRulesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if rr.Response.Response, err = future.GetResult(sender); err == nil && rr.Response.Response.StatusCode != http.StatusNoContent { + rr, err = client.CreateOrUpdateResponder(rr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesCreateOrUpdateFuture", "Result", rr.Response.Response, "Failure responding to request") + } + } + return +} + +// RoutingRulesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type RoutingRulesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *RoutingRulesDeleteFuture) Result(client RoutingRulesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("frontdoor.RoutingRulesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// RoutingRuleUpdateParameters routing rules to apply to an endpoint +type RoutingRuleUpdateParameters struct { + // FrontendEndpoints - Frontend endpoints associated with this rule + FrontendEndpoints *[]SubResource `json:"frontendEndpoints,omitempty"` + // AcceptedProtocols - Protocol schemes to match for this rule + AcceptedProtocols *[]Protocol `json:"acceptedProtocols,omitempty"` + // PatternsToMatch - The route patterns of the rule. + PatternsToMatch *[]string `json:"patternsToMatch,omitempty"` + // EnabledState - Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'. Possible values include: 'RoutingRuleEnabledStateEnabled', 'RoutingRuleEnabledStateDisabled' + EnabledState RoutingRuleEnabledState `json:"enabledState,omitempty"` + // RouteConfiguration - A reference to the routing configuration. + RouteConfiguration BasicRouteConfiguration `json:"routeConfiguration,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for RoutingRuleUpdateParameters struct. +func (rrup *RoutingRuleUpdateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "frontendEndpoints": + if v != nil { + var frontendEndpoints []SubResource + err = json.Unmarshal(*v, &frontendEndpoints) + if err != nil { + return err + } + rrup.FrontendEndpoints = &frontendEndpoints + } + case "acceptedProtocols": + if v != nil { + var acceptedProtocols []Protocol + err = json.Unmarshal(*v, &acceptedProtocols) + if err != nil { + return err + } + rrup.AcceptedProtocols = &acceptedProtocols + } + case "patternsToMatch": + if v != nil { + var patternsToMatch []string + err = json.Unmarshal(*v, &patternsToMatch) + if err != nil { + return err + } + rrup.PatternsToMatch = &patternsToMatch + } + case "enabledState": + if v != nil { + var enabledState RoutingRuleEnabledState + err = json.Unmarshal(*v, &enabledState) + if err != nil { + return err + } + rrup.EnabledState = enabledState + } + case "routeConfiguration": + if v != nil { + routeConfiguration, err := unmarshalBasicRouteConfiguration(*v) + if err != nil { + return err + } + rrup.RouteConfiguration = routeConfiguration + } + } + } + + return nil +} + +// SubResource reference to another subresource. +type SubResource struct { + // ID - Resource ID. + ID *string `json:"id,omitempty"` +} + +// TagsObject tags object for patch operations. +type TagsObject struct { + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for TagsObject. +func (toVar TagsObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if toVar.Tags != nil { + objectMap["tags"] = toVar.Tags + } + return json.Marshal(objectMap) +} + +// UpdateParameters the properties needed to update a Front Door +type UpdateParameters struct { + // FriendlyName - A friendly name for the frontDoor + FriendlyName *string `json:"friendlyName,omitempty"` + // RoutingRules - Routing rules associated with this Front Door. + RoutingRules *[]RoutingRule `json:"routingRules,omitempty"` + // LoadBalancingSettings - Load balancing settings associated with this Front Door instance. + LoadBalancingSettings *[]LoadBalancingSettingsModel `json:"loadBalancingSettings,omitempty"` + // HealthProbeSettings - Health probe settings associated with this Front Door instance. + HealthProbeSettings *[]HealthProbeSettingsModel `json:"healthProbeSettings,omitempty"` + // BackendPools - Backend pools available to routing rules. + BackendPools *[]BackendPool `json:"backendPools,omitempty"` + // FrontendEndpoints - Frontend endpoints available to routing rules. + FrontendEndpoints *[]FrontendEndpoint `json:"frontendEndpoints,omitempty"` + // BackendPoolsSettings - Settings for all backendPools + BackendPoolsSettings *BackendPoolsSettings `json:"backendPoolsSettings,omitempty"` + // EnabledState - Operational status of the Front Door load balancer. Permitted values are 'Enabled' or 'Disabled'. Possible values include: 'EnabledStateEnabled', 'EnabledStateDisabled' + EnabledState EnabledState `json:"enabledState,omitempty"` +} + +// ValidateCustomDomainInput input of the custom domain to be validated for DNS mapping. +type ValidateCustomDomainInput struct { + // HostName - The host name of the custom domain. Must be a domain name. + HostName *string `json:"hostName,omitempty"` +} + +// ValidateCustomDomainOutput output of custom domain validation. +type ValidateCustomDomainOutput struct { + autorest.Response `json:"-"` + // CustomDomainValidated - READ-ONLY; Indicates whether the custom domain is valid or not. + CustomDomainValidated *bool `json:"customDomainValidated,omitempty"` + // Reason - READ-ONLY; The reason why the custom domain is not valid. + Reason *string `json:"reason,omitempty"` + // Message - READ-ONLY; Error message describing why the custom domain is not valid. + Message *string `json:"message,omitempty"` +} + +// WebApplicationFirewallPolicy defines web application firewall policy. +type WebApplicationFirewallPolicy struct { + autorest.Response `json:"-"` + // WebApplicationFirewallPolicyProperties - Properties of the web application firewall policy. + *WebApplicationFirewallPolicyProperties `json:"properties,omitempty"` + // Etag - Gets a unique read-only string that changes whenever the resource is updated. + Etag *string `json:"etag,omitempty"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for WebApplicationFirewallPolicy. +func (wafp WebApplicationFirewallPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if wafp.WebApplicationFirewallPolicyProperties != nil { + objectMap["properties"] = wafp.WebApplicationFirewallPolicyProperties + } + if wafp.Etag != nil { + objectMap["etag"] = wafp.Etag + } + if wafp.Location != nil { + objectMap["location"] = wafp.Location + } + if wafp.Tags != nil { + objectMap["tags"] = wafp.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for WebApplicationFirewallPolicy struct. +func (wafp *WebApplicationFirewallPolicy) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var webApplicationFirewallPolicyProperties WebApplicationFirewallPolicyProperties + err = json.Unmarshal(*v, &webApplicationFirewallPolicyProperties) + if err != nil { + return err + } + wafp.WebApplicationFirewallPolicyProperties = &webApplicationFirewallPolicyProperties + } + case "etag": + if v != nil { + var etag string + err = json.Unmarshal(*v, &etag) + if err != nil { + return err + } + wafp.Etag = &etag + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + wafp.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + wafp.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + wafp.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + wafp.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + wafp.Tags = tags + } + } + } + + return nil +} + +// WebApplicationFirewallPolicyList defines a list of WebApplicationFirewallPolicies. It contains a list of +// WebApplicationFirewallPolicy objects and a URL link to get the next set of results. +type WebApplicationFirewallPolicyList struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; List of WebApplicationFirewallPolicies within a resource group. + Value *[]WebApplicationFirewallPolicy `json:"value,omitempty"` + // NextLink - URL to get the next set of WebApplicationFirewallPolicy objects if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// WebApplicationFirewallPolicyListIterator provides access to a complete listing of +// WebApplicationFirewallPolicy values. +type WebApplicationFirewallPolicyListIterator struct { + i int + page WebApplicationFirewallPolicyListPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *WebApplicationFirewallPolicyListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPolicyListIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *WebApplicationFirewallPolicyListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter WebApplicationFirewallPolicyListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter WebApplicationFirewallPolicyListIterator) Response() WebApplicationFirewallPolicyList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter WebApplicationFirewallPolicyListIterator) Value() WebApplicationFirewallPolicy { + if !iter.page.NotDone() { + return WebApplicationFirewallPolicy{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the WebApplicationFirewallPolicyListIterator type. +func NewWebApplicationFirewallPolicyListIterator(page WebApplicationFirewallPolicyListPage) WebApplicationFirewallPolicyListIterator { + return WebApplicationFirewallPolicyListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (wafpl WebApplicationFirewallPolicyList) IsEmpty() bool { + return wafpl.Value == nil || len(*wafpl.Value) == 0 +} + +// webApplicationFirewallPolicyListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (wafpl WebApplicationFirewallPolicyList) webApplicationFirewallPolicyListPreparer(ctx context.Context) (*http.Request, error) { + if wafpl.NextLink == nil || len(to.String(wafpl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(wafpl.NextLink))) +} + +// WebApplicationFirewallPolicyListPage contains a page of WebApplicationFirewallPolicy values. +type WebApplicationFirewallPolicyListPage struct { + fn func(context.Context, WebApplicationFirewallPolicyList) (WebApplicationFirewallPolicyList, error) + wafpl WebApplicationFirewallPolicyList +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *WebApplicationFirewallPolicyListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/WebApplicationFirewallPolicyListPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.wafpl) + if err != nil { + return err + } + page.wafpl = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *WebApplicationFirewallPolicyListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page WebApplicationFirewallPolicyListPage) NotDone() bool { + return !page.wafpl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page WebApplicationFirewallPolicyListPage) Response() WebApplicationFirewallPolicyList { + return page.wafpl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page WebApplicationFirewallPolicyListPage) Values() []WebApplicationFirewallPolicy { + if page.wafpl.IsEmpty() { + return nil + } + return *page.wafpl.Value +} + +// Creates a new instance of the WebApplicationFirewallPolicyListPage type. +func NewWebApplicationFirewallPolicyListPage(getNextPage func(context.Context, WebApplicationFirewallPolicyList) (WebApplicationFirewallPolicyList, error)) WebApplicationFirewallPolicyListPage { + return WebApplicationFirewallPolicyListPage{fn: getNextPage} +} + +// WebApplicationFirewallPolicyProperties defines web application firewall policy properties. +type WebApplicationFirewallPolicyProperties struct { + // PolicySettings - Describes settings for the policy. + PolicySettings *PolicySettings `json:"policySettings,omitempty"` + // CustomRules - Describes custom rules inside the policy. + CustomRules *CustomRuleList `json:"customRules,omitempty"` + // ManagedRules - Describes managed rules inside the policy. + ManagedRules *ManagedRuleSetList `json:"managedRules,omitempty"` + // FrontendEndpointLinks - READ-ONLY; Describes Frontend Endpoints associated with this Web Application Firewall policy. + FrontendEndpointLinks *[]FrontendEndpointLink `json:"frontendEndpointLinks,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the policy. + ProvisioningState *string `json:"provisioningState,omitempty"` + // ResourceState - READ-ONLY; Possible values include: 'PolicyResourceStateCreating', 'PolicyResourceStateEnabling', 'PolicyResourceStateEnabled', 'PolicyResourceStateDisabling', 'PolicyResourceStateDisabled', 'PolicyResourceStateDeleting' + ResourceState PolicyResourceState `json:"resourceState,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/policies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/policies.go new file mode 100644 index 000000000000..2c56a65c35d0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/policies.go @@ -0,0 +1,433 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// PoliciesClient is the frontDoor Client +type PoliciesClient struct { + BaseClient +} + +// NewPoliciesClient creates an instance of the PoliciesClient client. +func NewPoliciesClient(subscriptionID string) PoliciesClient { + return NewPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPoliciesClientWithBaseURI creates an instance of the PoliciesClient client. +func NewPoliciesClientWithBaseURI(baseURI string, subscriptionID string) PoliciesClient { + return PoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update policy with specified rule set name within a resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// policyName - the name of the Web Application Firewall Policy. +// parameters - policy to be created. +func (client PoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy) (result PoliciesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: policyName, + Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyProperties.PolicySettings", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyProperties.PolicySettings.CustomBlockResponseBody", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.WebApplicationFirewallPolicyProperties.PolicySettings.CustomBlockResponseBody", Name: validation.Pattern, Rule: `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`, Chain: nil}}}, + }}, + }}}}}); err != nil { + return result, validation.NewError("frontdoor.PoliciesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, policyName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, policyName string, parameters WebApplicationFirewallPolicy) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "policyName": autorest.Encode("path", policyName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/FrontDoorWebApplicationFirewallPolicies/{policyName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client PoliciesClient) CreateOrUpdateSender(req *http.Request) (future PoliciesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client PoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result WebApplicationFirewallPolicy, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes Policy +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// policyName - the name of the Web Application Firewall Policy. +func (client PoliciesClient) Delete(ctx context.Context, resourceGroupName string, policyName string) (result PoliciesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: policyName, + Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.PoliciesClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, policyName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, policyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "policyName": autorest.Encode("path", policyName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/FrontDoorWebApplicationFirewallPolicies/{policyName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client PoliciesClient) DeleteSender(req *http.Request) (future PoliciesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get retrieve protection policy with specified name within a resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// policyName - the name of the Web Application Firewall Policy. +func (client PoliciesClient) Get(ctx context.Context, resourceGroupName string, policyName string) (result WebApplicationFirewallPolicy, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: policyName, + Constraints: []validation.Constraint{{Target: "policyName", Name: validation.MaxLength, Rule: 128, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.PoliciesClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, policyName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, policyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "policyName": autorest.Encode("path", policyName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/FrontDoorWebApplicationFirewallPolicies/{policyName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client PoliciesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PoliciesClient) GetResponder(resp *http.Response) (result WebApplicationFirewallPolicy, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all of the protection policies within a resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +func (client PoliciesClient) List(ctx context.Context, resourceGroupName string) (result WebApplicationFirewallPolicyListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.List") + defer func() { + sc := -1 + if result.wafpl.Response.Response != nil { + sc = result.wafpl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.PoliciesClient", "List", err.Error()) + } + + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.wafpl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "List", resp, "Failure sending request") + return + } + + result.wafpl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client PoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/FrontDoorWebApplicationFirewallPolicies", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client PoliciesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PoliciesClient) ListResponder(resp *http.Response) (result WebApplicationFirewallPolicyList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client PoliciesClient) listNextResults(ctx context.Context, lastResults WebApplicationFirewallPolicyList) (result WebApplicationFirewallPolicyList, err error) { + req, err := lastResults.webApplicationFirewallPolicyListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.PoliciesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client PoliciesClient) ListComplete(ctx context.Context, resourceGroupName string) (result WebApplicationFirewallPolicyListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/routingrules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/routingrules.go new file mode 100644 index 000000000000..9911a7c69ab6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/routingrules.go @@ -0,0 +1,457 @@ +package frontdoor + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// RoutingRulesClient is the frontDoor Client +type RoutingRulesClient struct { + BaseClient +} + +// NewRoutingRulesClient creates an instance of the RoutingRulesClient client. +func NewRoutingRulesClient(subscriptionID string) RoutingRulesClient { + return NewRoutingRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRoutingRulesClientWithBaseURI creates an instance of the RoutingRulesClient client. +func NewRoutingRulesClientWithBaseURI(baseURI string, subscriptionID string) RoutingRulesClient { + return RoutingRulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new Routing Rule with the specified Rule name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// routingRuleName - name of the Routing Rule which is unique within the Front Door. +// routingRuleParameters - routing Rule properties needed to create a new Front Door. +func (client RoutingRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, frontDoorName string, routingRuleName string, routingRuleParameters RoutingRule) (result RoutingRulesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRulesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: routingRuleName, + Constraints: []validation.Constraint{{Target: "routingRuleName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "routingRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "routingRuleName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.RoutingRulesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, frontDoorName, routingRuleName, routingRuleParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RoutingRulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, routingRuleName string, routingRuleParameters RoutingRule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routingRuleName": autorest.Encode("path", routingRuleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + routingRuleParameters.Type = nil + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules/{routingRuleName}", pathParameters), + autorest.WithJSON(routingRuleParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client RoutingRulesClient) CreateOrUpdateSender(req *http.Request) (future RoutingRulesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client RoutingRulesClient) CreateOrUpdateResponder(resp *http.Response) (result RoutingRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing Routing Rule with the specified parameters. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// routingRuleName - name of the Routing Rule which is unique within the Front Door. +func (client RoutingRulesClient) Delete(ctx context.Context, resourceGroupName string, frontDoorName string, routingRuleName string) (result RoutingRulesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRulesClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: routingRuleName, + Constraints: []validation.Constraint{{Target: "routingRuleName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "routingRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "routingRuleName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.RoutingRulesClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, frontDoorName, routingRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client RoutingRulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, frontDoorName string, routingRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routingRuleName": autorest.Encode("path", routingRuleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules/{routingRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RoutingRulesClient) DeleteSender(req *http.Request) (future RoutingRulesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RoutingRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a Routing Rule with the specified Rule name within the specified Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +// routingRuleName - name of the Routing Rule which is unique within the Front Door. +func (client RoutingRulesClient) Get(ctx context.Context, resourceGroupName string, frontDoorName string, routingRuleName string) (result RoutingRule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRulesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}, + {TargetValue: routingRuleName, + Constraints: []validation.Constraint{{Target: "routingRuleName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "routingRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "routingRuleName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.RoutingRulesClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, frontDoorName, routingRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RoutingRulesClient) GetPreparer(ctx context.Context, resourceGroupName string, frontDoorName string, routingRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routingRuleName": autorest.Encode("path", routingRuleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules/{routingRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RoutingRulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RoutingRulesClient) GetResponder(resp *http.Response) (result RoutingRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByFrontDoor lists all of the Routing Rules within a Front Door. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// frontDoorName - name of the Front Door which is globally unique. +func (client RoutingRulesClient) ListByFrontDoor(ctx context.Context, resourceGroupName string, frontDoorName string) (result RoutingRuleListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRulesClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.rrlr.Response.Response != nil { + sc = result.rrlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 80, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_\-\(\)\.]*[^\.]$`, Chain: nil}}}, + {TargetValue: frontDoorName, + Constraints: []validation.Constraint{{Target: "frontDoorName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "frontDoorName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "frontDoorName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("frontdoor.RoutingRulesClient", "ListByFrontDoor", err.Error()) + } + + result.fn = client.listByFrontDoorNextResults + req, err := client.ListByFrontDoorPreparer(ctx, resourceGroupName, frontDoorName) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "ListByFrontDoor", nil, "Failure preparing request") + return + } + + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.rrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "ListByFrontDoor", resp, "Failure sending request") + return + } + + result.rrlr, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "ListByFrontDoor", resp, "Failure responding to request") + } + + return +} + +// ListByFrontDoorPreparer prepares the ListByFrontDoor request. +func (client RoutingRulesClient) ListByFrontDoorPreparer(ctx context.Context, resourceGroupName string, frontDoorName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "frontDoorName": autorest.Encode("path", frontDoorName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByFrontDoorSender sends the ListByFrontDoor request. The method will close the +// http.Response Body if it receives an error. +func (client RoutingRulesClient) ListByFrontDoorSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByFrontDoorResponder handles the response to the ListByFrontDoor request. The method always +// closes the http.Response Body. +func (client RoutingRulesClient) ListByFrontDoorResponder(resp *http.Response) (result RoutingRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByFrontDoorNextResults retrieves the next set of results, if any. +func (client RoutingRulesClient) listByFrontDoorNextResults(ctx context.Context, lastResults RoutingRuleListResult) (result RoutingRuleListResult, err error) { + req, err := lastResults.routingRuleListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "listByFrontDoorNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByFrontDoorSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "listByFrontDoorNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByFrontDoorResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "frontdoor.RoutingRulesClient", "listByFrontDoorNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByFrontDoorComplete enumerates all values, automatically crossing page boundaries as required. +func (client RoutingRulesClient) ListByFrontDoorComplete(ctx context.Context, resourceGroupName string, frontDoorName string) (result RoutingRuleListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/RoutingRulesClient.ListByFrontDoor") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByFrontDoor(ctx, resourceGroupName, frontDoorName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/version.go new file mode 100644 index 000000000000..402567522ba3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor/version.go @@ -0,0 +1,30 @@ +package frontdoor + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + version.Number + " frontdoor/2019-04-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} From 1cb59ceb427176be9fe4e377b43e059f0a314dbd Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 28 Jun 2019 14:05:33 -0700 Subject: [PATCH 03/74] PIP --- azurerm/config.go | 24 +- azurerm/provider.go | 166 +---- azurerm/resource_arm_front_door.go | 874 +++++++++++++++++++++++- azurerm/resource_arm_front_door_test.go | 125 ++-- website/docs/r/front_door.html.markdown | 189 ++++- 5 files changed, 1045 insertions(+), 333 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index 5a902d063903..6844db63992c 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -19,14 +19,9 @@ import ( analyticsAccount "github.com/Azure/azure-sdk-for-go/services/datalake/analytics/mgmt/2016-11-01/account" "github.com/Azure/azure-sdk-for-go/services/datalake/store/2016-11-01/filesystem" storeAccount "github.com/Azure/azure-sdk-for-go/services/datalake/store/mgmt/2016-11-01/account" -<<<<<<< HEAD - "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2016-05-15/dtl" - "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" - "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" -======= devtestlabsSvc "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2016-05-15/dtl" eventHubSvc "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" ->>>>>>> 03966b073d1d1a7ea0e51bbc4a8f3f8b267498d0 + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" keyVault "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault" "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2018-02-14/keyvault" @@ -228,20 +223,9 @@ type ArmClient struct { dataLakeAnalyticsAccountClient analyticsAccount.AccountsClient dataLakeAnalyticsFirewallRulesClient analyticsAccount.FirewallRulesClient -<<<<<<< HEAD - // Databricks - databricksWorkspacesClient databricks.WorkspacesClient - // Frontdoor - frontdoorClient frontdoor.FrontDoorsClient - - // HDInsight - hdinsightApplicationsClient hdinsight.ApplicationsClient - hdinsightClustersClient hdinsight.ClustersClient - hdinsightConfigurationsClient hdinsight.ConfigurationsClient - -======= ->>>>>>> 03966b073d1d1a7ea0e51bbc4a8f3f8b267498d0 + frontDoorsClient frontdoor.FrontDoorsClient + // KeyVault keyVaultClient keyvault.VaultsClient keyVaultManagementClient keyVault.BaseClient @@ -784,7 +768,7 @@ func (c *ArmClient) registerEventHubClients(endpoint, subscriptionId string, aut func (c *ArmClient) registerFrontdoorInstanceClients(endpoint, subscriptionId string, auth autorest.Authorizer) { fdc := frontdoor.NewFrontDoorsClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&fdc.Client, auth) - c.frontdoorClient = fdc + c.frontDoorsClient = fdc } func (c *ArmClient) registerHDInsightsClients(endpoint, subscriptionId string, auth autorest.Authorizer) { diff --git a/azurerm/provider.go b/azurerm/provider.go index 713ae84bc867..c36fc9d711ed 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -182,170 +182,6 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ -<<<<<<< HEAD - "azurerm_api_management": resourceArmApiManagementService(), - "azurerm_api_management_api": resourceArmApiManagementApi(), - "azurerm_api_management_api_operation": resourceArmApiManagementApiOperation(), - "azurerm_api_management_api_operation_policy": resourceArmApiManagementApiOperationPolicy(), - "azurerm_api_management_api_policy": resourceArmApiManagementApiPolicy(), - "azurerm_api_management_api_schema": resourceArmApiManagementApiSchema(), - "azurerm_api_management_api_version_set": resourceArmApiManagementApiVersionSet(), - "azurerm_api_management_authorization_server": resourceArmApiManagementAuthorizationServer(), - "azurerm_api_management_certificate": resourceArmApiManagementCertificate(), - "azurerm_api_management_group": resourceArmApiManagementGroup(), - "azurerm_api_management_group_user": resourceArmApiManagementGroupUser(), - "azurerm_api_management_logger": resourceArmApiManagementLogger(), - "azurerm_api_management_openid_connect_provider": resourceArmApiManagementOpenIDConnectProvider(), - "azurerm_api_management_product": resourceArmApiManagementProduct(), - "azurerm_api_management_product_api": resourceArmApiManagementProductApi(), - "azurerm_api_management_product_group": resourceArmApiManagementProductGroup(), - "azurerm_api_management_product_policy": resourceArmApiManagementProductPolicy(), - "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(), - "azurerm_app_service_plan": resourceArmAppServicePlan(), - "azurerm_app_service_slot": resourceArmAppServiceSlot(), - "azurerm_app_service": resourceArmAppService(), - "azurerm_application_gateway": resourceArmApplicationGateway(), - "azurerm_application_insights_api_key": resourceArmApplicationInsightsAPIKey(), - "azurerm_application_insights": resourceArmApplicationInsights(), - "azurerm_application_security_group": resourceArmApplicationSecurityGroup(), - "azurerm_automation_account": resourceArmAutomationAccount(), - "azurerm_automation_credential": resourceArmAutomationCredential(), - "azurerm_automation_dsc_configuration": resourceArmAutomationDscConfiguration(), - "azurerm_automation_dsc_nodeconfiguration": resourceArmAutomationDscNodeConfiguration(), - "azurerm_automation_module": resourceArmAutomationModule(), - "azurerm_automation_runbook": resourceArmAutomationRunbook(), - "azurerm_automation_schedule": resourceArmAutomationSchedule(), - "azurerm_automation_variable_bool": resourceArmAutomationVariableBool(), - "azurerm_automation_variable_datetime": resourceArmAutomationVariableDateTime(), - "azurerm_automation_variable_int": resourceArmAutomationVariableInt(), - "azurerm_automation_variable_string": resourceArmAutomationVariableString(), - "azurerm_autoscale_setting": resourceArmAutoScaleSetting(), - "azurerm_availability_set": resourceArmAvailabilitySet(), - "azurerm_azuread_application": resourceArmActiveDirectoryApplication(), - "azurerm_azuread_service_principal_password": resourceArmActiveDirectoryServicePrincipalPassword(), - "azurerm_azuread_service_principal": resourceArmActiveDirectoryServicePrincipal(), - "azurerm_batch_account": resourceArmBatchAccount(), - "azurerm_batch_certificate": resourceArmBatchCertificate(), - "azurerm_batch_pool": resourceArmBatchPool(), - "azurerm_cdn_endpoint": resourceArmCdnEndpoint(), - "azurerm_cdn_profile": resourceArmCdnProfile(), - "azurerm_cognitive_account": resourceArmCognitiveAccount(), - "azurerm_connection_monitor": resourceArmConnectionMonitor(), - "azurerm_container_group": resourceArmContainerGroup(), - "azurerm_container_registry": resourceArmContainerRegistry(), - "azurerm_container_service": resourceArmContainerService(), - "azurerm_cosmosdb_account": resourceArmCosmosDBAccount(), - "azurerm_data_factory": resourceArmDataFactory(), - "azurerm_data_factory_dataset_mysql": resourceArmDataFactoryDatasetMySQL(), - "azurerm_data_factory_dataset_postgresql": resourceArmDataFactoryDatasetPostgreSQL(), - "azurerm_data_factory_dataset_sql_server_table": resourceArmDataFactoryDatasetSQLServerTable(), - "azurerm_data_factory_linked_service_mysql": resourceArmDataFactoryLinkedServiceMySQL(), - "azurerm_data_factory_linked_service_postgresql": resourceArmDataFactoryLinkedServicePostgreSQL(), - "azurerm_data_factory_linked_service_sql_server": resourceArmDataFactoryLinkedServiceSQLServer(), - "azurerm_data_factory_pipeline": resourceArmDataFactoryPipeline(), - "azurerm_data_lake_analytics_account": resourceArmDataLakeAnalyticsAccount(), - "azurerm_data_lake_analytics_firewall_rule": resourceArmDataLakeAnalyticsFirewallRule(), - "azurerm_data_lake_store_file": resourceArmDataLakeStoreFile(), - "azurerm_data_lake_store_firewall_rule": resourceArmDataLakeStoreFirewallRule(), - "azurerm_data_lake_store": resourceArmDataLakeStore(), - "azurerm_databricks_workspace": resourceArmDatabricksWorkspace(), - "azurerm_ddos_protection_plan": resourceArmDDoSProtectionPlan(), - "azurerm_dev_test_lab": resourceArmDevTestLab(), - "azurerm_dev_test_linux_virtual_machine": resourceArmDevTestLinuxVirtualMachine(), - "azurerm_dev_test_policy": resourceArmDevTestPolicy(), - "azurerm_dev_test_virtual_network": resourceArmDevTestVirtualNetwork(), - "azurerm_dev_test_windows_virtual_machine": resourceArmDevTestWindowsVirtualMachine(), - "azurerm_devspace_controller": resourceArmDevSpaceController(), - "azurerm_dns_a_record": resourceArmDnsARecord(), - "azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(), - "azurerm_dns_caa_record": resourceArmDnsCaaRecord(), - "azurerm_dns_cname_record": resourceArmDnsCNameRecord(), - "azurerm_dns_mx_record": resourceArmDnsMxRecord(), - "azurerm_dns_ns_record": resourceArmDnsNsRecord(), - "azurerm_dns_ptr_record": resourceArmDnsPtrRecord(), - "azurerm_dns_srv_record": resourceArmDnsSrvRecord(), - "azurerm_dns_txt_record": resourceArmDnsTxtRecord(), - "azurerm_dns_zone": resourceArmDnsZone(), - "azurerm_eventgrid_domain": resourceArmEventGridDomain(), - "azurerm_eventgrid_event_subscription": resourceArmEventGridEventSubscription(), - "azurerm_eventgrid_topic": resourceArmEventGridTopic(), - "azurerm_eventhub_authorization_rule": resourceArmEventHubAuthorizationRule(), - "azurerm_eventhub_consumer_group": resourceArmEventHubConsumerGroup(), - "azurerm_eventhub_namespace_authorization_rule": resourceArmEventHubNamespaceAuthorizationRule(), - "azurerm_eventhub_namespace": resourceArmEventHubNamespace(), - "azurerm_eventhub": resourceArmEventHub(), - "azurerm_express_route_circuit_authorization": resourceArmExpressRouteCircuitAuthorization(), - "azurerm_express_route_circuit_peering": resourceArmExpressRouteCircuitPeering(), - "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), - "azurerm_firewall_application_rule_collection": resourceArmFirewallApplicationRuleCollection(), - "azurerm_firewall_nat_rule_collection": resourceArmFirewallNatRuleCollection(), - "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), - "azurerm_firewall": resourceArmFirewall(), - "azurerm_frontdoor": resourceArmFrontDoor(), - "azurerm_function_app": resourceArmFunctionApp(), - "azurerm_hdinsight_hadoop_cluster": resourceArmHDInsightHadoopCluster(), - "azurerm_hdinsight_hbase_cluster": resourceArmHDInsightHBaseCluster(), - "azurerm_hdinsight_interactive_query_cluster": resourceArmHDInsightInteractiveQueryCluster(), - "azurerm_hdinsight_kafka_cluster": resourceArmHDInsightKafkaCluster(), - "azurerm_hdinsight_ml_services_cluster": resourceArmHDInsightMLServicesCluster(), - "azurerm_hdinsight_rserver_cluster": resourceArmHDInsightRServerCluster(), - "azurerm_hdinsight_spark_cluster": resourceArmHDInsightSparkCluster(), - "azurerm_hdinsight_storm_cluster": resourceArmHDInsightStormCluster(), - "azurerm_image": resourceArmImage(), - "azurerm_iothub_consumer_group": resourceArmIotHubConsumerGroup(), - "azurerm_iothub": resourceArmIotHub(), - "azurerm_iothub_shared_access_policy": resourceArmIotHubSharedAccessPolicy(), - "azurerm_key_vault_access_policy": resourceArmKeyVaultAccessPolicy(), - "azurerm_key_vault_certificate": resourceArmKeyVaultCertificate(), - "azurerm_key_vault_key": resourceArmKeyVaultKey(), - "azurerm_key_vault_secret": resourceArmKeyVaultSecret(), - "azurerm_key_vault": resourceArmKeyVault(), - "azurerm_kubernetes_cluster": resourceArmKubernetesCluster(), - "azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(), - "azurerm_lb_nat_pool": resourceArmLoadBalancerNatPool(), - "azurerm_lb_nat_rule": resourceArmLoadBalancerNatRule(), - "azurerm_lb_probe": resourceArmLoadBalancerProbe(), - "azurerm_lb_outbound_rule": resourceArmLoadBalancerOutboundRule(), - "azurerm_lb_rule": resourceArmLoadBalancerRule(), - "azurerm_lb": resourceArmLoadBalancer(), - "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), - "azurerm_log_analytics_solution": resourceArmLogAnalyticsSolution(), - "azurerm_log_analytics_linked_service": resourceArmLogAnalyticsLinkedService(), - "azurerm_log_analytics_workspace_linked_service": resourceArmLogAnalyticsWorkspaceLinkedService(), - "azurerm_log_analytics_workspace": resourceArmLogAnalyticsWorkspace(), - "azurerm_logic_app_action_custom": resourceArmLogicAppActionCustom(), - "azurerm_logic_app_action_http": resourceArmLogicAppActionHTTP(), - "azurerm_logic_app_trigger_custom": resourceArmLogicAppTriggerCustom(), - "azurerm_logic_app_trigger_http_request": resourceArmLogicAppTriggerHttpRequest(), - "azurerm_logic_app_trigger_recurrence": resourceArmLogicAppTriggerRecurrence(), - "azurerm_logic_app_workflow": resourceArmLogicAppWorkflow(), - "azurerm_managed_disk": resourceArmManagedDisk(), - "azurerm_management_group": resourceArmManagementGroup(), - "azurerm_management_lock": resourceArmManagementLock(), - "azurerm_mariadb_database": resourceArmMariaDbDatabase(), - "azurerm_mariadb_server": resourceArmMariaDbServer(), - "azurerm_media_services_account": resourceArmMediaServicesAccount(), - "azurerm_metric_alertrule": resourceArmMetricAlertRule(), - "azurerm_monitor_autoscale_setting": resourceArmMonitorAutoScaleSetting(), - "azurerm_monitor_action_group": resourceArmMonitorActionGroup(), - "azurerm_monitor_activity_log_alert": resourceArmMonitorActivityLogAlert(), - "azurerm_monitor_diagnostic_setting": resourceArmMonitorDiagnosticSetting(), - "azurerm_monitor_log_profile": resourceArmMonitorLogProfile(), - "azurerm_monitor_metric_alert": resourceArmMonitorMetricAlert(), - "azurerm_monitor_metric_alertrule": resourceArmMonitorMetricAlertRule(), - "azurerm_mssql_elasticpool": resourceArmMsSqlElasticPool(), - "azurerm_mysql_configuration": resourceArmMySQLConfiguration(), - "azurerm_mysql_database": resourceArmMySqlDatabase(), - "azurerm_mysql_firewall_rule": resourceArmMySqlFirewallRule(), - "azurerm_mysql_server": resourceArmMySqlServer(), - "azurerm_mysql_virtual_network_rule": resourceArmMySqlVirtualNetworkRule(), - "azurerm_network_connection_monitor": resourceArmNetworkConnectionMonitor(), - "azurerm_network_ddos_protection_plan": resourceArmNetworkDDoSProtectionPlan(), -======= "azurerm_api_management": resourceArmApiManagementService(), "azurerm_api_management_api": resourceArmApiManagementApi(), "azurerm_api_management_api_operation": resourceArmApiManagementApiOperation(), @@ -455,6 +291,7 @@ func Provider() terraform.ResourceProvider { "azurerm_firewall_nat_rule_collection": resourceArmFirewallNatRuleCollection(), "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), "azurerm_firewall": resourceArmFirewall(), + "azurerm_frontdoor": resourceArmFrontDoor(), "azurerm_function_app": resourceArmFunctionApp(), "azurerm_hdinsight_hadoop_cluster": resourceArmHDInsightHadoopCluster(), "azurerm_hdinsight_hbase_cluster": resourceArmHDInsightHBaseCluster(), @@ -518,7 +355,6 @@ func Provider() terraform.ResourceProvider { "azurerm_network_connection_monitor": resourceArmNetworkConnectionMonitor(), "azurerm_network_ddos_protection_plan": resourceArmNetworkDDoSProtectionPlan(), "azurerm_network_interface": resourceArmNetworkInterface(), ->>>>>>> 03966b073d1d1a7ea0e51bbc4a8f3f8b267498d0 "azurerm_network_interface_application_gateway_backend_address_pool_association": resourceArmNetworkInterfaceApplicationGatewayBackendAddressPoolAssociation(), "azurerm_network_interface_application_security_group_association": resourceArmNetworkInterfaceApplicationSecurityGroupAssociation(), "azurerm_network_interface_backend_address_pool_association": resourceArmNetworkInterfaceBackendAddressPoolAssociation(), diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 476371ae01f3..3fbe990a7a64 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -26,51 +26,406 @@ func resourceArmFrontDoor() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: azure.ValidateFrontDoorName, + Type: schema.TypeString, + Required: true, + ForceNew: true, }, - "location": locationSchema(), + "location": azure.SchemaLocation(), + + "resource_group": azure.SchemaResourceGroupNameDiffSuppress(), - "resource_group_name": resourceGroupNameSchema(), + "backend_pools": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "backends": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "address": { + Type: schema.TypeString, + Optional: true, + }, + "backend_host_header": { + Type: schema.TypeString, + Optional: true, + }, + "enabled_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Enabled), + string(frontdoor.Disabled), + }, false), + Default: string(frontdoor.Enabled), + }, + "http_port": { + Type: schema.TypeInt, + Optional: true, + }, + "https_port": { + Type: schema.TypeInt, + Optional: true, + }, + "priority": { + Type: schema.TypeInt, + Optional: true, + }, + "weight": { + Type: schema.TypeInt, + Optional: true, + }, + }, + }, + }, + "health_probe_settings": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "id": { + Type: schema.TypeString, + Optional: true, + }, + "load_balancing_settings": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "resource_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.PolicyResourceStateCreating), + string(frontdoor.PolicyResourceStateEnabling), + string(frontdoor.PolicyResourceStateEnabled), + string(frontdoor.PolicyResourceStateDisabling), + string(frontdoor.PolicyResourceStateDisabled), + string(frontdoor.PolicyResourceStateDeleting), + }, false), + Default: string(frontdoor.PolicyResourceStateCreating), + }, + }, + }, + }, + + "backend_pools_settings": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enforce_certificate_name_check": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Enabled), + string(frontdoor.Disabled), + }, false), + Default: string(frontdoor.Enabled), + }, + }, + }, + }, "enabled_state": { Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.EnabledStateEnabled), - string(frontdoor.EnabledStateDisabled), + string(frontdoor.Enabled), + string(frontdoor.Disabled), }, false), Default: string(frontdoor.Enabled), }, - "enforce_certificate_name_check": { + "friendly_name": { + Type: schema.TypeString, + Optional: true, + }, + + "frontend_endpoints": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "host_name": { + Type: schema.TypeString, + Optional: true, + }, + "id": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "resource_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.PolicyResourceStateCreating), + string(frontdoor.PolicyResourceStateEnabling), + string(frontdoor.PolicyResourceStateEnabled), + string(frontdoor.PolicyResourceStateDisabling), + string(frontdoor.PolicyResourceStateDisabled), + string(frontdoor.PolicyResourceStateDeleting), + }, false), + Default: string(frontdoor.PolicyResourceStateCreating), + }, + "session_affinity_enabled_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Enabled), + string(frontdoor.Disabled), + }, false), + Default: string(frontdoor.Enabled), + }, + "session_affinity_ttl_seconds": { + Type: schema.TypeInt, + Optional: true, + }, + "web_application_firewall_policy_link": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + }, + }, + + "health_probe_settings": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + }, + "interval_in_seconds": { + Type: schema.TypeInt, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "path": { + Type: schema.TypeString, + Optional: true, + }, + "protocol": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.HTTP), + string(frontdoor.HTTPS), + }, false), + Default: string(frontdoor.HTTP), + }, + "resource_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.PolicyResourceStateCreating), + string(frontdoor.PolicyResourceStateEnabling), + string(frontdoor.PolicyResourceStateEnabled), + string(frontdoor.PolicyResourceStateDisabling), + string(frontdoor.PolicyResourceStateDisabled), + string(frontdoor.PolicyResourceStateDeleting), + }, false), + Default: string(frontdoor.PolicyResourceStateCreating), + }, + }, + }, + }, + + "load_balancing_settings": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "additional_latency_milliseconds": { + Type: schema.TypeInt, + Optional: true, + }, + "id": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "resource_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.PolicyResourceStateCreating), + string(frontdoor.PolicyResourceStateEnabling), + string(frontdoor.PolicyResourceStateEnabled), + string(frontdoor.PolicyResourceStateDisabling), + string(frontdoor.PolicyResourceStateDisabled), + string(frontdoor.PolicyResourceStateDeleting), + }, false), + Default: string(frontdoor.PolicyResourceStateCreating), + }, + "sample_size": { + Type: schema.TypeInt, + Optional: true, + }, + "successful_samples_required": { + Type: schema.TypeInt, + Optional: true, + }, + }, + }, + }, + + "resource_state": { Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.EnforceCertificateNameCheckEnabledStateEnabled), - string(frontdoor.EnforceCertificateNameCheckEnabledStateDisabled), + string(frontdoor.PolicyResourceStateCreating), + string(frontdoor.PolicyResourceStateEnabling), + string(frontdoor.PolicyResourceStateEnabled), + string(frontdoor.PolicyResourceStateDisabling), + string(frontdoor.PolicyResourceStateDisabled), + string(frontdoor.PolicyResourceStateDeleting), }, false), + Default: string(frontdoor.PolicyResourceStateCreating), }, - "friendly_name": { - Type: schema.TypeString, + "routing_rules": { + Type: schema.TypeList, Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "accepted_protocols": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.HTTP), + string(frontdoor.HTTPS), + }, false), + Default: string(frontdoor.HTTP), + }, + "enabled_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Enabled), + string(frontdoor.Disabled), + }, false), + Default: string(frontdoor.Enabled), + }, + "frontend_endpoints": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "id": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "patterns_to_match": { + Type: schema.TypeString, + Optional: true, + }, + "resource_state": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.PolicyResourceStateCreating), + string(frontdoor.PolicyResourceStateEnabling), + string(frontdoor.PolicyResourceStateEnabled), + string(frontdoor.PolicyResourceStateDisabling), + string(frontdoor.PolicyResourceStateDisabled), + string(frontdoor.PolicyResourceStateDeleting), + }, false), + Default: string(frontdoor.PolicyResourceStateCreating), + }, + }, + }, }, "tags": tagsSchema(), + + "cname": { + Type: schema.TypeString, + Computed: true, + }, + + "provisioning_state": { + Type: schema.TypeString, + Computed: true, + }, + + "type": { + Type: schema.TypeString, + Computed: true, + }, }, } } func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontdoorClient + client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) + resourceGroup := d.Get("resource_group").(string) if requireResourcesToBeImported { resp, err := client.Get(ctx, resourceGroup, name) @@ -84,30 +439,35 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } } - location := azureRMNormalizeLocation(d.Get("location").(string)) + location := azure.NormalizeLocation(d.Get("location").(string)) + backendPools := d.Get("backend_pools").([]interface{}) + backendPoolsSettings := d.Get("backend_pools_settings").([]interface{}) enabledState := d.Get("enabled_state").(string) - enforceCertificateNameCheck := d.Get("enforce_certificate_name_check").(string) friendlyName := d.Get("friendly_name").(string) + frontendEndpoints := d.Get("frontend_endpoints").([]interface{}) + healthProbeSettings := d.Get("health_probe_settings").([]interface{}) + loadBalancingSettings := d.Get("load_balancing_settings").([]interface{}) + resourceState := d.Get("resource_state").(string) + routingRules := d.Get("routing_rules").([]interface{}) tags := d.Get("tags").(map[string]interface{}) - parameters := frontdoor.FrontDoor{ + frontDoorParameters := frontdoor.FrontDoor{ Location: utils.String(location), Properties: &frontdoor.Properties{ - RoutingRules: &[]frontdoor.RoutingRule{}, - LoadBalancingSettings: &[]frontdoor.LoadBalancingSettingsModel{}, - HealthProbeSettings: &[]frontdoor.HealthProbeSettingsModel{}, - BackendPools: &[]frontdoor.BackendPool{}, - FrontendEndpoints: &[]frontdoor.FrontendEndpoint{}, - BackendPoolsSettings: &frontdoor.BackendPoolsSettings{ - EnforceCertificateNameCheck: frontdoor.EnforceCertificateNameCheckEnabledState(enforceCertificateNameCheck), - }, - EnabledState: frontdoor.EnabledState(enabledState), - FriendlyName: utils.String(friendlyName), + BackendPools: expandArmFrontDoorBackendPool(backendPools), + BackendPoolsSettings: expandArmFrontDoorBackendPoolsSettings(backendPoolsSettings), + EnabledState: frontdoor.EnabledState(enabledState), + FriendlyName: utils.String(friendlyName), + FrontendEndpoints: expandArmFrontDoorFrontendEndpoint(frontendEndpoints), + HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings), + LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings), + ResourceState: frontdoor.ResourceState(resourceState), + RoutingRules: expandArmFrontDoorRoutingRule(routingRules), }, Tags: expandTags(tags), } - future, err := client.CreateOrUpdate(ctx, resourceGroup, name, parameters) + future, err := client.CreateOrUpdate(ctx, resourceGroup, name, frontDoorParameters) if err != nil { return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) } @@ -128,7 +488,7 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontdoorClient + client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext id, err := parseAzureResourceID(d.Id()) @@ -149,24 +509,43 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) + d.Set("resource_group", resourceGroup) if location := resp.Location; location != nil { - d.Set("location", azureRMNormalizeLocation(*location)) + d.Set("location", azure.NormalizeLocation(*location)) } if properties := resp.Properties; properties != nil { - d.Set("enabled_state", string(properties.EnabledState)) - if backendPoolsSettings := properties.BackendPoolsSettings; backendPoolsSettings != nil { - d.Set("enforce_certificate_name_check", string(backendPoolsSettings.EnforceCertificateNameCheck)) + if err := d.Set("backend_pools", flattenArmFrontDoorBackendPool(properties.BackendPools)); err != nil { + return fmt.Errorf("Error setting `backend_pools`: %+v", err) } + if err := d.Set("backend_pools_settings", flattenArmFrontDoorBackendPoolsSettings(properties.BackendPoolsSettings)); err != nil { + return fmt.Errorf("Error setting `backend_pools_settings`: %+v", err) + } + d.Set("cname", properties.Cname) + d.Set("enabled_state", string(properties.EnabledState)) d.Set("friendly_name", properties.FriendlyName) + if err := d.Set("frontend_endpoints", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { + return fmt.Errorf("Error setting `frontend_endpoints`: %+v", err) + } + if err := d.Set("health_probe_settings", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { + return fmt.Errorf("Error setting `health_probe_settings`: %+v", err) + } + if err := d.Set("load_balancing_settings", flattenArmFrontDoorLoadBalancingSettingsModel(properties.LoadBalancingSettings)); err != nil { + return fmt.Errorf("Error setting `load_balancing_settings`: %+v", err) + } + d.Set("provisioning_state", properties.ProvisioningState) + d.Set("resource_state", string(properties.ResourceState)) + if err := d.Set("routing_rules", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { + return fmt.Errorf("Error setting `routing_rules`: %+v", err) + } } + d.Set("type", resp.Type) flattenAndSetTags(d, resp.Tags) return nil } func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontdoorClient + client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext id, err := parseAzureResourceID(d.Id()) @@ -192,3 +571,426 @@ func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error return nil } + +func expandArmFrontDoorBackendPool(input []interface{}) *[]frontdoor.BackendPool { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + backends := v["backends"].([]interface{}) + loadBalancingSettings := v["load_balancing_settings"].([]interface{}) + healthProbeSettings := v["health_probe_settings"].([]interface{}) + resourceState := v["resource_state"].(string) + name := v["name"].(string) + + result := frontdoor.BackendPool{ + ID: utils.String(id), + Name: utils.String(name), + BackendPoolProperties: &frontdoor.BackendPoolProperties{ + Backends: expandArmFrontDoorBackend(backends), + HealthProbeSettings: expandArmFrontDoorSubResource(healthProbeSettings), + LoadBalancingSettings: expandArmFrontDoorSubResource(loadBalancingSettings), + ResourceState: frontdoor.ResourceState(resourceState), + }, + } + return &[]frontdoor.BackendPool{result} +} + +func expandArmFrontDoorBackendPoolsSettings(input []interface{}) *frontdoor.BackendPoolsSettings { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + enforceCertificateNameCheck := v["enforce_certificate_name_check"].(string) + + result := frontdoor.BackendPoolsSettings{ + EnforceCertificateNameCheck: frontdoor.EnforceCertificateNameCheckEnabledState(enforceCertificateNameCheck), + } + return &result +} + +func expandArmFrontDoorFrontendEndpoint(input []interface{}) *[]frontdoor.FrontendEndpoint { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + hostName := v["host_name"].(string) + sessionAffinityEnabledState := v["session_affinity_enabled_state"].(string) + sessionAffinityTtlSeconds := v["session_affinity_ttl_seconds"].(int32) + webApplicationFirewallPolicyLink := v["web_application_firewall_policy_link"].([]interface{}) + resourceState := v["resource_state"].(string) + name := v["name"].(string) + + result := frontdoor.FrontendEndpoint{ + ID: utils.String(id), + Name: utils.String(name), + FrontendEndpointProperties: &frontdoor.FrontendEndpointProperties{ + HostName: utils.String(hostName), + ResourceState: frontdoor.ResourceState(resourceState), + SessionAffinityEnabledState: frontdoor.SessionAffinityEnabledState(sessionAffinityEnabledState), + SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), + WebApplicationFirewallPolicyLink: expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(webApplicationFirewallPolicyLink), + }, + } + return &[]frontdoor.FrontendEndpoint{result} +} + +func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}) *[]frontdoor.HealthProbeSettingsModel { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + path := v["path"].(string) + protocol := v["protocol"].(string) + intervalInSeconds := v["interval_in_seconds"].(int32) + resourceState := v["resource_state"].(string) + name := v["name"].(string) + + result := frontdoor.HealthProbeSettingsModel{ + ID: utils.String(id), + Name: utils.String(name), + HealthProbeSettingsProperties: &frontdoor.HealthProbeSettingsProperties{ + IntervalInSeconds: utils.Int32(intervalInSeconds), + Path: utils.String(path), + Protocol: frontdoor.Protocol(protocol), + ResourceState: frontdoor.ResourceState(resourceState), + }, + } + return &[]frontdoor.HealthProbeSettingsModel{result} +} + +func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}) *[]frontdoor.LoadBalancingSettingsModel { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + sampleSize := v["sample_size"].(int32) + successfulSamplesRequired := v["successful_samples_required"].(int32) + additionalLatencyMilliseconds := v["additional_latency_milliseconds"].(int32) + resourceState := v["resource_state"].(string) + name := v["name"].(string) + + result := frontdoor.LoadBalancingSettingsModel{ + ID: utils.String(id), + Name: utils.String(name), + LoadBalancingSettingsProperties: &frontdoor.LoadBalancingSettingsProperties{ + AdditionalLatencyMilliseconds: utils.Int32(additionalLatencyMilliseconds), + ResourceState: frontdoor.ResourceState(resourceState), + SampleSize: utils.Int32(sampleSize), + SuccessfulSamplesRequired: utils.Int32(successfulSamplesRequired), + }, + } + return &[]frontdoor.LoadBalancingSettingsModel{result} +} + +func expandArmFrontDoorRoutingRule(input []interface{}) *[]frontdoor.RoutingRule { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + frontendEndpoints := v["frontend_endpoints"].([]interface{}) + acceptedProtocols := v["accepted_protocols"].([]interface{}) + patternsToMatch := v["patterns_to_match"].([]interface{}) + enabledState := v["enabled_state"].(string) + resourceState := v["resource_state"].(string) + name := v["name"].(string) + + result := frontdoor.RoutingRule{ + ID: utils.String(id), + Name: utils.String(name), + RoutingRuleProperties: &frontdoor.RoutingRuleProperties{ + AcceptedProtocols: expandArmFrontDoorProtocols(acceptedProtocols), + EnabledState: frontdoor.RoutingRuleEnabledState(enabledState), + FrontendEndpoints: expandArmFrontDoorSubResource(frontendEndpoints), + PatternsToMatch: *patternsToMatch, + ResourceState: frontdoor.ResourceState(resourceState), + }, + } + return &[]frontdoor.RoutingRule{result} +} +func expandArmFrontDoorProtocols(input []interface{}) *[]frontdoor.Protocol { + if len(input) == 0 { + return nil + } + v := input[0].(string) + + protocol := v[0] + result := frontdoor.Protocol{protocol} + + return &[]frontdoor.Protocol{result} +} + +func expandArmFrontDoorBackend(input []interface{}) *[]frontdoor.Backend { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + address := v["address"].(string) + httpPort := v["http_port"].(int32) + httpsPort := v["https_port"].(int32) + enabledState := v["enabled_state"].(string) + priority := v["priority"].(int32) + weight := v["weight"].(int32) + backendHostHeader := v["backend_host_header"].(string) + + result := frontdoor.Backend{ + Address: utils.String(address), + BackendHostHeader: utils.String(backendHostHeader), + EnabledState: frontdoor.BackendEnabledState(enabledState), + HTTPPort: utils.Int32(httpPort), + HTTPSPort: utils.Int32(httpsPort), + Priority: utils.Int32(priority), + Weight: utils.Int32(weight), + } + return &[]frontdoor.Backend{result} +} + +func expandArmFrontDoorSubResource(input []interface{}) *frontdoor.SubResource { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + + result := frontdoor.SubResource{ + ID: utils.String(id), + } + return &frontdoor.SubResource{result} +} + +func expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input []interface{}) *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + + result := frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink{ + ID: utils.String(id), + } + return &result +} + +func flattenArmFrontDoorBackendPool(input *[]frontdoor.BackendPool) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + if properties := input.BackendPoolProperties; properties != nil { + result["backends"] = flattenArmFrontDoorBackend(properties.Backends) + result["health_probe_settings"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings) + result["load_balancing_settings"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings) + if resourceState := string(properties.ResourceState); resourceState != nil { + result["resource_state"] = *resourceState + } + } + + return []interface{}{result} +} + +func flattenArmFrontDoorBackendPoolsSettings(input *frontdoor.BackendPoolsSettings) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if enforceCertificateNameCheck := string(input.EnforceCertificateNameCheck); enforceCertificateNameCheck != "" { + result["enforce_certificate_name_check"] = enforceCertificateNameCheck + } + + return []interface{}{result} +} + +func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + if properties := input.FrontendEndpointProperties; properties != nil { + if hostName := properties.HostName; hostName != nil { + result["host_name"] = *hostName + } + if resourceState := string(properties.ResourceState); resourceState != nil { + result["resource_state"] = *resourceState + } + if sessionAffinityEnabledState := string(properties.SessionAffinityEnabledState); sessionAffinityEnabledState != nil { + result["session_affinity_enabled_state"] = *sessionAffinityEnabledState + } + if sessionAffinityTtlSeconds := properties.SessionAffinityTtlSeconds; sessionAffinityTtlSeconds != nil { + result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds + } + result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) + } + + return []interface{}{result} +} + +func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeSettingsModel) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + if properties := input.HealthProbeSettingsProperties; properties != nil { + if intervalInSeconds := properties.IntervalInSeconds; intervalInSeconds != nil { + result["interval_in_seconds"] = *intervalInSeconds + } + if path := properties.Path; path != nil { + result["path"] = *path + } + if protocol := string(properties.Protocol); protocol != nil { + result["protocol"] = *protocol + } + if resourceState := string(properties.ResourceState); resourceState != nil { + result["resource_state"] = *resourceState + } + } + + return []interface{}{result} +} + +func flattenArmFrontDoorLoadBalancingSettingsModel(input *[]frontdoor.LoadBalancingSettingsModel) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + if properties := input.Properties; properties != nil { + if additionalLatencyMilliseconds := properties.AdditionalLatencyMilliseconds; additionalLatencyMilliseconds != nil { + result["additional_latency_milliseconds"] = *additionalLatencyMilliseconds + } + if resourceState := string(properties.ResourceState); resourceState != nil { + result["resource_state"] = *resourceState + } + if sampleSize := properties.SampleSize; sampleSize != nil { + result["sample_size"] = *sampleSize + } + if successfulSamplesRequired := properties.SuccessfulSamplesRequired; successfulSamplesRequired != nil { + result["successful_samples_required"] = *successfulSamplesRequired + } + } + + return []interface{}{result} +} + +func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + if properties := input.Properties; properties != nil { + if acceptedProtocols := string(properties.AcceptedProtocols); acceptedProtocols != nil { + result["accepted_protocols"] = *acceptedProtocols + } + if enabledState := string(properties.EnabledState); enabledState != nil { + result["enabled_state"] = *enabledState + } + result["frontend_endpoints"] = flattenArmFrontDoorSubResource(properties.FrontendEndpoints) + if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { + result["patterns_to_match"] = *patternsToMatch + } + if resourceState := string(properties.ResourceState); resourceState != nil { + result["resource_state"] = *resourceState + } + } + + return []interface{}{result} +} + +func flattenArmFrontDoorBackend(input *frontdoor.Backend) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if address := input.Address; address != nil { + result["address"] = *address + } + if backendHostHeader := input.BackendHostHeader; backendHostHeader != nil { + result["backend_host_header"] = *backendHostHeader + } + if enabledState := string(input.EnabledState); enabledState != nil { + result["enabled_state"] = *enabledState + } + if httpPort := input.HttpPort; httpPort != nil { + result["http_port"] = *httpPort + } + if httpsPort := input.HttpsPort; httpsPort != nil { + result["https_port"] = *httpsPort + } + if priority := input.Priority; priority != nil { + result["priority"] = *priority + } + if weight := input.Weight; weight != nil { + result["weight"] = *weight + } + + return []interface{}{result} +} + +func flattenArmFrontDoorSubResource(input *frontdoor.SubResource) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + + return []interface{}{result} +} + +func flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + if id := input.ID; id != nil { + result["id"] = *id + } + + return []interface{}{result} +} diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index aee64e527ece..4ad88f3aa914 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -1,99 +1,60 @@ package azurerm import ( - "fmt" - "testing" + "fmt" + "testing" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func TestAccAzureRMFrontdoor_basic(t *testing.T) { - resourceName := "azurerm_frontdoor.test" - ri := tf.AccRandTimeInt() - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMFrontDoorDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMFrontdoor_basic(ri, testLocation()), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMFrontDoorExists(resourceName), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Front Door not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - client := testAccProvider.Meta().(*ArmClient).frontdoorClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext - - if resp, err := client.Get(ctx, resourceGroup, name); err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) - } - return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) - } - - return nil - } + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Front Door not found: %s", resourceName) + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group"] + + client := testAccProvider.Meta().(*ArmClient).frontDoorsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) + } + return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) + } + + return nil + } } func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).frontdoorClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext + client := testAccProvider.Meta().(*ArmClient).frontDoorsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_front_door" { - continue - } + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_front_door" { + continue + } - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group"] - if resp, err := client.Get(ctx, resourceGroup, name); err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Get on frontdoorClient: %+v", err) - } - } + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) + } + } - return nil - } + return nil + } - return nil -} - -func testAccAzureRMFrontdoor_basic(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_frontdoor" "test" { - name = "acctest-frontdoor" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - enabled_state = "Enabled" -} -`, rInt, location) + return nil } diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 1ffb460caefe..e34e8b20e72c 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -3,58 +3,187 @@ layout: "azurerm" page_title: "Azure Resource Manager: azurerm_front_door" sidebar_current: "docs-azurerm-resource-front-door" description: |- - Managed a Front Door on Azure. + Manage Azure FrontDoor instance. --- # azurerm_front_door -Managed a Front Door on Azure. +Manage Azure FrontDoor instance. -## Example Usage - -```hcl -resource "azurerm_resource_group" "example" { - name = "example-rg" - location = "West US" -} - -resource "azurerm_frontdoor" "example" { - name = "example-frontdoor" - resource_group_name = "${azurerm_resource_group.example.name}" - location = "${azurerm_resource_group.example.location}" -} -``` - ## Argument Reference The following arguments are supported: * `name` - (Required) Name of the Front Door which is globally unique. Changing this forces a new resource to be created. -* `resource_group_name` - (Required) The name of the resource group in which to create the Batch Account. Changing this forces a new resource to be created. +* `resource_group` - (Required) Name of the Resource group within the Azure subscription. Changing this forces a new resource to be created. + +* `location` - (Optional) Resource location. Changing this forces a new resource to be created. + +* `backend_pools` - (Optional) One `backend_pool` block defined below. + +* `backend_pools_settings` - (Optional) One `backend_pools_setting` block defined below. + +* `enabled_state` - (Optional) Operational status of the Front Door load balancer. Permitted values are 'Enabled' or 'Disabled' Defaults to `Enabled`. + +* `friendly_name` - (Optional) A friendly name for the frontDoor + +* `frontend_endpoints` - (Optional) One `frontend_endpoint` block defined below. + +* `health_probe_settings` - (Optional) One `health_probe_setting` block defined below. + +* `load_balancing_settings` - (Optional) One `load_balancing_setting` block defined below. + +* `resource_state` - (Optional) Resource status of the Front Door. Defaults to `Creating`. + +* `routing_rules` - (Optional) One `routing_rule` block defined below. + +* `tags` - (Optional) Resource tags. Changing this forces a new resource to be created. + +--- + +The `backend_pool` block supports the following: + +* `id` - (Optional) Resource ID. + +* `backends` - (Optional) One `backend` block defined below. + +* `load_balancing_settings` - (Optional) One `load_balancing_setting` block defined below. + +* `health_probe_settings` - (Optional) One `health_probe_setting` block defined below. + +* `resource_state` - (Optional) Resource status. Defaults to `Creating`. + +* `name` - (Optional) Resource name. + + +--- + +The `backend` block supports the following: + +* `address` - (Optional) Location of the backend (IP address or FQDN) + +* `http_port` - (Optional) The HTTP TCP port number. Must be between 1 and 65535. + +* `https_port` - (Optional) The HTTPS TCP port number. Must be between 1 and 65535. + +* `enabled_state` - (Optional) Whether to enable use of this backend. Permitted values are 'Enabled' or 'Disabled' Defaults to `Enabled`. + +* `priority` - (Optional) Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy. + +* `weight` - (Optional) Weight of this endpoint for load balancing purposes. + +* `backend_host_header` - (Optional) The value to use as the host header sent to the backend. If blank or unspecified, this defaults to the incoming host. + +--- + +The `load_balancing_setting` block supports the following: + +* `id` - (Optional) Resource ID. + +--- + +The `health_probe_setting` block supports the following: + +* `id` - (Optional) Resource ID. + +--- + +The `backend_pools_setting` block supports the following: + +* `enforce_certificate_name_check` - (Optional) Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests. Defaults to `Enabled`. -* `location` - (Required) Resource location. Changing this forces a new resource to be created. +--- + +The `frontend_endpoint` block supports the following: + +* `id` - (Optional) Resource ID. + +* `host_name` - (Optional) The host name of the frontendEndpoint. Must be a domain name. + +* `session_affinity_enabled_state` - (Optional) Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled' Defaults to `Enabled`. + +* `session_affinity_ttl_seconds` - (Optional) UNUSED. This field will be ignored. The TTL to use in seconds for session affinity, if applicable. + +* `web_application_firewall_policy_link` - (Optional) One `web_application_firewall_policy_link` block defined below. + +* `resource_state` - (Optional) Resource status. Defaults to `Creating`. + +* `name` - (Optional) Resource name. + + +--- + +The `web_application_firewall_policy_link` block supports the following: + +* `id` - (Optional) Resource ID. + +--- + +The `health_probe_setting` block supports the following: + +* `id` - (Optional) Resource ID. + +* `path` - (Optional) The path to use for the health probe. Default is / + +* `protocol` - (Optional) Protocol scheme to use for this probe Defaults to `Http`. + +* `interval_in_seconds` - (Optional) The number of seconds between health probes. + +* `resource_state` - (Optional) Resource status. Defaults to `Creating`. + +* `name` - (Optional) Resource name. -* `enabled_state` - (Optional) Operational status of the Front Door load balancer. Defaults to `Enabled`. +--- + +The `load_balancing_setting` block supports the following: + +* `id` - (Optional) Resource ID. + +* `sample_size` - (Optional) The number of samples to consider for load balancing decisions + +* `successful_samples_required` - (Optional) The number of samples within the sample period that must succeed + +* `additional_latency_milliseconds` - (Optional) The additional latency in milliseconds for probes to fall into the lowest latency bucket + +* `resource_state` - (Optional) Resource status. Defaults to `Creating`. + +* `name` - (Optional) Resource name. + +--- + +The `routing_rule` block supports the following: + +* `id` - (Optional) Resource ID. -* `enforce_certificate_name_check` - (Optional) Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests. +* `frontend_endpoints` - (Optional) One `frontend_endpoint` block defined below. -* `friendly_name` - (Optional) A friendly name for the frontDoor. +* `accepted_protocols` - (Optional) Protocol schemes to match for this rule Defaults to `Http`. -* `tags` - (Optional) Resource tags. +* `patterns_to_match` - (Optional) The route patterns of the rule. + +* `enabled_state` - (Optional) Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' Defaults to `Enabled`. + +* `resource_state` - (Optional) Resource status. Defaults to `Creating`. + +* `name` - (Optional) Resource name. + + +--- + +The `frontend_endpoint` block supports the following: + +* `id` - (Optional) Resource ID. ## Attributes Reference The following attributes are exported: -* `id` - Resource ID. +* `provisioning_state` - Provisioning state of the Front Door. +* `cname` - The host that each frontendEndpoint must CNAME to. -## Import - -Front Door can be imported using the `resource id`, e.g. +* `id` - Resource ID. -```shell -$ terraform import azurerm_front_door.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Network/frontDoors/example-frontdoor -``` +* `type` - Resource type. From 200f2a85b3e3833df2d9d356187ae63cacb15ef2 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 28 Jun 2019 19:19:48 -0700 Subject: [PATCH 04/74] PIP --- azurerm/resource_arm_front_door.go | 232 +++++++++++++++-------------- 1 file changed, 120 insertions(+), 112 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 3fbe990a7a64..e60222bcb1ac 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -577,7 +577,7 @@ func expandArmFrontDoorBackendPool(input []interface{}) *[]frontdoor.BackendPool return nil } v := input[0].(map[string]interface{}) - + id := v["id"].(string) backends := v["backends"].([]interface{}) loadBalancingSettings := v["load_balancing_settings"].([]interface{}) @@ -700,8 +700,8 @@ func expandArmFrontDoorRoutingRule(input []interface{}) *[]frontdoor.RoutingRule id := v["id"].(string) frontendEndpoints := v["frontend_endpoints"].([]interface{}) - acceptedProtocols := v["accepted_protocols"].([]interface{}) - patternsToMatch := v["patterns_to_match"].([]interface{}) + acceptedProtocols := v["accepted_protocols"].(*[]frontdoor.Protocol) + patternsToMatch := v["patterns_to_match"].(*[]string) enabledState := v["enabled_state"].(string) resourceState := v["resource_state"].(string) name := v["name"].(string) @@ -710,26 +710,15 @@ func expandArmFrontDoorRoutingRule(input []interface{}) *[]frontdoor.RoutingRule ID: utils.String(id), Name: utils.String(name), RoutingRuleProperties: &frontdoor.RoutingRuleProperties{ - AcceptedProtocols: expandArmFrontDoorProtocols(acceptedProtocols), + AcceptedProtocols: acceptedProtocols, EnabledState: frontdoor.RoutingRuleEnabledState(enabledState), - FrontendEndpoints: expandArmFrontDoorSubResource(frontendEndpoints), - PatternsToMatch: *patternsToMatch, + FrontendEndpoints: expandArmFrontDoorSubResources(frontendEndpoints), + PatternsToMatch: patternsToMatch, ResourceState: frontdoor.ResourceState(resourceState), }, } return &[]frontdoor.RoutingRule{result} } -func expandArmFrontDoorProtocols(input []interface{}) *[]frontdoor.Protocol { - if len(input) == 0 { - return nil - } - v := input[0].(string) - - protocol := v[0] - result := frontdoor.Protocol{protocol} - - return &[]frontdoor.Protocol{result} -} func expandArmFrontDoorBackend(input []interface{}) *[]frontdoor.Backend { if len(input) == 0 { @@ -768,7 +757,21 @@ func expandArmFrontDoorSubResource(input []interface{}) *frontdoor.SubResource { result := frontdoor.SubResource{ ID: utils.String(id), } - return &frontdoor.SubResource{result} + return &result +} + +func expandArmFrontDoorSubResources(input []interface{}) *[]frontdoor.SubResource { + if len(input) == 0 { + return nil + } + v := input[0].(map[string]interface{}) + + id := v["id"].(string) + + result := frontdoor.SubResource{ + ID: utils.String(id), + } + return &[]frontdoor.SubResource{result} } func expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input []interface{}) *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink { @@ -792,15 +795,15 @@ func flattenArmFrontDoorBackendPool(input *[]frontdoor.BackendPool) []interface{ result := make(map[string]interface{}) - if id := input.ID; id != nil { - result["id"] = *id - } - if properties := input.BackendPoolProperties; properties != nil { - result["backends"] = flattenArmFrontDoorBackend(properties.Backends) - result["health_probe_settings"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings) - result["load_balancing_settings"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings) - if resourceState := string(properties.ResourceState); resourceState != nil { - result["resource_state"] = *resourceState + for _, v := range *input { + if id := v.ID; id != nil { + result["id"] = *id + } + if properties := v.BackendPoolProperties; properties != nil { + result["backends"] = flattenArmFrontDoorBackend(properties.Backends) + result["health_probe_settings"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings) + result["load_balancing_settings"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings) + result["resource_state"] = string(properties.ResourceState) } } @@ -827,26 +830,22 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] } result := make(map[string]interface{}) - - if id := input.ID; id != nil { - result["id"] = *id - } - if properties := input.FrontendEndpointProperties; properties != nil { - if hostName := properties.HostName; hostName != nil { - result["host_name"] = *hostName - } - if resourceState := string(properties.ResourceState); resourceState != nil { - result["resource_state"] = *resourceState + for _, v := range *input { + if id := v.ID; id != nil { + result["id"] = *id } - if sessionAffinityEnabledState := string(properties.SessionAffinityEnabledState); sessionAffinityEnabledState != nil { - result["session_affinity_enabled_state"] = *sessionAffinityEnabledState - } - if sessionAffinityTtlSeconds := properties.SessionAffinityTtlSeconds; sessionAffinityTtlSeconds != nil { - result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds + if properties := v.FrontendEndpointProperties; properties != nil { + if hostName := properties.HostName; hostName != nil { + result["host_name"] = *hostName + } + result["resource_state"] = string(properties.ResourceState) + result["session_affinity_enabled_state"] = string(properties.SessionAffinityEnabledState) + if sessionAffinityTtlSeconds := properties.SessionAffinityTTLSeconds; sessionAffinityTtlSeconds != nil { + result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds + } + result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) } - result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) } - return []interface{}{result} } @@ -856,22 +855,19 @@ func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeS } result := make(map[string]interface{}) - - if id := input.ID; id != nil { - result["id"] = *id - } - if properties := input.HealthProbeSettingsProperties; properties != nil { - if intervalInSeconds := properties.IntervalInSeconds; intervalInSeconds != nil { - result["interval_in_seconds"] = *intervalInSeconds - } - if path := properties.Path; path != nil { - result["path"] = *path - } - if protocol := string(properties.Protocol); protocol != nil { - result["protocol"] = *protocol + for _, v := range *input { + if id := v.ID; id != nil { + result["id"] = *id } - if resourceState := string(properties.ResourceState); resourceState != nil { - result["resource_state"] = *resourceState + if properties := v.HealthProbeSettingsProperties; properties != nil { + if intervalInSeconds := properties.IntervalInSeconds; intervalInSeconds != nil { + result["interval_in_seconds"] = *intervalInSeconds + } + if path := properties.Path; path != nil { + result["path"] = *path + } + result["protocol"] = string(properties.Protocol) + result["resource_state"] = string(properties.ResourceState) } } @@ -885,24 +881,23 @@ func flattenArmFrontDoorLoadBalancingSettingsModel(input *[]frontdoor.LoadBalanc result := make(map[string]interface{}) - if id := input.ID; id != nil { - result["id"] = *id - } - if properties := input.Properties; properties != nil { - if additionalLatencyMilliseconds := properties.AdditionalLatencyMilliseconds; additionalLatencyMilliseconds != nil { - result["additional_latency_milliseconds"] = *additionalLatencyMilliseconds - } - if resourceState := string(properties.ResourceState); resourceState != nil { - result["resource_state"] = *resourceState - } - if sampleSize := properties.SampleSize; sampleSize != nil { - result["sample_size"] = *sampleSize + for _, v := range *input { + if id := v.ID; id != nil { + result["id"] = *id } - if successfulSamplesRequired := properties.SuccessfulSamplesRequired; successfulSamplesRequired != nil { - result["successful_samples_required"] = *successfulSamplesRequired + if properties := v.LoadBalancingSettingsProperties; properties != nil { + if additionalLatencyMilliseconds := properties.AdditionalLatencyMilliseconds; additionalLatencyMilliseconds != nil { + result["additional_latency_milliseconds"] = *additionalLatencyMilliseconds + } + result["resource_state"] = string(properties.ResourceState) + if sampleSize := properties.SampleSize; sampleSize != nil { + result["sample_size"] = *sampleSize + } + if successfulSamplesRequired := properties.SuccessfulSamplesRequired; successfulSamplesRequired != nil { + result["successful_samples_required"] = *successfulSamplesRequired + } } } - return []interface{}{result} } @@ -913,57 +908,55 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ result := make(map[string]interface{}) - if id := input.ID; id != nil { - result["id"] = *id - } - if properties := input.Properties; properties != nil { - if acceptedProtocols := string(properties.AcceptedProtocols); acceptedProtocols != nil { - result["accepted_protocols"] = *acceptedProtocols - } - if enabledState := string(properties.EnabledState); enabledState != nil { - result["enabled_state"] = *enabledState + for _, v := range *input { + if id := v.ID; id != nil { + result["id"] = *id } - result["frontend_endpoints"] = flattenArmFrontDoorSubResource(properties.FrontendEndpoints) - if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { - result["patterns_to_match"] = *patternsToMatch - } - if resourceState := string(properties.ResourceState); resourceState != nil { - result["resource_state"] = *resourceState + if properties := v.RoutingRuleProperties; properties != nil { + if acceptedProtocols := properties.AcceptedProtocols; acceptedProtocols != nil { + for _, ap := range *acceptedProtocols { + result["accepted_protocols"] = string(ap) + } + } + result["enabled_state"] = string(properties.EnabledState) + result["frontend_endpoints"] = flattenArmFrontDoorSubResources(properties.FrontendEndpoints) + if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { + result["patterns_to_match"] = *patternsToMatch + } + result["resource_state"] = string(properties.ResourceState) } } return []interface{}{result} } -func flattenArmFrontDoorBackend(input *frontdoor.Backend) []interface{} { +func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { if input == nil { return make([]interface{}, 0) } result := make(map[string]interface{}) - - if address := input.Address; address != nil { - result["address"] = *address - } - if backendHostHeader := input.BackendHostHeader; backendHostHeader != nil { - result["backend_host_header"] = *backendHostHeader - } - if enabledState := string(input.EnabledState); enabledState != nil { - result["enabled_state"] = *enabledState - } - if httpPort := input.HttpPort; httpPort != nil { - result["http_port"] = *httpPort - } - if httpsPort := input.HttpsPort; httpsPort != nil { - result["https_port"] = *httpsPort - } - if priority := input.Priority; priority != nil { - result["priority"] = *priority - } - if weight := input.Weight; weight != nil { - result["weight"] = *weight + for _, v := range *input { + if address := v.Address; address != nil { + result["address"] = *address + } + if backendHostHeader := v.BackendHostHeader; backendHostHeader != nil { + result["backend_host_header"] = *backendHostHeader + } + result["enabled_state"] = string(v.EnabledState) + if httpPort := v.HTTPPort; httpPort != nil { + result["http_port"] = *httpPort + } + if httpsPort := v.HTTPSPort; httpsPort != nil { + result["https_port"] = *httpsPort + } + if priority := v.Priority; priority != nil { + result["priority"] = *priority + } + if weight := v.Weight; weight != nil { + result["weight"] = *weight + } } - return []interface{}{result} } @@ -981,6 +974,21 @@ func flattenArmFrontDoorSubResource(input *frontdoor.SubResource) []interface{} return []interface{}{result} } +func flattenArmFrontDoorSubResources(input *[]frontdoor.SubResource) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + result := make(map[string]interface{}) + + for _,v := range *input { + if id := v.ID; id != nil { + result["id"] = *id + } + } + return []interface{}{result} +} + func flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink) []interface{} { if input == nil { return make([]interface{}, 0) From 8291122291773d5950a1801213629f9ba117bcaf Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 9 Jul 2019 18:00:32 -0700 Subject: [PATCH 05/74] Finalized Schema --- azurerm/helpers/azure/frontdoor.go | 12 +- azurerm/resource_arm_front_door.go | 448 +++++++++++------------- azurerm/resource_arm_front_door_test.go | 4 +- 3 files changed, 214 insertions(+), 250 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index a863e53b0a30..4d9368b9c75b 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -8,9 +8,17 @@ import ( //Frontdoor name must begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens. func ValidateFrontDoorName(i interface{}, k string) (_ []string, errors []error) { - if m, regexErrs := validate.RegExHelper(i, k, `^[\da-zA-Z]([-\da-z]{4,61})[\da-zA-Z]?$`); !m { - errors = append(regexErrs, fmt.Errorf(`%q must begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) + if m, regexErrs := validate.RegExHelper(i, k, `(^[\da-zA-Z])([-\da-zA-Z]{3,61})([\da-zA-Z]$)`); !m { + errors = append(regexErrs, fmt.Errorf(`%q must be between 5 and 63 characters in length and begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) } return nil, errors } + +func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, errors []error) { + if m, regexErrs := validate.RegExHelper(i, k, `(^[\da-zA-Z])([-\da-zA-Z]{1,88})([\da-zA-Z]$)`); !m { + errors = append(regexErrs, fmt.Errorf(`%q must be between 1 and 90 characters in length and begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) + } + + return nil, errors +} \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index e60222bcb1ac..efc5854176fa 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -29,111 +29,152 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, + ValidateFunc: azure.ValidateFrontDoorName, + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, }, "location": azure.SchemaLocation(), - "resource_group": azure.SchemaResourceGroupNameDiffSuppress(), + "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), - "backend_pools": { - Type: schema.TypeList, + "routing_rule": { + Type: schema.TypeList, + MaxItems: 100, Optional: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "backends": { + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "accepted_protocols": { + Type: schema.TypeList, + Optional: true, + MaxItems: 2, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.HTTP), + string(frontdoor.HTTPS), + }, false), + Default: string(frontdoor.HTTP), + }, + }, + "patterns_to_match": { + Type: schema.TypeList, + Optional: true, + MaxItems: 25, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "frontend_endpoints": { + Type: schema.TypeList, + Optional: true, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "redirect_configuration": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "address": { + "custom_fragment": { Type: schema.TypeString, Optional: true, }, - "backend_host_header": { + "custom_host": { Type: schema.TypeString, Optional: true, }, - "enabled_state": { + "custom_path": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Enabled), - string(frontdoor.Disabled), - }, false), - Default: string(frontdoor.Enabled), - }, - "http_port": { - Type: schema.TypeInt, - Optional: true, - }, - "https_port": { - Type: schema.TypeInt, - Optional: true, }, - "priority": { - Type: schema.TypeInt, + "redirect_protocol": { + Type: schema.TypeString, Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.RedirectProtocolHTTPOnly), + string(frontdoor.RedirectProtocolHTTPSOnly), + string(frontdoor.RedirectProtocolMatchRequest), + }, false), }, - "weight": { - Type: schema.TypeInt, + "redirect_type": { + Type: schema.TypeString, Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Found ), + string(frontdoor.Moved ), + string(frontdoor.PermanentRedirect), + string(frontdoor.TemporaryRedirect), + }, false), }, }, }, }, - "health_probe_settings": { + "forwarding_configuration": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { + "backend_pool_name": { + Type: schema.TypeString, + Required: true, + }, + "cache_use_dynamic_compression": { Type: schema.TypeString, Optional: true, + Default: false, }, - }, - }, - }, - "id": { - Type: schema.TypeString, - Optional: true, - }, - "load_balancing_settings": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { + "cache_query_parameter_strip_directive": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.StripAll), + string(frontdoor.StripNone), + }, false), + Default: string(frontdoor.StripNone), + }, + "custom_forwarding_path": { + Type: schema.TypeString, + Required: true, + }, + "forwarding_protocol": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.HTTPOnly), + string(frontdoor.HTTPSOnly), + string(frontdoor.MatchRequest), + }, false), + Default: string(frontdoor.MatchRequest), }, }, }, }, - "name": { - Type: schema.TypeString, - Optional: true, - }, - "resource_state": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.PolicyResourceStateCreating), - string(frontdoor.PolicyResourceStateEnabling), - string(frontdoor.PolicyResourceStateEnabled), - string(frontdoor.PolicyResourceStateDisabling), - string(frontdoor.PolicyResourceStateDisabled), - string(frontdoor.PolicyResourceStateDeleting), - }, false), - Default: string(frontdoor.PolicyResourceStateCreating), - }, }, }, }, - "backend_pools_settings": { Type: schema.TypeList, Optional: true, @@ -141,115 +182,52 @@ func resourceArmFrontDoor() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "enforce_certificate_name_check": { - Type: schema.TypeString, + Type: schema.TypeBool, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Enabled), - string(frontdoor.Disabled), - }, false), - Default: string(frontdoor.Enabled), + Default: true, }, }, }, }, - - "enabled_state": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Enabled), - string(frontdoor.Disabled), - }, false), - Default: string(frontdoor.Enabled), - }, - - "friendly_name": { - Type: schema.TypeString, - Optional: true, - }, - - "frontend_endpoints": { + "load_balancing_setting": { Type: schema.TypeList, + MaxItems: 5000, Optional: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "host_name": { - Type: schema.TypeString, - Optional: true, - }, - "id": { - Type: schema.TypeString, - Optional: true, - }, "name": { Type: schema.TypeString, - Optional: true, - }, - "resource_state": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.PolicyResourceStateCreating), - string(frontdoor.PolicyResourceStateEnabling), - string(frontdoor.PolicyResourceStateEnabled), - string(frontdoor.PolicyResourceStateDisabling), - string(frontdoor.PolicyResourceStateDisabled), - string(frontdoor.PolicyResourceStateDeleting), - }, false), - Default: string(frontdoor.PolicyResourceStateCreating), - }, - "session_affinity_enabled_state": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Enabled), - string(frontdoor.Disabled), - }, false), - Default: string(frontdoor.Enabled), + Required: true, + ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, - "session_affinity_ttl_seconds": { + "sample_size": { Type: schema.TypeInt, Optional: true, + Default: 4, }, - "web_application_firewall_policy_link": { - Type: schema.TypeList, + "successful_samples_required": { + Type: schema.TypeInt, Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Optional: true, - }, - }, - }, + Default: 2, }, }, }, }, - - "health_probe_settings": { + "health_probe_setting": { Type: schema.TypeList, + MaxItems: 5000, Optional: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Optional: true, - }, - "interval_in_seconds": { - Type: schema.TypeInt, - Optional: true, - }, "name": { Type: schema.TypeString, - Optional: true, + Required: true, + ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "path": { Type: schema.TypeString, Optional: true, + Default: "/", }, "protocol": { Type: schema.TypeString, @@ -260,162 +238,140 @@ func resourceArmFrontDoor() *schema.Resource { }, false), Default: string(frontdoor.HTTP), }, - "resource_state": { - Type: schema.TypeString, + "interval_in_seconds": { + Type: schema.TypeInt, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.PolicyResourceStateCreating), - string(frontdoor.PolicyResourceStateEnabling), - string(frontdoor.PolicyResourceStateEnabled), - string(frontdoor.PolicyResourceStateDisabling), - string(frontdoor.PolicyResourceStateDisabled), - string(frontdoor.PolicyResourceStateDeleting), - }, false), - Default: string(frontdoor.PolicyResourceStateCreating), + Default: 120, }, }, }, }, - - "load_balancing_settings": { + "backend_pool": { Type: schema.TypeList, - Optional: true, - MaxItems: 1, + MaxItems: 50, + Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "additional_latency_milliseconds": { - Type: schema.TypeInt, - Optional: true, - }, - "id": { - Type: schema.TypeString, - Optional: true, + "backend": { + Type: schema.TypeList, + MaxItems: 100, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "address": { + Type: schema.TypeString, + Optional: true, + }, + "http_port": { + Type: schema.TypeInt, + Optional: true, + }, + "https_port": { + Type: schema.TypeInt, + Optional: true, + }, + "weight": { + Type: schema.TypeInt, + Optional: true, + }, + "priority": { + Type: schema.TypeInt, + Optional: true, + }, + }, + }, }, "name": { Type: schema.TypeString, - Optional: true, + Required: true, + ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, - "resource_state": { + "health_probe_settings_name": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.PolicyResourceStateCreating), - string(frontdoor.PolicyResourceStateEnabling), - string(frontdoor.PolicyResourceStateEnabled), - string(frontdoor.PolicyResourceStateDisabling), - string(frontdoor.PolicyResourceStateDisabled), - string(frontdoor.PolicyResourceStateDeleting), - }, false), - Default: string(frontdoor.PolicyResourceStateCreating), - }, - "sample_size": { - Type: schema.TypeInt, - Optional: true, }, - "successful_samples_required": { - Type: schema.TypeInt, + "load_balancing_settings_name": { + Type: schema.TypeString, Optional: true, }, }, }, }, - - "resource_state": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.PolicyResourceStateCreating), - string(frontdoor.PolicyResourceStateEnabling), - string(frontdoor.PolicyResourceStateEnabled), - string(frontdoor.PolicyResourceStateDisabling), - string(frontdoor.PolicyResourceStateDisabled), - string(frontdoor.PolicyResourceStateDeleting), - }, false), - Default: string(frontdoor.PolicyResourceStateCreating), - }, - - "routing_rules": { + "frontend_endpoint": { Type: schema.TypeList, + MaxItems: 100, Optional: true, - MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "accepted_protocols": { + "name": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.HTTP), - string(frontdoor.HTTPS), - }, false), - Default: string(frontdoor.HTTP), + ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, - "enabled_state": { + "host_name": { Type: schema.TypeString, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Enabled), - string(frontdoor.Disabled), - }, false), - Default: string(frontdoor.Enabled), }, - "frontend_endpoints": { + "session_affinity_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "session_affinity_ttl_seconds": { + Type: schema.TypeInt, + Optional: true, + }, + "web_application_firewall_policy_link_id": { + Type: schema.TypeString, + Optional: true, + }, + "custom_https_configuration": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "id": { + "certificate_source": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.CertificateSourceAzureKeyVault), + string(frontdoor.CertificateSourceFrontDoor), + }, false), + Default: string(frontdoor.CertificateSourceFrontDoor), + }, + // NOTE: None of these attributes are valid if + // certificate_source is set to FrontDoor + "azure_key_vault_certificate_secret_name": { + Type: schema.TypeString, + Optional: true, + }, + "azure_key_vault_certificate_secret_version": { + Type: schema.TypeString, + Optional: true, + }, + "azure_key_vault_certificate_vault_id": { Type: schema.TypeString, Optional: true, }, }, }, }, - "id": { - Type: schema.TypeString, - Optional: true, - }, - "name": { - Type: schema.TypeString, - Optional: true, - }, - "patterns_to_match": { - Type: schema.TypeString, - Optional: true, - }, - "resource_state": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.PolicyResourceStateCreating), - string(frontdoor.PolicyResourceStateEnabling), - string(frontdoor.PolicyResourceStateEnabled), - string(frontdoor.PolicyResourceStateDisabling), - string(frontdoor.PolicyResourceStateDisabled), - string(frontdoor.PolicyResourceStateDeleting), - }, false), - Default: string(frontdoor.PolicyResourceStateCreating), - }, }, }, }, - "tags": tagsSchema(), - - "cname": { - Type: schema.TypeString, - Computed: true, - }, - - "provisioning_state": { + "friendly_name": { Type: schema.TypeString, - Computed: true, + Optional: true, }, - "type": { - Type: schema.TypeString, - Computed: true, - }, + "tags": tagsSchema(), }, } } diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 4ad88f3aa914..5c2165d1515a 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -2,11 +2,11 @@ package azurerm import ( "fmt" - "testing" + //"testing" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + //"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) From 7d6636682bf33eadc0f6ec9cbd77b32a5d533aac Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 10 Jul 2019 15:59:59 -0700 Subject: [PATCH 06/74] WIP Current state --- azurerm/resource_arm_front_door.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index efc5854176fa..9d6fce010a9f 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -407,6 +407,11 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) routingRules := d.Get("routing_rules").([]interface{}) tags := d.Get("tags").(map[string]interface{}) + // Validate config settings are valid + if err := azure.ValidateFrontdoor(d); err != nil { + return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + frontDoorParameters := frontdoor.FrontDoor{ Location: utils.String(location), Properties: &frontdoor.Properties{ From 0f412eb5e6a694ce763b8653d857702bafa27c28 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 15 Jul 2019 18:50:22 -0700 Subject: [PATCH 07/74] WIP adding validation --- azurerm/helpers/azure/frontdoor.go | 63 ++++++++++++++++++++++++++++++ azurerm/resource_arm_front_door.go | 13 +++++- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 4d9368b9c75b..c759f8e76c9c 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -3,6 +3,7 @@ package azure import ( "fmt" + "github.com/hashicorp/terraform/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" ) @@ -21,4 +22,66 @@ func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, er } return nil, errors +} + +func ValidateFrontdoor(d *schema.ResourceData) error { + routingRules := d.Get("routing_rule").([]interface{}) + configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) + + // if len(routingRules) == 0 { + // return nil + // } + + if len(configFrontendEndpoints) == 0 { + return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) + } + + // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule + // start routing rule validation + if routingRules != nil { + for _, rr := range routingRules { + routingRule := rr.(map[string]interface{}) + routingRuleName := routingRule["name"] + found := false + + redirectConfig := routingRule["redirect_configuration"].([]interface{}) + forwardConfig := routingRule["forwarding_configuration"].([]interface{}) + + // 1. validate that only one type of redirect configuration is set per routing rule + if len(redirectConfig) == 1 && len(forwardConfig) == 1 { + return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per routing rule`, routingRuleName) + } + + // 2. validate that each routing rule frontend_endpoints are actually defined in the resource schema + if rrFrontends := routingRule["frontend_endpoints"].([]interface{}); len(rrFrontends) > 0 { + + for _, rrFrontend := range rrFrontends { + // Get the name of the frontend defined in the routing rule + frontendsName := rrFrontend.(string) + found = false + + // Loop over all of the defined frontend endpoints in the config + // seeing if we find the routing rule frontend in the list + for _, configFrontendEndpoint := range configFrontendEndpoints { + cFrontend := configFrontendEndpoint.(map[string]interface{}) + configFrontendName := cFrontend["name"] + if( frontendsName == configFrontendName){ + found = true + break + } + } + + if !found { + return fmt.Errorf(`"routing_rule":%q "frontend_endpoints":%q was not found in the configuration file. verify you have the "frontend_endpoint":%q defined in the configuration file`, routingRuleName, frontendsName, frontendsName) + } + } + } else { + return fmt.Errorf(`"routing_rule": %q must have at least one "frontend_endpoints" defined`, routingRuleName) + } + + } // end routing rule validation + + } // end routing rule nil check + + return nil } \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 9d6fce010a9f..cae4e8b697c2 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -377,11 +377,20 @@ func resourceArmFrontDoor() *schema.Resource { } func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) error { + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) + + if err := azure.ValidateFrontdoor(d); err != nil { + return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + +return nil + + client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group").(string) + if requireResourcesToBeImported { resp, err := client.Get(ctx, resourceGroup, name) From 4440babacb0c4653b246f66f6c0eddf1370089a7 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 17 Jul 2019 15:43:24 -0700 Subject: [PATCH 08/74] WIP Finished validation code --- azurerm/helpers/azure/frontdoor.go | 114 +++++++++++++++++++++++++---- azurerm/resource_arm_front_door.go | 44 +++++------ 2 files changed, 120 insertions(+), 38 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index c759f8e76c9c..6fc16cc5c0b4 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -3,6 +3,7 @@ package azure import ( "fmt" + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/hashicorp/terraform/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" ) @@ -27,6 +28,9 @@ func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, er func ValidateFrontdoor(d *schema.ResourceData) error { routingRules := d.Get("routing_rule").([]interface{}) configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) + backendPools := d.Get("backend_pool").([]interface{}) + loadBalancingSettings:= d.Get("backend_pool_load_balancing").([]interface{}) + healthProbeSettings:= d.Get("backend_pool_health_probe").([]interface{}) // if len(routingRules) == 0 { // return nil @@ -35,10 +39,9 @@ func ValidateFrontdoor(d *schema.ResourceData) error { if len(configFrontendEndpoints) == 0 { return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) } - - // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule - // start routing rule validation + if routingRules != nil { + // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule for _, rr := range routingRules { routingRule := rr.(map[string]interface{}) routingRuleName := routingRule["name"] @@ -47,41 +50,124 @@ func ValidateFrontdoor(d *schema.ResourceData) error { redirectConfig := routingRule["redirect_configuration"].([]interface{}) forwardConfig := routingRule["forwarding_configuration"].([]interface{}) - // 1. validate that only one type of redirect configuration is set per routing rule + // Check 1. validate that only one configuration type is defined per routing rule if len(redirectConfig) == 1 && len(forwardConfig) == 1 { return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per routing rule`, routingRuleName) } - // 2. validate that each routing rule frontend_endpoints are actually defined in the resource schema - if rrFrontends := routingRule["frontend_endpoints"].([]interface{}); len(rrFrontends) > 0 { + // Check 2. validate that each routing rule frontend_endpoints are actually defined in the resource schema + if routingRuleFrontends := routingRule["frontend_endpoints"].([]interface{}); len(routingRuleFrontends) > 0 { - for _, rrFrontend := range rrFrontends { + for _, routingRuleFrontend := range routingRuleFrontends { // Get the name of the frontend defined in the routing rule - frontendsName := rrFrontend.(string) + routingRulefrontendName := routingRuleFrontend.(string) found = false // Loop over all of the defined frontend endpoints in the config // seeing if we find the routing rule frontend in the list for _, configFrontendEndpoint := range configFrontendEndpoints { - cFrontend := configFrontendEndpoint.(map[string]interface{}) - configFrontendName := cFrontend["name"] - if( frontendsName == configFrontendName){ + configFrontend := configFrontendEndpoint.(map[string]interface{}) + configFrontendName := configFrontend["name"] + if( routingRulefrontendName == configFrontendName){ found = true break } } if !found { - return fmt.Errorf(`"routing_rule":%q "frontend_endpoints":%q was not found in the configuration file. verify you have the "frontend_endpoint":%q defined in the configuration file`, routingRuleName, frontendsName, frontendsName) + return fmt.Errorf(`"routing_rule":%q "frontend_endpoints":%q was not found in the configuration file. verify you have the "frontend_endpoint":%q defined in the configuration file`, routingRuleName, routingRulefrontendName, routingRulefrontendName) } } } else { return fmt.Errorf(`"routing_rule": %q must have at least one "frontend_endpoints" defined`, routingRuleName) } + } + } + + // Verify backend pool load balancing settings and health probe settings are defined in the resource schema + if backendPools != nil { + + for _, bp := range backendPools { + backendPool := bp.(map[string]interface{}) + backendPoolName := backendPool["name"] + backendPoolLoadBalancingName := backendPool["load_balancing_name"] + backendPoolHealthProbeName := backendPool["health_probe_name"] + found := false - } // end routing rule validation + // Verify backend pool load balancing settings name exists + for _, lbs := range loadBalancingSettings{ + loadBalancing := lbs.(map[string]interface{}) + loadBalancingName := loadBalancing["name"] + + if loadBalancingName == backendPoolLoadBalancingName { + found = true + break + } + } - } // end routing rule nil check + if !found { + return fmt.Errorf(`"backend_pool":%q "load_balancing_name":%q was not found in the configuration file. verify you have the "backend_pool_load_balancing":%q defined in the configuration file`, backendPoolName, backendPoolLoadBalancingName, backendPoolLoadBalancingName) + } + + found = false + + // Verify health probe settings name exists + for _, hps := range healthProbeSettings{ + healthProbe := hps.(map[string]interface{}) + healthProbeName := healthProbe["name"] + + if healthProbeName == backendPoolHealthProbeName { + found = true + break + } + } + + if !found { + return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) + } + + } + } else { + return fmt.Errorf(`"backend_pool": must have at least one "backend" defined`) + } + + // Verify frontend endpoints custom https configuration is valid if defined + for _, configFrontendEndpoint := range configFrontendEndpoints { + if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { + FrontendName := configFrontend["name"] + if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { + customHttpsConfiguration := chc[0].(map[string]interface{}) + certificateSource := customHttpsConfiguration["certificate_source"] + if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { + if !azureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { + return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must have values in the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) + } + } else { + if azureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { + return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must be removed from the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) + } + } + } + } + } return nil +} + +func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]interface{}, MatchAllKeys bool) bool { + certificateSecretName := customHttpsConfiguration["azure_key_vault_certificate_secret_name"] + certificateSecretVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"] + certificateVaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"] + + if MatchAllKeys { + if certificateSecretName != "" && certificateSecretVersion != "" && certificateVaultId != "" { + return true + } + } else { + if certificateSecretName != "" || certificateSecretVersion != "" || certificateVaultId != "" { + return true + } + } + + return false } \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index cae4e8b697c2..129fa4674f73 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -54,7 +54,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "name": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "enabled": { @@ -81,11 +81,12 @@ func resourceArmFrontDoor() *schema.Resource { MaxItems: 25, Elem: &schema.Schema{ Type: schema.TypeString, + Default: "/*", }, }, "frontend_endpoints": { Type: schema.TypeList, - Optional: true, + Required: true, MaxItems: 100, Elem: &schema.Schema{ Type: schema.TypeString, @@ -175,21 +176,11 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, - "backend_pools_settings": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "enforce_certificate_name_check": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - }, - }, + "enforce_backend_pools_certificate_name_check": { + Type: schema.TypeBool, + Required: true, }, - "load_balancing_setting": { + "backend_pool_load_balancing": { Type: schema.TypeList, MaxItems: 5000, Optional: true, @@ -213,7 +204,7 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, - "health_probe_setting": { + "backend_pool_health_probe": { Type: schema.TypeList, MaxItems: 5000, Optional: true, @@ -265,23 +256,28 @@ func resourceArmFrontDoor() *schema.Resource { }, "address": { Type: schema.TypeString, - Optional: true, + Required: true, }, "http_port": { Type: schema.TypeInt, - Optional: true, + Required: true, + ValidateFunc: validation.IntBetween(1, 65535), }, "https_port": { Type: schema.TypeInt, - Optional: true, + Required: true, + ValidateFunc: validation.IntBetween(1, 65535), }, "weight": { Type: schema.TypeInt, Optional: true, + ValidateFunc: validation.IntBetween(1, 1000), + Default: 50, }, "priority": { Type: schema.TypeInt, - Optional: true, + Required: true, + ValidateFunc: validation.IntBetween(1, 5), }, }, }, @@ -291,11 +287,11 @@ func resourceArmFrontDoor() *schema.Resource { Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, - "health_probe_settings_name": { + "health_probe_name": { Type: schema.TypeString, Optional: true, }, - "load_balancing_settings_name": { + "load_balancing_name": { Type: schema.TypeString, Optional: true, }, @@ -315,7 +311,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "host_name": { Type: schema.TypeString, - Optional: true, + Required: true, }, "session_affinity_enabled": { Type: schema.TypeBool, From 04adc2fd60e13f995fbd41ce0bc78bb88e504c6f Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 19 Jul 2019 16:44:31 -0700 Subject: [PATCH 09/74] WIP Expand RoutingRules working --- azurerm/helpers/azure/frontdoor.go | 17 ++- azurerm/resource_arm_front_door.go | 231 +++++++++++++++++++++++------ 2 files changed, 193 insertions(+), 55 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 6fc16cc5c0b4..a858b5ea6ea7 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -2,6 +2,7 @@ package azure import ( "fmt" + "strings" "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/hashicorp/terraform/helper/schema" @@ -32,10 +33,6 @@ func ValidateFrontdoor(d *schema.ResourceData) error { loadBalancingSettings:= d.Get("backend_pool_load_balancing").([]interface{}) healthProbeSettings:= d.Get("backend_pool_health_probe").([]interface{}) - // if len(routingRules) == 0 { - // return nil - // } - if len(configFrontendEndpoints) == 0 { return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) } @@ -160,14 +157,22 @@ func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]inter certificateVaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"] if MatchAllKeys { - if certificateSecretName != "" && certificateSecretVersion != "" && certificateVaultId != "" { + if strings.TrimSpace(certificateSecretName.(string)) != "" && strings.TrimSpace(certificateSecretVersion.(string)) != "" && strings.TrimSpace(certificateVaultId.(string)) != "" { return true } } else { - if certificateSecretName != "" || certificateSecretVersion != "" || certificateVaultId != "" { + if strings.TrimSpace(certificateSecretName.(string)) != "" || strings.TrimSpace(certificateSecretVersion.(string)) != "" || strings.TrimSpace(certificateVaultId.(string)) != "" { return true } } return false +} + +func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, serviceName string, resourceType string, resourceName string) string { + if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(serviceName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { + return "" + } + + return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontDoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) } \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 129fa4674f73..977d2bc1c471 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -110,6 +110,10 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeString, Optional: true, }, + "custom_query_string": { + Type: schema.TypeString, + Optional: true, + }, "redirect_protocol": { Type: schema.TypeString, Optional: true, @@ -123,8 +127,8 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeString, Optional: true, ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Found ), - string(frontdoor.Moved ), + string(frontdoor.Found), + string(frontdoor.Moved), string(frontdoor.PermanentRedirect), string(frontdoor.TemporaryRedirect), }, false), @@ -380,13 +384,9 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) } -return nil - - client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext - - + subscriptionId := meta.(*ArmClient).subscriptionId if requireResourcesToBeImported { resp, err := client.Get(ctx, resourceGroup, name) @@ -400,35 +400,33 @@ return nil } } + // if subId := azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, name, resourceType, resourceName); subId == "" { + // return fmt.Errorf("Error Front Door %q (Resource Group %q): unable to creating ID for sub resource", name, resourceGroup) + // } + location := azure.NormalizeLocation(d.Get("location").(string)) - backendPools := d.Get("backend_pools").([]interface{}) - backendPoolsSettings := d.Get("backend_pools_settings").([]interface{}) - enabledState := d.Get("enabled_state").(string) friendlyName := d.Get("friendly_name").(string) - frontendEndpoints := d.Get("frontend_endpoints").([]interface{}) - healthProbeSettings := d.Get("health_probe_settings").([]interface{}) - loadBalancingSettings := d.Get("load_balancing_settings").([]interface{}) - resourceState := d.Get("resource_state").(string) routingRules := d.Get("routing_rules").([]interface{}) + loadBalancingSettings := d.Get("load_balancing_settings").([]interface{}) + healthProbeSettings := d.Get("health_probe_settings").([]interface{}) + backendPools := d.Get("backend_pools").([]interface{}) + frontendEndpoints := d.Get("frontend_endpoints").([]interface{}) + backendPoolsSettings := d.Get("backend_pools_settings").([]interface{}) + enabledState := d.Get("enabled").(bool) tags := d.Get("tags").(map[string]interface{}) - // Validate config settings are valid - if err := azure.ValidateFrontdoor(d); err != nil { - return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) - } - frontDoorParameters := frontdoor.FrontDoor{ Location: utils.String(location), Properties: &frontdoor.Properties{ + FriendlyName: utils.String(friendlyName), + RoutingRules: expandArmFrontDoorRoutingRule(routingRules, subscriptionId, resourceGroup, name), BackendPools: expandArmFrontDoorBackendPool(backendPools), BackendPoolsSettings: expandArmFrontDoorBackendPoolsSettings(backendPoolsSettings), - EnabledState: frontdoor.EnabledState(enabledState), - FriendlyName: utils.String(friendlyName), FrontendEndpoints: expandArmFrontDoorFrontendEndpoint(frontendEndpoints), HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings), LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings), - ResourceState: frontdoor.ResourceState(resourceState), - RoutingRules: expandArmFrontDoorRoutingRule(routingRules), + EnabledState: expandArmFrontDoorEnabledState(enabledState), + }, Tags: expandTags(tags), } @@ -658,32 +656,50 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}) *[]frontd return &[]frontdoor.LoadBalancingSettingsModel{result} } -func expandArmFrontDoorRoutingRule(input []interface{}) *[]frontdoor.RoutingRule { +func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, resourceGroup, serviceName string) *[]frontdoor.RoutingRule { if len(input) == 0 { return nil } - v := input[0].(map[string]interface{}) - id := v["id"].(string) - frontendEndpoints := v["frontend_endpoints"].([]interface{}) - acceptedProtocols := v["accepted_protocols"].(*[]frontdoor.Protocol) - patternsToMatch := v["patterns_to_match"].(*[]string) - enabledState := v["enabled_state"].(string) - resourceState := v["resource_state"].(string) - name := v["name"].(string) + output := make([]frontdoor.RoutingRule, 0) - result := frontdoor.RoutingRule{ - ID: utils.String(id), - Name: utils.String(name), - RoutingRuleProperties: &frontdoor.RoutingRuleProperties{ - AcceptedProtocols: acceptedProtocols, - EnabledState: frontdoor.RoutingRuleEnabledState(enabledState), - FrontendEndpoints: expandArmFrontDoorSubResources(frontendEndpoints), - PatternsToMatch: patternsToMatch, - ResourceState: frontdoor.ResourceState(resourceState), - }, + for _, rr := range input { + routingRule := rr.(map[string]interface{}) + + id := routingRule["id"].(string) + frontendEndpoints := routingRule["frontend_endpoints"].([]interface{}) + acceptedProtocols := routingRule["accepted_protocols"].(*[]frontdoor.Protocol) + patternsToMatch := routingRule["patterns_to_match"].(*[]string) + enabled := routingRule["enabled"].(bool) + name := routingRule["name"].(string) + + var routingConfiguration frontdoor.BasicRouteConfiguration + + if rc := routingRule["redirect_configuration"].([]interface{}); rc != nil { + redirectConfiguration := expandArmFrontDoorRedirectConfiguration(rc) + routingConfiguration = redirectConfiguration + } else if fc := routingRule["forwarding_configuration"].([]interface{}); fc != nil { + forwardingConfiguration := expandArmFrontDoorForwardingConfiguration(fc, subscriptionId, resourceGroup, serviceName) + routingConfiguration = forwardingConfiguration + } + + currentRoutingRule := frontdoor.RoutingRule{ + ID: utils.String(id), + Name: utils.String(name), + RoutingRuleProperties: &frontdoor.RoutingRuleProperties{ + //ResourceState: + FrontendEndpoints: expandArmFrontDoorFrontEndEndpoints(frontendEndpoints, subscriptionId, resourceGroup, serviceName), + AcceptedProtocols: acceptedProtocols, + PatternsToMatch: patternsToMatch, + EnabledState: frontdoor.RoutingRuleEnabledState(expandArmFrontDoorEnabledState(enabled)), + RouteConfiguration: routingConfiguration, + }, + } + + output = append(output, currentRoutingRule) } - return &[]frontdoor.RoutingRule{result} + + return &output } func expandArmFrontDoorBackend(input []interface{}) *[]frontdoor.Backend { @@ -726,18 +742,27 @@ func expandArmFrontDoorSubResource(input []interface{}) *frontdoor.SubResource { return &result } -func expandArmFrontDoorSubResources(input []interface{}) *[]frontdoor.SubResource { +func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.SubResource { if len(input) == 0 { - return nil + return &[]frontdoor.SubResource{} } + + output := make([]frontdoor.SubResource, 0) + v := input[0].(map[string]interface{}) - id := v["id"].(string) + for _, SubResource := range v { + frontendEndpointName := SubResource.(string) + id := azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", frontendEndpointName) - result := frontdoor.SubResource{ - ID: utils.String(id), + result := frontdoor.SubResource{ + ID: utils.String(id), + } + + output = append(output, result) } - return &[]frontdoor.SubResource{result} + + return &output } func expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input []interface{}) *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink { @@ -753,6 +778,114 @@ func expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPo } return &result } + +func expandArmFrontDoorEnabledState(input interface{}) frontdoor.EnabledState { + v := input.(bool) + result := frontdoor.EnabledStateDisabled + + if v { + result = frontdoor.EnabledStateEnabled + } + + return result +} + +func expandArmFrontDoorDynamicDynamicCompression(input bool) frontdoor.DynamicCompressionEnabled { + result := frontdoor.DynamicCompressionEnabledDisabled + + if input { + result = frontdoor.DynamicCompressionEnabledEnabled + } + + return result +} + +func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.RedirectConfiguration { + if len(input) == 0 { + return frontdoor.RedirectConfiguration{} + } + v := input[0].(map[string]interface{}) + + redirectType := v["redirect_type"].(frontdoor.RedirectType) + redirectProtocol := v["redirect_protocol"].(frontdoor.RedirectProtocol) + customHost := v["custom_host"].(string) + customPath := v["custom_path"].(string) + customFragment := v["custom_fragment"].(string) + customQueryString := v["custom_query_string"].(string) + + redirectConfiguration := frontdoor.RedirectConfiguration { + RedirectType: redirectType, + RedirectProtocol: redirectProtocol, + CustomHost: utils.String(customHost), + CustomPath: utils.String(customPath), + CustomFragment: utils.String(customFragment), + CustomQueryString: utils.String(customQueryString), + OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration, + } + + return redirectConfiguration +} + +func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscriptionId string, resourceGroup, serviceName string) frontdoor.ForwardingConfiguration { + if len(input) == 0 { + return frontdoor.ForwardingConfiguration{} + } + v := input[0].(map[string]interface{}) + + customForwardingPath := v["custom_forwarding_path"].(string) + forwardingProtocol := v["forwarding_protocol"].(frontdoor.ForwardingProtocol) + cacheUseDynamicCompression := v["cache_use_dynamic_compression"].(bool) + cacheQueryParameterStripDirective := v["cache_query_parameter_strip_directive"].(frontdoor.Query) + backendPoolName := v["backend_pool_name"].(string) + + cacheConfiguration := &frontdoor.CacheConfiguration { + QueryParameterStripDirective: cacheQueryParameterStripDirective, + DynamicCompression: expandArmFrontDoorDynamicDynamicCompression(cacheUseDynamicCompression), + } + + backend := &frontdoor.SubResource{ + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "backendPools", backendPoolName)), + } + + forwardingConfiguration := frontdoor.ForwardingConfiguration { + CustomForwardingPath: utils.String(customForwardingPath), + ForwardingProtocol: forwardingProtocol, + CacheConfiguration: cacheConfiguration, + BackendPool: backend, + OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration, + } + + return forwardingConfiguration +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + func flattenArmFrontDoorBackendPool(input *[]frontdoor.BackendPool) []interface{} { if input == nil { From cf9096f734763591e8de9b3a53d17a9f1dfdb3b8 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 22 Jul 2019 19:21:45 -0700 Subject: [PATCH 10/74] WIP All expand func implemented --- azurerm/resource_arm_front_door.go | 425 +++++++++++++++++------------ 1 file changed, 253 insertions(+), 172 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 977d2bc1c471..2271b1247925 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -205,6 +205,11 @@ func resourceArmFrontDoor() *schema.Resource { Optional: true, Default: 2, }, + "additional_latency_milliseconds": { + Type: schema.TypeInt, + Optional: true, + Default: 2, + }, }, }, }, @@ -283,6 +288,10 @@ func resourceArmFrontDoor() *schema.Resource { Required: true, ValidateFunc: validation.IntBetween(1, 5), }, + "host_header": { + Type: schema.TypeString, + Optional: true, + }, }, }, }, @@ -305,7 +314,7 @@ func resourceArmFrontDoor() *schema.Resource { "frontend_endpoint": { Type: schema.TypeList, MaxItems: 100, - Optional: true, + Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { @@ -326,10 +335,6 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeInt, Optional: true, }, - "web_application_firewall_policy_link_id": { - Type: schema.TypeString, - Optional: true, - }, "custom_https_configuration": { Type: schema.TypeList, Optional: true, @@ -406,12 +411,12 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) location := azure.NormalizeLocation(d.Get("location").(string)) friendlyName := d.Get("friendly_name").(string) - routingRules := d.Get("routing_rules").([]interface{}) - loadBalancingSettings := d.Get("load_balancing_settings").([]interface{}) - healthProbeSettings := d.Get("health_probe_settings").([]interface{}) - backendPools := d.Get("backend_pools").([]interface{}) - frontendEndpoints := d.Get("frontend_endpoints").([]interface{}) - backendPoolsSettings := d.Get("backend_pools_settings").([]interface{}) + routingRules := d.Get("routing_rule").([]interface{}) + loadBalancingSettings := d.Get("backend_pool_load_balancing").([]interface{}) + healthProbeSettings := d.Get("backend_pool_health_probe").([]interface{}) + backendPools := d.Get("backend_pool").([]interface{}) + frontendEndpoints := d.Get("frontend_endpoint").([]interface{}) + backendPoolsSettings := d.Get("enforce_backend_pools_certificate_name_check").(bool) enabledState := d.Get("enabled").(bool) tags := d.Get("tags").(map[string]interface{}) @@ -420,11 +425,11 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) Properties: &frontdoor.Properties{ FriendlyName: utils.String(friendlyName), RoutingRules: expandArmFrontDoorRoutingRule(routingRules, subscriptionId, resourceGroup, name), - BackendPools: expandArmFrontDoorBackendPool(backendPools), + BackendPools: expandArmFrontDoorBackendPools(backendPools, subscriptionId, resourceGroup, name), BackendPoolsSettings: expandArmFrontDoorBackendPoolsSettings(backendPoolsSettings), - FrontendEndpoints: expandArmFrontDoorFrontendEndpoint(frontendEndpoints), - HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings), - LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings), + FrontendEndpoints: expandArmFrontDoorFrontendEndpoint(frontendEndpoints, subscriptionId, resourceGroup, name), + HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings, subscriptionId, resourceGroup, name), + LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings, subscriptionId, resourceGroup, name), EnabledState: expandArmFrontDoorEnabledState(enabledState), }, @@ -448,7 +453,8 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } d.SetId(*resp.ID) - return resourceArmFrontDoorRead(d, meta) + //return resourceArmFrontDoorRead(d, meta) + return nil } func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { @@ -487,8 +493,8 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { d.Set("cname", properties.Cname) d.Set("enabled_state", string(properties.EnabledState)) d.Set("friendly_name", properties.FriendlyName) - if err := d.Set("frontend_endpoints", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { - return fmt.Errorf("Error setting `frontend_endpoints`: %+v", err) + if err := d.Set("frontend_endpoint", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { + return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) } if err := d.Set("health_probe_settings", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { return fmt.Errorf("Error setting `health_probe_settings`: %+v", err) @@ -536,124 +542,237 @@ func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error return nil } -func expandArmFrontDoorBackendPool(input []interface{}) *[]frontdoor.BackendPool { +func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.BackendPool { if len(input) == 0 { - return nil + return &[]frontdoor.BackendPool{} } - v := input[0].(map[string]interface{}) - id := v["id"].(string) - backends := v["backends"].([]interface{}) - loadBalancingSettings := v["load_balancing_settings"].([]interface{}) - healthProbeSettings := v["health_probe_settings"].([]interface{}) - resourceState := v["resource_state"].(string) - name := v["name"].(string) - - result := frontdoor.BackendPool{ - ID: utils.String(id), - Name: utils.String(name), - BackendPoolProperties: &frontdoor.BackendPoolProperties{ - Backends: expandArmFrontDoorBackend(backends), - HealthProbeSettings: expandArmFrontDoorSubResource(healthProbeSettings), - LoadBalancingSettings: expandArmFrontDoorSubResource(loadBalancingSettings), - ResourceState: frontdoor.ResourceState(resourceState), - }, + output := make([]frontdoor.BackendPool, 0) + + for _, bp := range input { + backendPool := bp.(map[string]interface{}) + + backendPoolName := backendPool["name"].(string) + backendPoolLoadBalancingName := backendPool["load_balancing_name"].(string) + backendPoolHealthProbeName := backendPool["health_probe_name"].(string) + + backends := backendPool["backend"].([]interface{}) + + result := frontdoor.BackendPool{ + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "backendPools", backendPoolName)), + Name: utils.String(backendPoolName), + BackendPoolProperties: &frontdoor.BackendPoolProperties{ + // ResourceState + Backends: expandArmFrontDoorBackend(backends), + LoadBalancingSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "loadBalancingSettings", backendPoolLoadBalancingName), + HealthProbeSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "healthProbeSettings", backendPoolHealthProbeName), + }, + } + + output = append(output, result) } - return &[]frontdoor.BackendPool{result} + + return &output } -func expandArmFrontDoorBackendPoolsSettings(input []interface{}) *frontdoor.BackendPoolsSettings { +func expandArmFrontDoorBackend(input []interface{}) *[]frontdoor.Backend { if len(input) == 0 { - return nil + return &[]frontdoor.Backend{} } - v := input[0].(map[string]interface{}) - enforceCertificateNameCheck := v["enforce_certificate_name_check"].(string) + output := make([]frontdoor.Backend, 0) + + for _, be := range input { + backend := be.(map[string]interface{}) + + address := backend["address"].(string) + httpPort := backend["http_port"].(int32) + httpsPort := backend["https_port"].(int32) + enabled := backend["enabled"].(bool) + priority := backend["priority"].(int32) + weight := backend["weight"].(int32) + hostHeader := backend["host_header"].(string) + + result := frontdoor.Backend{ + Address: utils.String(address), + BackendHostHeader: utils.String(hostHeader), + EnabledState: expandArmFrontDoorBackendEnabledState(enabled), + HTTPPort: utils.Int32(httpPort), + HTTPSPort: utils.Int32(httpsPort), + Priority: utils.Int32(priority), + Weight: utils.Int32(weight), + } + + output = append(output, result) + } + + return &output +} + +func expandArmFrontDoorBackendEnabledState(isEnabled bool) frontdoor.BackendEnabledState { + if isEnabled { + return frontdoor.Enabled + } + + return frontdoor.Disabled +} + +func expandArmFrontDoorBackendPoolsSettings(enforceCertificateNameCheck bool) *frontdoor.BackendPoolsSettings { + + enforceCheck := frontdoor.EnforceCertificateNameCheckEnabledStateDisabled + + if enforceCertificateNameCheck { + enforceCheck = frontdoor.EnforceCertificateNameCheckEnabledStateEnabled + } result := frontdoor.BackendPoolsSettings{ - EnforceCertificateNameCheck: frontdoor.EnforceCertificateNameCheckEnabledState(enforceCertificateNameCheck), + EnforceCertificateNameCheck: enforceCheck, } + return &result } -func expandArmFrontDoorFrontendEndpoint(input []interface{}) *[]frontdoor.FrontendEndpoint { +func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.FrontendEndpoint { if len(input) == 0 { - return nil + return &[]frontdoor.FrontendEndpoint{} } - v := input[0].(map[string]interface{}) - id := v["id"].(string) - hostName := v["host_name"].(string) - sessionAffinityEnabledState := v["session_affinity_enabled_state"].(string) - sessionAffinityTtlSeconds := v["session_affinity_ttl_seconds"].(int32) - webApplicationFirewallPolicyLink := v["web_application_firewall_policy_link"].([]interface{}) - resourceState := v["resource_state"].(string) - name := v["name"].(string) - - result := frontdoor.FrontendEndpoint{ - ID: utils.String(id), - Name: utils.String(name), - FrontendEndpointProperties: &frontdoor.FrontendEndpointProperties{ - HostName: utils.String(hostName), - ResourceState: frontdoor.ResourceState(resourceState), - SessionAffinityEnabledState: frontdoor.SessionAffinityEnabledState(sessionAffinityEnabledState), - SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), - WebApplicationFirewallPolicyLink: expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(webApplicationFirewallPolicyLink), - }, + output := make([]frontdoor.FrontendEndpoint, 0) + + for _, frontendEndpoints := range input { + frontendEndpoint := frontendEndpoints.(map[string]interface{}) + + hostName := frontendEndpoint["host_name"].(string) + isSessionAffinityEnabled := frontendEndpoint["session_affinity_enabled"].(bool) + sessionAffinityTtlSeconds := frontendEndpoint["session_affinity_ttl_seconds"].(int32) + customHttpsConfiguration := frontendEndpoint["custom_https_configuration"].([]interface{}) + name := frontendEndpoint["name"].(string) + id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", name)) + + sessionAffinityEnabled := frontdoor.SessionAffinityEnabledStateDisabled + + if isSessionAffinityEnabled { + sessionAffinityEnabled = frontdoor.SessionAffinityEnabledStateEnabled + } + + result := frontdoor.FrontendEndpoint{ + ID: id, + Name: utils.String(name), + FrontendEndpointProperties: &frontdoor.FrontendEndpointProperties{ + // ResourceState: + // CustomHTTPSProvisioningState: + // CustomHTTPSProvisioningSubstate: + CustomHTTPSConfiguration: expandArmFrontDoorCustomHTTPSConfiguration(customHttpsConfiguration), + HostName: utils.String(hostName), + SessionAffinityEnabledState: sessionAffinityEnabled, + SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), + // WebApplicationFirewallPolicyLink: + + }, + } + + output = append(output, result) } - return &[]frontdoor.FrontendEndpoint{result} + + return &output } -func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}) *[]frontdoor.HealthProbeSettingsModel { +func expandArmFrontDoorCustomHTTPSConfiguration(input []interface{}) *frontdoor.CustomHTTPSConfiguration { if len(input) == 0 { - return nil + return &frontdoor.CustomHTTPSConfiguration{} } + v := input[0].(map[string]interface{}) + certSource := v["certificate_source"].(string) + + result := frontdoor.CustomHTTPSConfiguration { + ProtocolType: frontdoor.ServerNameIndication, + } - id := v["id"].(string) - path := v["path"].(string) - protocol := v["protocol"].(string) - intervalInSeconds := v["interval_in_seconds"].(int32) - resourceState := v["resource_state"].(string) - name := v["name"].(string) - - result := frontdoor.HealthProbeSettingsModel{ - ID: utils.String(id), - Name: utils.String(name), - HealthProbeSettingsProperties: &frontdoor.HealthProbeSettingsProperties{ - IntervalInSeconds: utils.Int32(intervalInSeconds), - Path: utils.String(path), - Protocol: frontdoor.Protocol(protocol), - ResourceState: frontdoor.ResourceState(resourceState), - }, + if certSource == "AzureKeyVault" { + vaultSecret := v["azure_key_vault_certificate_secret_name"].(string) + vaultVersion := v["azure_key_vault_certificate_secret_version"].(string) + vaultId := v["azure_key_vault_certificate_vault_id"].(string) + + result.CertificateSource = frontdoor.CertificateSourceAzureKeyVault + result.KeyVaultCertificateSourceParameters = &frontdoor.KeyVaultCertificateSourceParameters{ + Vault: &frontdoor.KeyVaultCertificateSourceParametersVault { + ID: utils.String(vaultId), + }, + SecretName: utils.String(vaultSecret), + SecretVersion:utils.String(vaultVersion), + } + } else { + result.CertificateSource = frontdoor.CertificateSourceFrontDoor + result.CertificateSourceParameters = &frontdoor.CertificateSourceParameters{ + CertificateType: frontdoor.Dedicated, + } + } + + return &result +} + +func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.HealthProbeSettingsModel { + if len(input) == 0 { + return &[]frontdoor.HealthProbeSettingsModel{} + } + + output := make([]frontdoor.HealthProbeSettingsModel, 0) + + for _,hps := range input { + v := hps.(map[string]interface{}) + + path := v["path"].(string) + protocol := v["protocol"].(string) + intervalInSeconds := v["interval_in_seconds"].(int32) + name := v["name"].(string) + + result := frontdoor.HealthProbeSettingsModel{ + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "healthProbeSettings", name)), + Name: utils.String(name), + HealthProbeSettingsProperties: &frontdoor.HealthProbeSettingsProperties{ + IntervalInSeconds: utils.Int32(intervalInSeconds), + Path: utils.String(path), + Protocol: frontdoor.Protocol(protocol), + }, + } + + output = append(output, result) } - return &[]frontdoor.HealthProbeSettingsModel{result} + + return &output } -func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}) *[]frontdoor.LoadBalancingSettingsModel { +func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.LoadBalancingSettingsModel { if len(input) == 0 { - return nil + return &[]frontdoor.LoadBalancingSettingsModel{} } - v := input[0].(map[string]interface{}) - id := v["id"].(string) - sampleSize := v["sample_size"].(int32) - successfulSamplesRequired := v["successful_samples_required"].(int32) - additionalLatencyMilliseconds := v["additional_latency_milliseconds"].(int32) - resourceState := v["resource_state"].(string) - name := v["name"].(string) - - result := frontdoor.LoadBalancingSettingsModel{ - ID: utils.String(id), - Name: utils.String(name), - LoadBalancingSettingsProperties: &frontdoor.LoadBalancingSettingsProperties{ - AdditionalLatencyMilliseconds: utils.Int32(additionalLatencyMilliseconds), - ResourceState: frontdoor.ResourceState(resourceState), - SampleSize: utils.Int32(sampleSize), - SuccessfulSamplesRequired: utils.Int32(successfulSamplesRequired), - }, + output := make([]frontdoor.LoadBalancingSettingsModel,0) + + for _, lbs := range input { + loadBalanceSetting := lbs.(map[string]interface{}) + + name := loadBalanceSetting["name"].(string) + sampleSize := loadBalanceSetting["sample_size"].(int32) + successfulSamplesRequired := loadBalanceSetting["successful_samples_required"].(int32) + additionalLatencyMilliseconds := loadBalanceSetting["additional_latency_milliseconds"].(int32) + id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "loadBalancingSettings", name)) + + result := frontdoor.LoadBalancingSettingsModel{ + ID: id, + Name: utils.String(name), + LoadBalancingSettingsProperties: &frontdoor.LoadBalancingSettingsProperties{ + SampleSize: utils.Int32(sampleSize), + SuccessfulSamplesRequired: utils.Int32(successfulSamplesRequired), + AdditionalLatencyMilliseconds: utils.Int32(additionalLatencyMilliseconds), + }, + } + + output = append(output, result) } - return &[]frontdoor.LoadBalancingSettingsModel{result} + + return &output } func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, resourceGroup, serviceName string) *[]frontdoor.RoutingRule { @@ -668,7 +787,7 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r id := routingRule["id"].(string) frontendEndpoints := routingRule["frontend_endpoints"].([]interface{}) - acceptedProtocols := routingRule["accepted_protocols"].(*[]frontdoor.Protocol) + acceptedProtocols := routingRule["accepted_protocols"].([]interface{}) patternsToMatch := routingRule["patterns_to_match"].(*[]string) enabled := routingRule["enabled"].(bool) name := routingRule["name"].(string) @@ -689,7 +808,7 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r RoutingRuleProperties: &frontdoor.RoutingRuleProperties{ //ResourceState: FrontendEndpoints: expandArmFrontDoorFrontEndEndpoints(frontendEndpoints, subscriptionId, resourceGroup, serviceName), - AcceptedProtocols: acceptedProtocols, + AcceptedProtocols: expandArmFrontDoorAcceptedProtocols(acceptedProtocols), PatternsToMatch: patternsToMatch, EnabledState: frontdoor.RoutingRuleEnabledState(expandArmFrontDoorEnabledState(enabled)), RouteConfiguration: routingConfiguration, @@ -702,43 +821,31 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r return &output } -func expandArmFrontDoorBackend(input []interface{}) *[]frontdoor.Backend { +func expandArmFrontDoorAcceptedProtocols(input []interface{}) *[]frontdoor.Protocol { if len(input) == 0 { - return nil + return &[]frontdoor.Protocol{} } - v := input[0].(map[string]interface{}) - address := v["address"].(string) - httpPort := v["http_port"].(int32) - httpsPort := v["https_port"].(int32) - enabledState := v["enabled_state"].(string) - priority := v["priority"].(int32) - weight := v["weight"].(int32) - backendHostHeader := v["backend_host_header"].(string) - - result := frontdoor.Backend{ - Address: utils.String(address), - BackendHostHeader: utils.String(backendHostHeader), - EnabledState: frontdoor.BackendEnabledState(enabledState), - HTTPPort: utils.Int32(httpPort), - HTTPSPort: utils.Int32(httpsPort), - Priority: utils.Int32(priority), - Weight: utils.Int32(weight), - } - return &[]frontdoor.Backend{result} -} + output := make([]frontdoor.Protocol,0) -func expandArmFrontDoorSubResource(input []interface{}) *frontdoor.SubResource { - if len(input) == 0 { - return nil + for _,ap := range input { + result := frontdoor.HTTPS + + if ap.(frontdoor.Protocol) == frontdoor.HTTP { + result = frontdoor.HTTP + } + + output = append(output, result) } - v := input[0].(map[string]interface{}) - id := v["id"].(string) + return &output +} +func expandArmFrontDoorSubResource(subscriptionId string, resourceGroup string, serviceName string, resourceType string, resourceName string) *frontdoor.SubResource { result := frontdoor.SubResource{ - ID: utils.String(id), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, resourceType, resourceName)), } + return &result } @@ -747,59 +854,27 @@ func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId str return &[]frontdoor.SubResource{} } - output := make([]frontdoor.SubResource, 0) - v := input[0].(map[string]interface{}) + output := make([]frontdoor.SubResource, 0) for _, SubResource := range v { - frontendEndpointName := SubResource.(string) - id := azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", frontendEndpointName) - - result := frontdoor.SubResource{ - ID: utils.String(id), - } - + result := *expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", SubResource.(string)) output = append(output, result) } - - return &output -} -func expandArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input []interface{}) *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink { - if len(input) == 0 { - return nil - } - v := input[0].(map[string]interface{}) - - id := v["id"].(string) - - result := frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink{ - ID: utils.String(id), - } - return &result + return &output } -func expandArmFrontDoorEnabledState(input interface{}) frontdoor.EnabledState { - v := input.(bool) +func expandArmFrontDoorEnabledState(enabled bool) frontdoor.EnabledState { result := frontdoor.EnabledStateDisabled - if v { + if enabled { result = frontdoor.EnabledStateEnabled } return result } -func expandArmFrontDoorDynamicDynamicCompression(input bool) frontdoor.DynamicCompressionEnabled { - result := frontdoor.DynamicCompressionEnabledDisabled - - if input { - result = frontdoor.DynamicCompressionEnabledEnabled - } - - return result -} - func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.RedirectConfiguration { if len(input) == 0 { return frontdoor.RedirectConfiguration{} @@ -838,9 +913,15 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription cacheQueryParameterStripDirective := v["cache_query_parameter_strip_directive"].(frontdoor.Query) backendPoolName := v["backend_pool_name"].(string) + useDynamicCompression := frontdoor.DynamicCompressionEnabledDisabled + + if cacheUseDynamicCompression { + useDynamicCompression = frontdoor.DynamicCompressionEnabledEnabled + } + cacheConfiguration := &frontdoor.CacheConfiguration { QueryParameterStripDirective: cacheQueryParameterStripDirective, - DynamicCompression: expandArmFrontDoorDynamicDynamicCompression(cacheUseDynamicCompression), + DynamicCompression: useDynamicCompression, } backend := &frontdoor.SubResource{ From 00a51cde8a43093b8e88da0cd7496f4b17107069 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 23 Jul 2019 16:27:13 -0700 Subject: [PATCH 11/74] WIP: Functional CreateUpdate done --- azurerm/helpers/azure/frontdoor.go | 44 ++++++ azurerm/resource_arm_front_door.go | 231 ++++++++++++++++------------- 2 files changed, 169 insertions(+), 106 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index a858b5ea6ea7..f70db9e66fab 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -175,4 +175,48 @@ func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, ser } return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontDoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) +} + +func GetArmFrontDoorRedirectType(input string) frontdoor.RedirectType { + switch input { + case "Moved": + return frontdoor.Moved + case "PermanentRedirect": + return frontdoor.PermanentRedirect + case "TemporaryRedirect": + return frontdoor.TemporaryRedirect + default: + return frontdoor.Found + } +} + +func GetArmFrontDoorRedirectProtocol(input string) frontdoor.RedirectProtocol { + switch input { + case "RedirectProtocolHTTPOnly": + return frontdoor.RedirectProtocolHTTPOnly + case "RedirectProtocolHTTPSOnly": + return frontdoor.RedirectProtocolHTTPSOnly + default: + return frontdoor.RedirectProtocolMatchRequest + } +} + +func GetArmFrontDoorForwardingProtocol(input string) frontdoor.ForwardingProtocol { + switch input { + case "HTTPOnly": + return frontdoor.HTTPOnly + case "HTTPSOnly": + return frontdoor.HTTPSOnly + default: + return frontdoor.MatchRequest + } +} + +func GetArmFrontDoorQuery(input string) frontdoor.Query { + switch input { + case "StripAll": + return frontdoor.StripAll + default: + return frontdoor.StripNone + } } \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 2271b1247925..e89eb3f54b6f 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -26,16 +26,16 @@ func resourceArmFrontDoor() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, ValidateFunc: azure.ValidateFrontDoorName, }, "enabled": { Type: schema.TypeBool, Optional: true, - Default: true, + Default: true, }, "location": azure.SchemaLocation(), @@ -43,7 +43,7 @@ func resourceArmFrontDoor() *schema.Resource { "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), "routing_rule": { - Type: schema.TypeList, + Type: schema.TypeList, MaxItems: 100, Optional: true, Elem: &schema.Resource{ @@ -53,14 +53,14 @@ func resourceArmFrontDoor() *schema.Resource { Computed: true, }, "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "enabled": { Type: schema.TypeBool, Optional: true, - Default: true, + Default: true, }, "accepted_protocols": { Type: schema.TypeList, @@ -69,7 +69,7 @@ func resourceArmFrontDoor() *schema.Resource { Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.HTTP), + string(frontdoor.HTTP), string(frontdoor.HTTPS), }, false), Default: string(frontdoor.HTTP), @@ -80,7 +80,7 @@ func resourceArmFrontDoor() *schema.Resource { Optional: true, MaxItems: 25, Elem: &schema.Schema{ - Type: schema.TypeString, + Type: schema.TypeString, Default: "/*", }, }, @@ -89,7 +89,7 @@ func resourceArmFrontDoor() *schema.Resource { Required: true, MaxItems: 100, Elem: &schema.Schema{ - Type: schema.TypeString, + Type: schema.TypeString, }, }, "redirect_configuration": { @@ -116,7 +116,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "redirect_protocol": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.RedirectProtocolHTTPOnly), string(frontdoor.RedirectProtocolHTTPSOnly), @@ -125,7 +125,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "redirect_type": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Found), string(frontdoor.Moved), @@ -147,9 +147,9 @@ func resourceArmFrontDoor() *schema.Resource { Required: true, }, "cache_use_dynamic_compression": { - Type: schema.TypeString, + Type: schema.TypeBool, Optional: true, - Default: false, + Default: false, }, "cache_query_parameter_strip_directive": { Type: schema.TypeString, @@ -162,7 +162,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "custom_forwarding_path": { Type: schema.TypeString, - Required: true, + Optional: true, }, "forwarding_protocol": { Type: schema.TypeString, @@ -191,24 +191,24 @@ func resourceArmFrontDoor() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "sample_size": { Type: schema.TypeInt, Optional: true, - Default: 4, + Default: 4, }, "successful_samples_required": { Type: schema.TypeInt, Optional: true, - Default: 2, + Default: 2, }, "additional_latency_milliseconds": { Type: schema.TypeInt, Optional: true, - Default: 2, + Default: 2, }, }, }, @@ -220,14 +220,14 @@ func resourceArmFrontDoor() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "path": { Type: schema.TypeString, Optional: true, - Default: "/", + Default: "/", }, "protocol": { Type: schema.TypeString, @@ -241,7 +241,7 @@ func resourceArmFrontDoor() *schema.Resource { "interval_in_seconds": { Type: schema.TypeInt, Optional: true, - Default: 120, + Default: 120, }, }, }, @@ -261,31 +261,31 @@ func resourceArmFrontDoor() *schema.Resource { "enabled": { Type: schema.TypeBool, Optional: true, - Default: true, + Default: true, }, "address": { Type: schema.TypeString, Required: true, }, "http_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntBetween(1, 65535), }, "https_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntBetween(1, 65535), }, "weight": { - Type: schema.TypeInt, - Optional: true, + Type: schema.TypeInt, + Optional: true, ValidateFunc: validation.IntBetween(1, 1000), - Default: 50, + Default: 50, }, "priority": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntBetween(1, 5), }, "host_header": { @@ -296,8 +296,8 @@ func resourceArmFrontDoor() *schema.Resource { }, }, "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "health_probe_name": { @@ -318,8 +318,8 @@ func resourceArmFrontDoor() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "host_name": { @@ -329,7 +329,7 @@ func resourceArmFrontDoor() *schema.Resource { "session_affinity_enabled": { Type: schema.TypeBool, Optional: true, - Default: true, + Default: true, }, "session_affinity_ttl_seconds": { Type: schema.TypeInt, @@ -431,7 +431,6 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings, subscriptionId, resourceGroup, name), LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings, subscriptionId, resourceGroup, name), EnabledState: expandArmFrontDoorEnabledState(enabledState), - }, Tags: expandTags(tags), } @@ -571,7 +570,7 @@ func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, output = append(output, result) } - + return &output } @@ -586,12 +585,12 @@ func expandArmFrontDoorBackend(input []interface{}) *[]frontdoor.Backend { backend := be.(map[string]interface{}) address := backend["address"].(string) - httpPort := backend["http_port"].(int32) - httpsPort := backend["https_port"].(int32) - enabled := backend["enabled"].(bool) - priority := backend["priority"].(int32) - weight := backend["weight"].(int32) hostHeader := backend["host_header"].(string) + enabled := backend["enabled"].(bool) + httpPort := int32(backend["http_port"].(int)) + httpsPort := int32(backend["https_port"].(int)) + priority := int32(backend["priority"].(int)) + weight := int32(backend["weight"].(int)) result := frontdoor.Backend{ Address: utils.String(address), @@ -618,7 +617,6 @@ func expandArmFrontDoorBackendEnabledState(isEnabled bool) frontdoor.BackendEnab } func expandArmFrontDoorBackendPoolsSettings(enforceCertificateNameCheck bool) *frontdoor.BackendPoolsSettings { - enforceCheck := frontdoor.EnforceCertificateNameCheckEnabledStateDisabled if enforceCertificateNameCheck { @@ -644,7 +642,7 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri hostName := frontendEndpoint["host_name"].(string) isSessionAffinityEnabled := frontendEndpoint["session_affinity_enabled"].(bool) - sessionAffinityTtlSeconds := frontendEndpoint["session_affinity_ttl_seconds"].(int32) + sessionAffinityTtlSeconds := int32(frontendEndpoint["session_affinity_ttl_seconds"].(int)) customHttpsConfiguration := frontendEndpoint["custom_https_configuration"].([]interface{}) name := frontendEndpoint["name"].(string) id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", name)) @@ -662,12 +660,12 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri // ResourceState: // CustomHTTPSProvisioningState: // CustomHTTPSProvisioningSubstate: - CustomHTTPSConfiguration: expandArmFrontDoorCustomHTTPSConfiguration(customHttpsConfiguration), - HostName: utils.String(hostName), - SessionAffinityEnabledState: sessionAffinityEnabled, - SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), + CustomHTTPSConfiguration: expandArmFrontDoorCustomHTTPSConfiguration(customHttpsConfiguration), + HostName: utils.String(hostName), + SessionAffinityEnabledState: sessionAffinityEnabled, + SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), // WebApplicationFirewallPolicyLink: - + }, } @@ -684,8 +682,8 @@ func expandArmFrontDoorCustomHTTPSConfiguration(input []interface{}) *frontdoor. v := input[0].(map[string]interface{}) certSource := v["certificate_source"].(string) - - result := frontdoor.CustomHTTPSConfiguration { + + result := frontdoor.CustomHTTPSConfiguration{ ProtocolType: frontdoor.ServerNameIndication, } @@ -696,11 +694,11 @@ func expandArmFrontDoorCustomHTTPSConfiguration(input []interface{}) *frontdoor. result.CertificateSource = frontdoor.CertificateSourceAzureKeyVault result.KeyVaultCertificateSourceParameters = &frontdoor.KeyVaultCertificateSourceParameters{ - Vault: &frontdoor.KeyVaultCertificateSourceParametersVault { + Vault: &frontdoor.KeyVaultCertificateSourceParametersVault{ ID: utils.String(vaultId), }, - SecretName: utils.String(vaultSecret), - SecretVersion:utils.String(vaultVersion), + SecretName: utils.String(vaultSecret), + SecretVersion: utils.String(vaultVersion), } } else { result.CertificateSource = frontdoor.CertificateSourceFrontDoor @@ -719,14 +717,14 @@ func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptio output := make([]frontdoor.HealthProbeSettingsModel, 0) - for _,hps := range input { + for _, hps := range input { v := hps.(map[string]interface{}) path := v["path"].(string) protocol := v["protocol"].(string) - intervalInSeconds := v["interval_in_seconds"].(int32) + intervalInSeconds := int32(v["interval_in_seconds"].(int)) name := v["name"].(string) - + result := frontdoor.HealthProbeSettingsModel{ ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "healthProbeSettings", name)), Name: utils.String(name), @@ -748,15 +746,15 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscript return &[]frontdoor.LoadBalancingSettingsModel{} } - output := make([]frontdoor.LoadBalancingSettingsModel,0) + output := make([]frontdoor.LoadBalancingSettingsModel, 0) for _, lbs := range input { loadBalanceSetting := lbs.(map[string]interface{}) name := loadBalanceSetting["name"].(string) - sampleSize := loadBalanceSetting["sample_size"].(int32) - successfulSamplesRequired := loadBalanceSetting["successful_samples_required"].(int32) - additionalLatencyMilliseconds := loadBalanceSetting["additional_latency_milliseconds"].(int32) + sampleSize := int32(loadBalanceSetting["sample_size"].(int)) + successfulSamplesRequired := int32(loadBalanceSetting["successful_samples_required"].(int)) + additionalLatencyMilliseconds := int32(loadBalanceSetting["additional_latency_milliseconds"].(int)) id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "loadBalancingSettings", name)) result := frontdoor.LoadBalancingSettingsModel{ @@ -771,7 +769,7 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscript output = append(output, result) } - + return &output } @@ -788,18 +786,22 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r id := routingRule["id"].(string) frontendEndpoints := routingRule["frontend_endpoints"].([]interface{}) acceptedProtocols := routingRule["accepted_protocols"].([]interface{}) - patternsToMatch := routingRule["patterns_to_match"].(*[]string) + ptm := routingRule["patterns_to_match"].([]interface{}) enabled := routingRule["enabled"].(bool) name := routingRule["name"].(string) + patternsToMatch := make([]string, 0) + + for _, p := range ptm { + patternsToMatch = append(patternsToMatch, p.(string)) + } + var routingConfiguration frontdoor.BasicRouteConfiguration - if rc := routingRule["redirect_configuration"].([]interface{}); rc != nil { - redirectConfiguration := expandArmFrontDoorRedirectConfiguration(rc) - routingConfiguration = redirectConfiguration - } else if fc := routingRule["forwarding_configuration"].([]interface{}); fc != nil { - forwardingConfiguration := expandArmFrontDoorForwardingConfiguration(fc, subscriptionId, resourceGroup, serviceName) - routingConfiguration = forwardingConfiguration + if rc := routingRule["redirect_configuration"].([]interface{}); len(rc) != 0 { + routingConfiguration = expandArmFrontDoorRedirectConfiguration(rc) + } else if fc := routingRule["forwarding_configuration"].([]interface{}); len(fc) != 0 { + routingConfiguration = expandArmFrontDoorForwardingConfiguration(fc, subscriptionId, resourceGroup, serviceName) } currentRoutingRule := frontdoor.RoutingRule{ @@ -809,7 +811,7 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r //ResourceState: FrontendEndpoints: expandArmFrontDoorFrontEndEndpoints(frontendEndpoints, subscriptionId, resourceGroup, serviceName), AcceptedProtocols: expandArmFrontDoorAcceptedProtocols(acceptedProtocols), - PatternsToMatch: patternsToMatch, + PatternsToMatch: &patternsToMatch, EnabledState: frontdoor.RoutingRuleEnabledState(expandArmFrontDoorEnabledState(enabled)), RouteConfiguration: routingConfiguration, }, @@ -826,12 +828,12 @@ func expandArmFrontDoorAcceptedProtocols(input []interface{}) *[]frontdoor.Proto return &[]frontdoor.Protocol{} } - output := make([]frontdoor.Protocol,0) + output := make([]frontdoor.Protocol, 0) - for _,ap := range input { + for _, ap := range input { result := frontdoor.HTTPS - if ap.(frontdoor.Protocol) == frontdoor.HTTP { + if ap.(string) == fmt.Sprintf("%s", frontdoor.HTTP) { result = frontdoor.HTTP } @@ -854,10 +856,10 @@ func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId str return &[]frontdoor.SubResource{} } - v := input[0].(map[string]interface{}) + //v := input.(map[string]interface{}) output := make([]frontdoor.SubResource, 0) - for _, SubResource := range v { + for _, SubResource := range input { result := *expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", SubResource.(string)) output = append(output, result) } @@ -867,7 +869,7 @@ func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId str func expandArmFrontDoorEnabledState(enabled bool) frontdoor.EnabledState { result := frontdoor.EnabledStateDisabled - + if enabled { result = frontdoor.EnabledStateEnabled } @@ -880,17 +882,17 @@ func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.Redi return frontdoor.RedirectConfiguration{} } v := input[0].(map[string]interface{}) - - redirectType := v["redirect_type"].(frontdoor.RedirectType) - redirectProtocol := v["redirect_protocol"].(frontdoor.RedirectProtocol) + + redirectType := v["redirect_type"].(string) + redirectProtocol := v["redirect_protocol"].(string) customHost := v["custom_host"].(string) customPath := v["custom_path"].(string) customFragment := v["custom_fragment"].(string) customQueryString := v["custom_query_string"].(string) - redirectConfiguration := frontdoor.RedirectConfiguration { - RedirectType: redirectType, - RedirectProtocol: redirectProtocol, + redirectConfiguration := frontdoor.RedirectConfiguration{ + RedirectType: azure.GetArmFrontDoorRedirectType(redirectType), + RedirectProtocol: azure.GetArmFrontDoorRedirectProtocol(redirectProtocol), CustomHost: utils.String(customHost), CustomPath: utils.String(customPath), CustomFragment: utils.String(customFragment), @@ -906,11 +908,11 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription return frontdoor.ForwardingConfiguration{} } v := input[0].(map[string]interface{}) - + customForwardingPath := v["custom_forwarding_path"].(string) - forwardingProtocol := v["forwarding_protocol"].(frontdoor.ForwardingProtocol) + forwardingProtocol := v["forwarding_protocol"].(string) cacheUseDynamicCompression := v["cache_use_dynamic_compression"].(bool) - cacheQueryParameterStripDirective := v["cache_query_parameter_strip_directive"].(frontdoor.Query) + cacheQueryParameterStripDirective := v["cache_query_parameter_strip_directive"].(string) backendPoolName := v["backend_pool_name"].(string) useDynamicCompression := frontdoor.DynamicCompressionEnabledDisabled @@ -919,21 +921,24 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription useDynamicCompression = frontdoor.DynamicCompressionEnabledEnabled } - cacheConfiguration := &frontdoor.CacheConfiguration { - QueryParameterStripDirective: cacheQueryParameterStripDirective, - DynamicCompression: useDynamicCompression, + cacheConfiguration := &frontdoor.CacheConfiguration{ + QueryParameterStripDirective: azure.GetArmFrontDoorQuery(cacheQueryParameterStripDirective), + DynamicCompression: useDynamicCompression, } backend := &frontdoor.SubResource{ ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "backendPools", backendPoolName)), } - forwardingConfiguration := frontdoor.ForwardingConfiguration { - CustomForwardingPath: utils.String(customForwardingPath), - ForwardingProtocol: forwardingProtocol, - CacheConfiguration: cacheConfiguration, - BackendPool: backend, - OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration, + forwardingConfiguration := frontdoor.ForwardingConfiguration{ + ForwardingProtocol: azure.GetArmFrontDoorForwardingProtocol(forwardingProtocol), + CacheConfiguration: cacheConfiguration, + BackendPool: backend, + OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration, + } + + if customForwardingPath != "" { + forwardingConfiguration.CustomForwardingPath = utils.String(customForwardingPath) } return forwardingConfiguration @@ -958,6 +963,20 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription + + + + + + + + + + + + + + @@ -1098,12 +1117,12 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ result["accepted_protocols"] = string(ap) } } - result["enabled_state"] = string(properties.EnabledState) - result["frontend_endpoints"] = flattenArmFrontDoorSubResources(properties.FrontendEndpoints) - if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { - result["patterns_to_match"] = *patternsToMatch - } - result["resource_state"] = string(properties.ResourceState) + result["enabled_state"] = string(properties.EnabledState) + result["frontend_endpoints"] = flattenArmFrontDoorSubResources(properties.FrontendEndpoints) + if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { + result["patterns_to_match"] = *patternsToMatch + } + result["resource_state"] = string(properties.ResourceState) } } @@ -1161,7 +1180,7 @@ func flattenArmFrontDoorSubResources(input *[]frontdoor.SubResource) []interface result := make(map[string]interface{}) - for _,v := range *input { + for _, v := range *input { if id := v.ID; id != nil { result["id"] = *id } From 68b84d08e49a8a45a08809153706914da6a56ef6 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 23 Jul 2019 18:46:31 -0700 Subject: [PATCH 12/74] Cast values and start on flatten functions --- azurerm/helpers/azure/frontdoor.go | 44 --------------- azurerm/resource_arm_front_door.go | 91 ++++++++++++++++++++---------- 2 files changed, 61 insertions(+), 74 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index f70db9e66fab..9c49bee950ca 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -176,47 +176,3 @@ func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, ser return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontDoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) } - -func GetArmFrontDoorRedirectType(input string) frontdoor.RedirectType { - switch input { - case "Moved": - return frontdoor.Moved - case "PermanentRedirect": - return frontdoor.PermanentRedirect - case "TemporaryRedirect": - return frontdoor.TemporaryRedirect - default: - return frontdoor.Found - } -} - -func GetArmFrontDoorRedirectProtocol(input string) frontdoor.RedirectProtocol { - switch input { - case "RedirectProtocolHTTPOnly": - return frontdoor.RedirectProtocolHTTPOnly - case "RedirectProtocolHTTPSOnly": - return frontdoor.RedirectProtocolHTTPSOnly - default: - return frontdoor.RedirectProtocolMatchRequest - } -} - -func GetArmFrontDoorForwardingProtocol(input string) frontdoor.ForwardingProtocol { - switch input { - case "HTTPOnly": - return frontdoor.HTTPOnly - case "HTTPSOnly": - return frontdoor.HTTPSOnly - default: - return frontdoor.MatchRequest - } -} - -func GetArmFrontDoorQuery(input string) frontdoor.Query { - switch input { - case "StripAll": - return frontdoor.StripAll - default: - return frontdoor.StripNone - } -} \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index e89eb3f54b6f..1b7e7f43b41f 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -452,8 +452,7 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } d.SetId(*resp.ID) - //return resourceArmFrontDoorRead(d, meta) - return nil + return resourceArmFrontDoorRead(d, meta) } func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { @@ -483,14 +482,18 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { d.Set("location", azure.NormalizeLocation(*location)) } if properties := resp.Properties; properties != nil { - if err := d.Set("backend_pools", flattenArmFrontDoorBackendPool(properties.BackendPools)); err != nil { + if err := d.Set("backend_pools", flattenArmFrontDoorBackendPools(properties.BackendPools)); err != nil { return fmt.Errorf("Error setting `backend_pools`: %+v", err) } - if err := d.Set("backend_pools_settings", flattenArmFrontDoorBackendPoolsSettings(properties.BackendPoolsSettings)); err != nil { - return fmt.Errorf("Error setting `backend_pools_settings`: %+v", err) + if err := d.Set("enforce_backend_pools_certificate_name_check", flattenArmFrontDoorBackendPoolsSettings(properties.BackendPoolsSettings)); err != nil { + return fmt.Errorf("Error setting `enforce_backend_pools_certificate_name_check`: %+v", err) } d.Set("cname", properties.Cname) - d.Set("enabled_state", string(properties.EnabledState)) + if properties.EnabledState == frontdoor.EnabledStateEnabled { + d.Set("enabled", true) + } else { + d.Set("enabled", false) + } d.Set("friendly_name", properties.FriendlyName) if err := d.Set("frontend_endpoint", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) @@ -502,7 +505,6 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error setting `load_balancing_settings`: %+v", err) } d.Set("provisioning_state", properties.ProvisioningState) - d.Set("resource_state", string(properties.ResourceState)) if err := d.Set("routing_rules", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { return fmt.Errorf("Error setting `routing_rules`: %+v", err) } @@ -891,8 +893,8 @@ func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.Redi customQueryString := v["custom_query_string"].(string) redirectConfiguration := frontdoor.RedirectConfiguration{ - RedirectType: azure.GetArmFrontDoorRedirectType(redirectType), - RedirectProtocol: azure.GetArmFrontDoorRedirectProtocol(redirectProtocol), + RedirectType: frontdoor.RedirectType(redirectType), + RedirectProtocol: frontdoor.RedirectProtocol(redirectProtocol), CustomHost: utils.String(customHost), CustomPath: utils.String(customPath), CustomFragment: utils.String(customFragment), @@ -922,7 +924,7 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription } cacheConfiguration := &frontdoor.CacheConfiguration{ - QueryParameterStripDirective: azure.GetArmFrontDoorQuery(cacheQueryParameterStripDirective), + QueryParameterStripDirective: frontdoor.Query(cacheQueryParameterStripDirective), DynamicCompression: useDynamicCompression, } @@ -931,7 +933,7 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription } forwardingConfiguration := frontdoor.ForwardingConfiguration{ - ForwardingProtocol: azure.GetArmFrontDoorForwardingProtocol(forwardingProtocol), + ForwardingProtocol: frontdoor.ForwardingProtocol(forwardingProtocol), CacheConfiguration: cacheConfiguration, BackendPool: backend, OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorForwardingConfiguration, @@ -987,7 +989,7 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription -func flattenArmFrontDoorBackendPool(input *[]frontdoor.BackendPool) []interface{} { +func flattenArmFrontDoorBackendPools(input *[]frontdoor.BackendPool) []interface{} { if input == nil { return make([]interface{}, 0) } @@ -998,29 +1000,35 @@ func flattenArmFrontDoorBackendPool(input *[]frontdoor.BackendPool) []interface{ if id := v.ID; id != nil { result["id"] = *id } + + if name := v.Name; name != nil { + result["name"] = *name + } + if properties := v.BackendPoolProperties; properties != nil { - result["backends"] = flattenArmFrontDoorBackend(properties.Backends) - result["health_probe_settings"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings) - result["load_balancing_settings"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings) - result["resource_state"] = string(properties.ResourceState) + result["backend"] = flattenArmFrontDoorBackend(properties.Backends) + result["backend_pool_health_probe"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings) + result["backend_pool_load_balancing"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings) } } return []interface{}{result} } -func flattenArmFrontDoorBackendPoolsSettings(input *frontdoor.BackendPoolsSettings) []interface{} { +func flattenArmFrontDoorBackendPoolsSettings(input *frontdoor.BackendPoolsSettings) bool { if input == nil { return make([]interface{}, 0) } - result := make(map[string]interface{}) + result := false - if enforceCertificateNameCheck := string(input.EnforceCertificateNameCheck); enforceCertificateNameCheck != "" { - result["enforce_certificate_name_check"] = enforceCertificateNameCheck + if enforceCertificateNameCheck := frontdoor.EnforceCertificateNameCheckEnabledState(input.EnforceCertificateNameCheck); enforceCertificateNameCheck != "" { + if enforceCertificateNameCheck == frontdoor.EnforceCertificateNameCheckEnabledStateEnabled { + result = true + } } - return []interface{}{result} + return result } func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) []interface{} { @@ -1033,16 +1041,30 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] if id := v.ID; id != nil { result["id"] = *id } + if name := v.Name; name != nil { + result["name"] = *id + } if properties := v.FrontendEndpointProperties; properties != nil { if hostName := properties.HostName; hostName != nil { result["host_name"] = *hostName } - result["resource_state"] = string(properties.ResourceState) - result["session_affinity_enabled_state"] = string(properties.SessionAffinityEnabledState) + if sessionAffinityEnabled := properties.SessionAffinityEnabledState; sessionAffinityEnabled != nil { + if sessionAffinityEnabled == SessionAffinityEnabledStateEnabled { + result["session_affinity_enabled"] = true + } else { + result["session_affinity_enabled"] = false + } + } + if sessionAffinityTtlSeconds := properties.SessionAffinityTTLSeconds; sessionAffinityTtlSeconds != nil { result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds } - result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) + + if properties.CustomHTTPSConfiguration != nil { + + } + + //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) } } return []interface{}{result} @@ -1140,20 +1162,29 @@ func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { result["address"] = *address } if backendHostHeader := v.BackendHostHeader; backendHostHeader != nil { - result["backend_host_header"] = *backendHostHeader + result["host_header"] = *backendHostHeader } - result["enabled_state"] = string(v.EnabledState) + + if v.EnabledState == frontdoor.Enabled { + result["enabled"] = true + } else { + result["enabled"] = false + } + if httpPort := v.HTTPPort; httpPort != nil { - result["http_port"] = *httpPort + result["http_port"] = int(*httpPort) } + if httpsPort := v.HTTPSPort; httpsPort != nil { - result["https_port"] = *httpsPort + result["https_port"] = int(*httpsPort) } + if priority := v.Priority; priority != nil { - result["priority"] = *priority + result["priority"] = int(*priority) } + if weight := v.Weight; weight != nil { - result["weight"] = *weight + result["weight"] = int(*weight) } } return []interface{}{result} From c40fcc929558f36c81e5c115da05c157cd627dcb Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 24 Jul 2019 19:00:51 -0700 Subject: [PATCH 13/74] WIP: Last fix routing rules --- azurerm/helpers/azure/frontdoor.go | 2 +- azurerm/resource_arm_front_door.go | 240 +++++++++++++++-------------- 2 files changed, 123 insertions(+), 119 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 9c49bee950ca..17ceecaf2605 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -174,5 +174,5 @@ func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, ser return "" } - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontDoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) + return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontdoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) } diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 1b7e7f43b41f..61d8a664dcd8 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -190,6 +190,10 @@ func resourceArmFrontDoor() *schema.Resource { Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, "name": { Type: schema.TypeString, Required: true, @@ -219,6 +223,10 @@ func resourceArmFrontDoor() *schema.Resource { Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, "name": { Type: schema.TypeString, Required: true, @@ -295,6 +303,10 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, + "id": { + Type: schema.TypeString, + Computed: true, + }, "name": { Type: schema.TypeString, Required: true, @@ -317,6 +329,10 @@ func resourceArmFrontDoor() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, "name": { Type: schema.TypeString, Optional: true, @@ -464,7 +480,7 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { return err } resourceGroup := id.ResourceGroup - name := id.Path["frontDoors"] + name := id.Path["frontdoors"] resp, err := client.Get(ctx, resourceGroup, name) if err != nil { @@ -482,8 +498,8 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { d.Set("location", azure.NormalizeLocation(*location)) } if properties := resp.Properties; properties != nil { - if err := d.Set("backend_pools", flattenArmFrontDoorBackendPools(properties.BackendPools)); err != nil { - return fmt.Errorf("Error setting `backend_pools`: %+v", err) + if err := d.Set("backend_pool", flattenArmFrontDoorBackendPools(properties.BackendPools)); err != nil { + return fmt.Errorf("Error setting `backend_pool`: %+v", err) } if err := d.Set("enforce_backend_pools_certificate_name_check", flattenArmFrontDoorBackendPoolsSettings(properties.BackendPoolsSettings)); err != nil { return fmt.Errorf("Error setting `enforce_backend_pools_certificate_name_check`: %+v", err) @@ -498,18 +514,17 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { if err := d.Set("frontend_endpoint", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) } - if err := d.Set("health_probe_settings", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { - return fmt.Errorf("Error setting `health_probe_settings`: %+v", err) + if err := d.Set("backend_pool_health_probe", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { + return fmt.Errorf("Error setting `backend_pool_health_probe`: %+v", err) } - if err := d.Set("load_balancing_settings", flattenArmFrontDoorLoadBalancingSettingsModel(properties.LoadBalancingSettings)); err != nil { - return fmt.Errorf("Error setting `load_balancing_settings`: %+v", err) + if err := d.Set("backend_pool_load_balancing", flattenArmFrontDoorLoadBalancingSettingsModel(properties.LoadBalancingSettings)); err != nil { + return fmt.Errorf("Error setting `backend_pool_load_balancing`: %+v", err) } - d.Set("provisioning_state", properties.ProvisioningState) - if err := d.Set("routing_rules", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { + if err := d.Set("routing_rule", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { return fmt.Errorf("Error setting `routing_rules`: %+v", err) } } - d.Set("type", resp.Type) + flattenAndSetTags(d, resp.Tags) return nil @@ -946,57 +961,16 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription return forwardingConfiguration } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -func flattenArmFrontDoorBackendPools(input *[]frontdoor.BackendPool) []interface{} { +func flattenArmFrontDoorBackendPools(input *[]frontdoor.BackendPool) []map[string]interface{} { if input == nil { - return make([]interface{}, 0) + return make([]map[string]interface{},0) } - result := make(map[string]interface{}) + output := make([]map[string]interface{},0) for _, v := range *input { + result := make(map[string]interface{}) + if id := v.ID; id != nil { result["id"] = *id } @@ -1007,17 +981,19 @@ func flattenArmFrontDoorBackendPools(input *[]frontdoor.BackendPool) []interface if properties := v.BackendPoolProperties; properties != nil { result["backend"] = flattenArmFrontDoorBackend(properties.Backends) - result["backend_pool_health_probe"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings) - result["backend_pool_load_balancing"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings) + result["health_probe_name"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings, "healthProbeSettings") + result["load_balancing_name"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings, "loadBalancingSettings") } + + output = append(output, result) } - return []interface{}{result} + return output } func flattenArmFrontDoorBackendPoolsSettings(input *frontdoor.BackendPoolsSettings) bool { if input == nil { - return make([]interface{}, 0) + return true } result := false @@ -1031,6 +1007,51 @@ func flattenArmFrontDoorBackendPoolsSettings(input *frontdoor.BackendPoolsSettin return result } +func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + output := make([]interface{},0) + + for _, v := range *input { + result := make(map[string]interface{}) + + if address := v.Address; address != nil { + result["address"] = *address + } + if backendHostHeader := v.BackendHostHeader; backendHostHeader != nil { + result["host_header"] = *backendHostHeader + } + + if v.EnabledState == frontdoor.Enabled { + result["enabled"] = true + } else { + result["enabled"] = false + } + + if httpPort := v.HTTPPort; httpPort != nil { + result["http_port"] = int(*httpPort) + } + + if httpsPort := v.HTTPSPort; httpsPort != nil { + result["https_port"] = int(*httpsPort) + } + + if priority := v.Priority; priority != nil { + result["priority"] = int(*priority) + } + + if weight := v.Weight; weight != nil { + result["weight"] = int(*weight) + } + + output = append(output, result) + } + + return output +} + func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) []interface{} { if input == nil { return make([]interface{}, 0) @@ -1042,14 +1063,14 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] result["id"] = *id } if name := v.Name; name != nil { - result["name"] = *id + result["name"] = *name } if properties := v.FrontendEndpointProperties; properties != nil { if hostName := properties.HostName; hostName != nil { result["host_name"] = *hostName } - if sessionAffinityEnabled := properties.SessionAffinityEnabledState; sessionAffinityEnabled != nil { - if sessionAffinityEnabled == SessionAffinityEnabledStateEnabled { + if sessionAffinityEnabled := properties.SessionAffinityEnabledState; sessionAffinityEnabled != "" { + if sessionAffinityEnabled == frontdoor.SessionAffinityEnabledStateEnabled { result["session_affinity_enabled"] = true } else { result["session_affinity_enabled"] = false @@ -1061,7 +1082,18 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] } if properties.CustomHTTPSConfiguration != nil { - + customHttpsConfiguration := make(map[string]interface{}, 0) + customHttpsConfiguration["certificate_source"] = string(properties.CustomHTTPSConfiguration.CertificateSource) + + if properties.CustomHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { + kvcsp := properties.CustomHTTPSConfiguration.KeyVaultCertificateSourceParameters + + customHttpsConfiguration["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID + customHttpsConfiguration["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName + customHttpsConfiguration["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion + } + + result["custom_https_configuration"] = customHttpsConfiguration } //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) @@ -1088,7 +1120,6 @@ func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeS result["path"] = *path } result["protocol"] = string(properties.Protocol) - result["resource_state"] = string(properties.ResourceState) } } @@ -1110,7 +1141,6 @@ func flattenArmFrontDoorLoadBalancingSettingsModel(input *[]frontdoor.LoadBalanc if additionalLatencyMilliseconds := properties.AdditionalLatencyMilliseconds; additionalLatencyMilliseconds != nil { result["additional_latency_milliseconds"] = *additionalLatencyMilliseconds } - result["resource_state"] = string(properties.ResourceState) if sampleSize := properties.SampleSize; sampleSize != nil { result["sample_size"] = *sampleSize } @@ -1133,90 +1163,64 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ if id := v.ID; id != nil { result["id"] = *id } + result["name"] = *v.Name if properties := v.RoutingRuleProperties; properties != nil { - if acceptedProtocols := properties.AcceptedProtocols; acceptedProtocols != nil { - for _, ap := range *acceptedProtocols { - result["accepted_protocols"] = string(ap) - } - } + result["accepted_protocols"] = flattenArmFrontDoorAcceptedProtocol(properties.AcceptedProtocols) result["enabled_state"] = string(properties.EnabledState) - result["frontend_endpoints"] = flattenArmFrontDoorSubResources(properties.FrontendEndpoints) + result["frontend_endpoints"] = flattenArmFrontDoorFrontendEndpointsSubResources(properties.FrontendEndpoints) if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { result["patterns_to_match"] = *patternsToMatch } - result["resource_state"] = string(properties.ResourceState) } } return []interface{}{result} } -func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { +func flattenArmFrontDoorAcceptedProtocol(input *[]frontdoor.Protocol) []interface{} { if input == nil { return make([]interface{}, 0) } - result := make(map[string]interface{}) - for _, v := range *input { - if address := v.Address; address != nil { - result["address"] = *address - } - if backendHostHeader := v.BackendHostHeader; backendHostHeader != nil { - result["host_header"] = *backendHostHeader - } - - if v.EnabledState == frontdoor.Enabled { - result["enabled"] = true - } else { - result["enabled"] = false - } - - if httpPort := v.HTTPPort; httpPort != nil { - result["http_port"] = int(*httpPort) - } - - if httpsPort := v.HTTPSPort; httpsPort != nil { - result["https_port"] = int(*httpsPort) - } - - if priority := v.Priority; priority != nil { - result["priority"] = int(*priority) - } - - if weight := v.Weight; weight != nil { - result["weight"] = int(*weight) - } + output := make([]interface{},0) + for _, p := range *input { + output = append(output, string(p)) } - return []interface{}{result} + + return []interface{}{output} } -func flattenArmFrontDoorSubResource(input *frontdoor.SubResource) []interface{} { +func flattenArmFrontDoorSubResource(input *frontdoor.SubResource, resourceType string) string { if input == nil { - return make([]interface{}, 0) + return "" } - result := make(map[string]interface{}) + name := "" if id := input.ID; id != nil { - result["id"] = *id + aid, err := parseAzureResourceID(*id) + if err != nil { + return "" + } + name = aid.Path[resourceType] } - return []interface{}{result} + return name } -func flattenArmFrontDoorSubResources(input *[]frontdoor.SubResource) []interface{} { +func flattenArmFrontDoorFrontendEndpointsSubResources(input *[]frontdoor.SubResource) []interface{} { if input == nil { return make([]interface{}, 0) } - - result := make(map[string]interface{}) - + + output := make([]interface{},0) + for _, v := range *input { - if id := v.ID; id != nil { - result["id"] = *id - } + name := flattenArmFrontDoorSubResource(&v, "frontendEndpoints") + output = append(output, name) } - return []interface{}{result} + + return []interface{}{output} } func flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink) []interface{} { From 35c45020a93366028f5a90a5b874354fec9cb9e0 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 25 Jul 2019 18:32:40 -0700 Subject: [PATCH 14/74] WIP: Fully working Frontdoor --- azurerm/helpers/azure/frontdoor.go | 13 ++++ azurerm/resource_arm_front_door.go | 111 ++++++++++++++++++++--------- 2 files changed, 91 insertions(+), 33 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 17ceecaf2605..bc06be002390 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -176,3 +176,16 @@ func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, ser return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontdoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) } + +func GetFrontDoorBasicRouteConfigurationType (i interface{}) string { + _, ok := i.(frontdoor.ForwardingConfiguration ) + if !ok { + _, ok := i.(frontdoor.RedirectConfiguration ) + if !ok { + return "" + } + return "RedirectConfiguration" + } else { + return "ForwardingConfiguration" + } +} \ No newline at end of file diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 61d8a664dcd8..ce7825271b2a 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -1058,6 +1058,9 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] } result := make(map[string]interface{}) + customHttpsConfiguration := make([]interface{}, 0) + chc := make(map[string]interface{}, 0) + for _, v := range *input { if id := v.ID; id != nil { result["id"] = *id @@ -1065,6 +1068,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] if name := v.Name; name != nil { result["name"] = *name } + if properties := v.FrontendEndpointProperties; properties != nil { if hostName := properties.HostName; hostName != nil { result["host_name"] = *hostName @@ -1082,19 +1086,22 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] } if properties.CustomHTTPSConfiguration != nil { - customHttpsConfiguration := make(map[string]interface{}, 0) - customHttpsConfiguration["certificate_source"] = string(properties.CustomHTTPSConfiguration.CertificateSource) + chc["certificate_source"] = string(properties.CustomHTTPSConfiguration.CertificateSource) if properties.CustomHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { kvcsp := properties.CustomHTTPSConfiguration.KeyVaultCertificateSourceParameters - - customHttpsConfiguration["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID - customHttpsConfiguration["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName - customHttpsConfiguration["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion + chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID + chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName + chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion } - - result["custom_https_configuration"] = customHttpsConfiguration + } else { + // since FrontDoor is the default the API does not set this value (e.g. null) in Azure, + // Set default value for state file + chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) } + + customHttpsConfiguration = append(customHttpsConfiguration, chc) + result["custom_https_configuration"] = customHttpsConfiguration //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) } @@ -1106,12 +1113,15 @@ func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeS if input == nil { return make([]interface{}, 0) } - result := make(map[string]interface{}) + for _, v := range *input { if id := v.ID; id != nil { result["id"] = *id } + if name :=v.Name; name != nil { + result["name"] = *name + } if properties := v.HealthProbeSettingsProperties; properties != nil { if intervalInSeconds := properties.IntervalInSeconds; intervalInSeconds != nil { result["interval_in_seconds"] = *intervalInSeconds @@ -1137,6 +1147,9 @@ func flattenArmFrontDoorLoadBalancingSettingsModel(input *[]frontdoor.LoadBalanc if id := v.ID; id != nil { result["id"] = *id } + if name := v.Name; name != nil { + result["name"] = *name + } if properties := v.LoadBalancingSettingsProperties; properties != nil { if additionalLatencyMilliseconds := properties.AdditionalLatencyMilliseconds; additionalLatencyMilliseconds != nil { result["additional_latency_milliseconds"] = *additionalLatencyMilliseconds @@ -1157,6 +1170,7 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ return make([]interface{}, 0) } + output := make([]interface{}, 0) result := make(map[string]interface{}) for _, v := range *input { @@ -1164,30 +1178,75 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ result["id"] = *id } result["name"] = *v.Name + if properties := v.RoutingRuleProperties; properties != nil { result["accepted_protocols"] = flattenArmFrontDoorAcceptedProtocol(properties.AcceptedProtocols) - result["enabled_state"] = string(properties.EnabledState) + + if properties.EnabledState == frontdoor.RoutingRuleEnabledStateEnabled { + result["enabled"] = true + } else { + result["enabled"] = false + } result["frontend_endpoints"] = flattenArmFrontDoorFrontendEndpointsSubResources(properties.FrontendEndpoints) if patternsToMatch := properties.PatternsToMatch; patternsToMatch != nil { result["patterns_to_match"] = *patternsToMatch } + + brc := properties.RouteConfiguration + if routeConfigType := azure.GetFrontDoorBasicRouteConfigurationType(brc.(interface{})); routeConfigType != "" { + rc := make([]interface{}, 0) + c := make(map[string]interface{}) + + // there are only two types of Route Configuration Types + if routeConfigType == "ForwardingConfiguration" { + v := brc.(frontdoor.ForwardingConfiguration) + + c["backend_pool_name"] = flattenArmFrontDoorSubResource(v.BackendPool, "backendPools") + c["custom_forwarding_path"] = v.CustomForwardingPath + c["forwarding_protocol"] = string(v.ForwardingProtocol) + + cc := v.CacheConfiguration + c["cache_query_parameter_strip_directive"] = string(cc.QueryParameterStripDirective) + if cc.DynamicCompression == frontdoor.DynamicCompressionEnabledEnabled { + c["cache_use_dynamic_compression"] = true + } else { + c["cache_use_dynamic_compression"] = false + } + + rc = append(rc, c) + result["forwarding_configuration"] = rc + } else { + v := brc.(frontdoor.RedirectConfiguration) + c["custom_fragment"] = v.CustomFragment + c["custom_host"] = v.CustomHost + c["custom_path"] = v.CustomPath + c["custom_query_string"] = v.CustomQueryString + c["redirect_protocol"] = string(v.RedirectProtocol) + c["redirect_type"] = string(v.RedirectType) + + rc = append(rc, c) + result["redirect_configuration"] = rc + } + } } } - return []interface{}{result} + output = append(output, result) + + return output } -func flattenArmFrontDoorAcceptedProtocol(input *[]frontdoor.Protocol) []interface{} { +func flattenArmFrontDoorAcceptedProtocol(input *[]frontdoor.Protocol) []string { if input == nil { - return make([]interface{}, 0) + return make([]string, 0) } - output := make([]interface{},0) + output := make([]string,0) for _, p := range *input { output = append(output, string(p)) } - return []interface{}{output} + return output } func flattenArmFrontDoorSubResource(input *frontdoor.SubResource, resourceType string) string { @@ -1208,31 +1267,17 @@ func flattenArmFrontDoorSubResource(input *frontdoor.SubResource, resourceType s return name } -func flattenArmFrontDoorFrontendEndpointsSubResources(input *[]frontdoor.SubResource) []interface{} { +func flattenArmFrontDoorFrontendEndpointsSubResources(input *[]frontdoor.SubResource) []string { if input == nil { - return make([]interface{}, 0) + return make([]string, 0) } - output := make([]interface{},0) + output := make([]string,0) for _, v := range *input { name := flattenArmFrontDoorSubResource(&v, "frontendEndpoints") output = append(output, name) } - return []interface{}{output} -} - -func flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(input *frontdoor.FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink) []interface{} { - if input == nil { - return make([]interface{}, 0) - } - - result := make(map[string]interface{}) - - if id := input.ID; id != nil { - result["id"] = *id - } - - return []interface{}{result} + return output } From 74817222767543c49a1227f7fc9cbdd9f914b875 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 25 Jul 2019 18:41:43 -0700 Subject: [PATCH 15/74] WIP: Wasnt exactly done... fixed destroy --- azurerm/resource_arm_front_door.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index ce7825271b2a..2754dc4c39bc 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -539,7 +539,7 @@ func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error return err } resourceGroup := id.ResourceGroup - name := id.Path["frontDoors"] + name := id.Path["frontdoors"] future, err := client.Delete(ctx, resourceGroup, name) if err != nil { From 88e5f6a3ab7f5c858314eea1ab6786a7675d103d Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 25 Jul 2019 18:45:03 -0700 Subject: [PATCH 16/74] gofmt code --- azurerm/helpers/azure/frontdoor.go | 36 +++++++++++++++--------------- azurerm/resource_arm_front_door.go | 36 +++++++++++++++--------------- 2 files changed, 36 insertions(+), 36 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index bc06be002390..53aa0f47db3a 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -30,13 +30,13 @@ func ValidateFrontdoor(d *schema.ResourceData) error { routingRules := d.Get("routing_rule").([]interface{}) configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) backendPools := d.Get("backend_pool").([]interface{}) - loadBalancingSettings:= d.Get("backend_pool_load_balancing").([]interface{}) - healthProbeSettings:= d.Get("backend_pool_health_probe").([]interface{}) + loadBalancingSettings := d.Get("backend_pool_load_balancing").([]interface{}) + healthProbeSettings := d.Get("backend_pool_health_probe").([]interface{}) if len(configFrontendEndpoints) == 0 { return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) } - + if routingRules != nil { // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule for _, rr := range routingRules { @@ -60,12 +60,12 @@ func ValidateFrontdoor(d *schema.ResourceData) error { routingRulefrontendName := routingRuleFrontend.(string) found = false - // Loop over all of the defined frontend endpoints in the config + // Loop over all of the defined frontend endpoints in the config // seeing if we find the routing rule frontend in the list for _, configFrontendEndpoint := range configFrontendEndpoints { configFrontend := configFrontendEndpoint.(map[string]interface{}) configFrontendName := configFrontend["name"] - if( routingRulefrontendName == configFrontendName){ + if routingRulefrontendName == configFrontendName { found = true break } @@ -83,7 +83,7 @@ func ValidateFrontdoor(d *schema.ResourceData) error { // Verify backend pool load balancing settings and health probe settings are defined in the resource schema if backendPools != nil { - + for _, bp := range backendPools { backendPool := bp.(map[string]interface{}) backendPoolName := backendPool["name"] @@ -92,7 +92,7 @@ func ValidateFrontdoor(d *schema.ResourceData) error { found := false // Verify backend pool load balancing settings name exists - for _, lbs := range loadBalancingSettings{ + for _, lbs := range loadBalancingSettings { loadBalancing := lbs.(map[string]interface{}) loadBalancingName := loadBalancing["name"] @@ -109,7 +109,7 @@ func ValidateFrontdoor(d *schema.ResourceData) error { found = false // Verify health probe settings name exists - for _, hps := range healthProbeSettings{ + for _, hps := range healthProbeSettings { healthProbe := hps.(map[string]interface{}) healthProbeName := healthProbe["name"] @@ -122,7 +122,7 @@ func ValidateFrontdoor(d *schema.ResourceData) error { if !found { return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) } - + } } else { return fmt.Errorf(`"backend_pool": must have at least one "backend" defined`) @@ -132,7 +132,7 @@ func ValidateFrontdoor(d *schema.ResourceData) error { for _, configFrontendEndpoint := range configFrontendEndpoints { if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { FrontendName := configFrontend["name"] - if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { + if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { customHttpsConfiguration := chc[0].(map[string]interface{}) certificateSource := customHttpsConfiguration["certificate_source"] if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { @@ -157,19 +157,19 @@ func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]inter certificateVaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"] if MatchAllKeys { - if strings.TrimSpace(certificateSecretName.(string)) != "" && strings.TrimSpace(certificateSecretVersion.(string)) != "" && strings.TrimSpace(certificateVaultId.(string)) != "" { + if strings.TrimSpace(certificateSecretName.(string)) != "" && strings.TrimSpace(certificateSecretVersion.(string)) != "" && strings.TrimSpace(certificateVaultId.(string)) != "" { return true } } else { - if strings.TrimSpace(certificateSecretName.(string)) != "" || strings.TrimSpace(certificateSecretVersion.(string)) != "" || strings.TrimSpace(certificateVaultId.(string)) != "" { + if strings.TrimSpace(certificateSecretName.(string)) != "" || strings.TrimSpace(certificateSecretVersion.(string)) != "" || strings.TrimSpace(certificateVaultId.(string)) != "" { return true } } - + return false } -func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, serviceName string, resourceType string, resourceName string) string { +func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, serviceName string, resourceType string, resourceName string) string { if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(serviceName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { return "" } @@ -177,10 +177,10 @@ func GetFrontDoorSubResourceId (subscriptionId string, resourceGroup string, ser return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontdoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) } -func GetFrontDoorBasicRouteConfigurationType (i interface{}) string { - _, ok := i.(frontdoor.ForwardingConfiguration ) +func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { + _, ok := i.(frontdoor.ForwardingConfiguration) if !ok { - _, ok := i.(frontdoor.RedirectConfiguration ) + _, ok := i.(frontdoor.RedirectConfiguration) if !ok { return "" } @@ -188,4 +188,4 @@ func GetFrontDoorBasicRouteConfigurationType (i interface{}) string { } else { return "ForwardingConfiguration" } -} \ No newline at end of file +} diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 2754dc4c39bc..b7b6a7c9d2f5 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -963,10 +963,10 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription func flattenArmFrontDoorBackendPools(input *[]frontdoor.BackendPool) []map[string]interface{} { if input == nil { - return make([]map[string]interface{},0) + return make([]map[string]interface{}, 0) } - output := make([]map[string]interface{},0) + output := make([]map[string]interface{}, 0) for _, v := range *input { result := make(map[string]interface{}) @@ -1012,7 +1012,7 @@ func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { return make([]interface{}, 0) } - output := make([]interface{},0) + output := make([]interface{}, 0) for _, v := range *input { result := make(map[string]interface{}) @@ -1023,8 +1023,8 @@ func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { if backendHostHeader := v.BackendHostHeader; backendHostHeader != nil { result["host_header"] = *backendHostHeader } - - if v.EnabledState == frontdoor.Enabled { + + if v.EnabledState == frontdoor.Enabled { result["enabled"] = true } else { result["enabled"] = false @@ -1080,7 +1080,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] result["session_affinity_enabled"] = false } } - + if sessionAffinityTtlSeconds := properties.SessionAffinityTTLSeconds; sessionAffinityTtlSeconds != nil { result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds } @@ -1094,12 +1094,12 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion } - } else { - // since FrontDoor is the default the API does not set this value (e.g. null) in Azure, + } else { + // since FrontDoor is the default the API does not set this value (e.g. null) in Azure, // Set default value for state file chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) } - + customHttpsConfiguration = append(customHttpsConfiguration, chc) result["custom_https_configuration"] = customHttpsConfiguration @@ -1119,7 +1119,7 @@ func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeS if id := v.ID; id != nil { result["id"] = *id } - if name :=v.Name; name != nil { + if name := v.Name; name != nil { result["name"] = *name } if properties := v.HealthProbeSettingsProperties; properties != nil { @@ -1200,12 +1200,12 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ // there are only two types of Route Configuration Types if routeConfigType == "ForwardingConfiguration" { v := brc.(frontdoor.ForwardingConfiguration) - + c["backend_pool_name"] = flattenArmFrontDoorSubResource(v.BackendPool, "backendPools") c["custom_forwarding_path"] = v.CustomForwardingPath c["forwarding_protocol"] = string(v.ForwardingProtocol) - cc := v.CacheConfiguration + cc := v.CacheConfiguration c["cache_query_parameter_strip_directive"] = string(cc.QueryParameterStripDirective) if cc.DynamicCompression == frontdoor.DynamicCompressionEnabledEnabled { c["cache_use_dynamic_compression"] = true @@ -1219,7 +1219,7 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ v := brc.(frontdoor.RedirectConfiguration) c["custom_fragment"] = v.CustomFragment c["custom_host"] = v.CustomHost - c["custom_path"] = v.CustomPath + c["custom_path"] = v.CustomPath c["custom_query_string"] = v.CustomQueryString c["redirect_protocol"] = string(v.RedirectProtocol) c["redirect_type"] = string(v.RedirectType) @@ -1227,7 +1227,7 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ rc = append(rc, c) result["redirect_configuration"] = rc } - } + } } } @@ -1241,7 +1241,7 @@ func flattenArmFrontDoorAcceptedProtocol(input *[]frontdoor.Protocol) []string { return make([]string, 0) } - output := make([]string,0) + output := make([]string, 0) for _, p := range *input { output = append(output, string(p)) } @@ -1271,9 +1271,9 @@ func flattenArmFrontDoorFrontendEndpointsSubResources(input *[]frontdoor.SubReso if input == nil { return make([]string, 0) } - - output := make([]string,0) - + + output := make([]string, 0) + for _, v := range *input { name := flattenArmFrontDoorSubResource(&v, "frontendEndpoints") output = append(output, name) From 156b97b02e279f7d2a34dc529a5d75bb18783997 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 26 Jul 2019 17:29:55 -0700 Subject: [PATCH 17/74] WIP: Added first test --- azurerm/resource_arm_front_door.go | 2 +- azurerm/resource_arm_front_door_test.go | 149 +++++++++++++++++++++++- 2 files changed, 144 insertions(+), 7 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index b7b6a7c9d2f5..03e5909afdef 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -493,7 +493,7 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } d.Set("name", resp.Name) - d.Set("resource_group", resourceGroup) + d.Set("resource_group_name", resourceGroup) if location := resp.Location; location != nil { d.Set("location", azure.NormalizeLocation(*location)) } diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 5c2165d1515a..4ab907dabd6e 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -1,15 +1,72 @@ package azurerm import ( - "fmt" - //"testing" + "fmt" + "strings" + "testing" "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" - //"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/hashicorp/terraform/terraform" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) +func TestAccAzureRMFrontDoor_basic(t *testing.T) { + resourceName := "azurerm_frontdoor.test" + ri := tf.AccRandTimeInt() + rs := strings.ToLower(acctest.RandString(5)) + config := testAccAzureRMFrontDoor_basic(ri, rs, testLocation()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMFunctionAppDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("testaccfrontdoorsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -19,7 +76,7 @@ func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc } name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] client := testAccProvider.Meta().(*ArmClient).frontDoorsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext @@ -45,7 +102,7 @@ func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { } name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] if resp, err := client.Get(ctx, resourceGroup, name); err != nil { if !utils.ResponseWasNotFound(resp.Response) { @@ -58,3 +115,83 @@ func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { return nil } + +func testAccAzureRMFrontDoor_basic(rInt int, rString string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testAccRG-%[1]d" + location = "%[3]s" +} + +resource "azurerm_storage_account" "test" { + name = "testaccfrontdoorsa%[2]s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_frontdoor" "test" { + name = "testAccFrontDoor-%[1]d" + friendly_name = "tafd" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + enabled = true + + routing_rule { + name = "testAccRoutingRulerule1-%[1]d" + enabled = true + accepted_protocols = ["Http", "Https"] + patterns_to_match = ["/*"] + frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] + forwarding_configuration { + forwarding_protocol = "MatchRequest" + cache_use_dynamic_compression = true + backend_pool_name = "testAccBackendPool1-%[1]d" + } + } + + enforce_backend_pools_certificate_name_check = true + + backend_pool_load_balancing { + name = "testAccLoadBalancingSettings1-%[1]d" + sample_size = 4 + successful_samples_required = 2 + additional_latency_milliseconds = 0 + } + + backend_pool_health_probe { + name = "testAccHealthProbeSetting1-%[1]d" + path = "/" + protocol = "Https" + interval_in_seconds = 30 + } + + backend_pool { + name = "testAccBackendPool1-%[1]d" + backend { + enabled = true + host_header = "${azurerm_storage_account.test.name}.blob.core.windows.net" + address = "${azurerm_storage_account.test.name}.blob.core.windows.net" + http_port = 80 + https_port = 443 + weight = 50 + priority = 1 + } + + load_balancing_name = "testAccLoadBalancingSettings1-%[1]d" + health_probe_name = "testAccHealthProbeSetting1-%[1]d" + } + + frontend_endpoint { + name = "testAccFrontendEndpoint1-%[1]d" + host_name = "testAccFrontDoor-%[1]d.azurefd.net" + session_affinity_enabled = true + session_affinity_ttl_seconds = 0 + custom_https_configuration { + certificate_source = "FrontDoor" + } + } +} +`, rInt, rString, location) +} \ No newline at end of file From ca743f9ddcc4b4c1e24899d60bb9b5b7f3ef07fd Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 29 Jul 2019 14:45:08 -0700 Subject: [PATCH 18/74] Fixed casing issue when interacting with portal --- azurerm/helpers/azure/frontdoor.go | 2 +- azurerm/resource_arm_front_door.go | 30 ++++++------- azurerm/resource_arm_front_door_test.go | 56 +++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 15 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 53aa0f47db3a..55330b327ada 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -174,7 +174,7 @@ func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, serv return "" } - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/frontdoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) + return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) } func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 03e5909afdef..0c6b4f43285e 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -575,13 +575,13 @@ func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, backends := backendPool["backend"].([]interface{}) result := frontdoor.BackendPool{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "backendPools", backendPoolName)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "BackendPools", backendPoolName)), Name: utils.String(backendPoolName), BackendPoolProperties: &frontdoor.BackendPoolProperties{ // ResourceState Backends: expandArmFrontDoorBackend(backends), - LoadBalancingSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "loadBalancingSettings", backendPoolLoadBalancingName), - HealthProbeSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "healthProbeSettings", backendPoolHealthProbeName), + LoadBalancingSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "LoadBalancingSettings", backendPoolLoadBalancingName), + HealthProbeSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "HealthProbeSettings", backendPoolHealthProbeName), }, } @@ -662,7 +662,7 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri sessionAffinityTtlSeconds := int32(frontendEndpoint["session_affinity_ttl_seconds"].(int)) customHttpsConfiguration := frontendEndpoint["custom_https_configuration"].([]interface{}) name := frontendEndpoint["name"].(string) - id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", name)) + id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "FrontendEndpoints", name)) sessionAffinityEnabled := frontdoor.SessionAffinityEnabledStateDisabled @@ -743,7 +743,7 @@ func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptio name := v["name"].(string) result := frontdoor.HealthProbeSettingsModel{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "healthProbeSettings", name)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "HealthProbeSettings", name)), Name: utils.String(name), HealthProbeSettingsProperties: &frontdoor.HealthProbeSettingsProperties{ IntervalInSeconds: utils.Int32(intervalInSeconds), @@ -772,7 +772,7 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscript sampleSize := int32(loadBalanceSetting["sample_size"].(int)) successfulSamplesRequired := int32(loadBalanceSetting["successful_samples_required"].(int)) additionalLatencyMilliseconds := int32(loadBalanceSetting["additional_latency_milliseconds"].(int)) - id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "loadBalancingSettings", name)) + id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "LoadBalancingSettings", name)) result := frontdoor.LoadBalancingSettingsModel{ ID: id, @@ -877,7 +877,7 @@ func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId str output := make([]frontdoor.SubResource, 0) for _, SubResource := range input { - result := *expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "frontendEndpoints", SubResource.(string)) + result := *expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "FrontendEndpoints", SubResource.(string)) output = append(output, result) } @@ -944,7 +944,7 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription } backend := &frontdoor.SubResource{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "backendPools", backendPoolName)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "BackendPools", backendPoolName)), } forwardingConfiguration := frontdoor.ForwardingConfiguration{ @@ -981,8 +981,8 @@ func flattenArmFrontDoorBackendPools(input *[]frontdoor.BackendPool) []map[strin if properties := v.BackendPoolProperties; properties != nil { result["backend"] = flattenArmFrontDoorBackend(properties.Backends) - result["health_probe_name"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings, "healthProbeSettings") - result["load_balancing_name"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings, "loadBalancingSettings") + result["health_probe_name"] = flattenArmFrontDoorSubResource(properties.HealthProbeSettings, "HealthProbeSettings") + result["load_balancing_name"] = flattenArmFrontDoorSubResource(properties.LoadBalancingSettings, "LoadBalancingSettings") } output = append(output, result) @@ -1177,7 +1177,9 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ if id := v.ID; id != nil { result["id"] = *id } - result["name"] = *v.Name + if name := v.Name; name != nil { + result["name"] = *name + } if properties := v.RoutingRuleProperties; properties != nil { result["accepted_protocols"] = flattenArmFrontDoorAcceptedProtocol(properties.AcceptedProtocols) @@ -1197,11 +1199,11 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ rc := make([]interface{}, 0) c := make(map[string]interface{}) - // there are only two types of Route Configuration Types + // there are only two types of Route Configuration if routeConfigType == "ForwardingConfiguration" { v := brc.(frontdoor.ForwardingConfiguration) - c["backend_pool_name"] = flattenArmFrontDoorSubResource(v.BackendPool, "backendPools") + c["backend_pool_name"] = flattenArmFrontDoorSubResource(v.BackendPool, "BackendPools") c["custom_forwarding_path"] = v.CustomForwardingPath c["forwarding_protocol"] = string(v.ForwardingProtocol) @@ -1275,7 +1277,7 @@ func flattenArmFrontDoorFrontendEndpointsSubResources(input *[]frontdoor.SubReso output := make([]string, 0) for _, v := range *input { - name := flattenArmFrontDoorSubResource(&v, "frontendEndpoints") + name := flattenArmFrontDoorSubResource(&v, "FrontendEndpoints") output = append(output, name) } diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 4ab907dabd6e..e478bf2880ca 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -68,6 +68,62 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { }) } +func TestAccAzureRMFrontDoor_update(t *testing.T) { + resourceName := "azurerm_frontdoor.test" + ri := tf.AccRandTimeInt() + rs := strings.ToLower(acctest.RandString(5)) + config := testAccAzureRMFrontDoor_basic(ri, rs, testLocation()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMFunctionAppDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("testaccfrontdoorsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] From c94c75af9a1c65ad7af061453fa0c8b1440df652 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 30 Jul 2019 19:55:52 -0700 Subject: [PATCH 19/74] Fix bug in fronend endpoint enum --- azurerm/resource_arm_front_door.go | 12 +- azurerm/resource_arm_front_door_test.go | 340 +++++++++++++++++++++++- website/docs/r/front_door.html.markdown | 17 +- 3 files changed, 352 insertions(+), 17 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 0c6b4f43285e..ab472dff263b 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -1056,12 +1056,15 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] if input == nil { return make([]interface{}, 0) } - - result := make(map[string]interface{}) + + output := make([]interface{}, 0) + customHttpsConfiguration := make([]interface{}, 0) chc := make(map[string]interface{}, 0) for _, v := range *input { + result := make(map[string]interface{}) + if id := v.ID; id != nil { result["id"] = *id } @@ -1105,8 +1108,11 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) } + + output = append(output, result) } - return []interface{}{result} + + return output } func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeSettingsModel) []interface{} { diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index e478bf2880ca..793ca6eec86f 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -32,7 +32,7 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "enabled", "true"), resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("testaccfrontdoorsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), @@ -73,6 +73,7 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { ri := tf.AccRandTimeInt() rs := strings.ToLower(acctest.RandString(5)) config := testAccAzureRMFrontDoor_basic(ri, rs, testLocation()) + update := testAccAzureRMFrontDoor_update(ri, rs, testLocation()) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -88,7 +89,102 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "enabled", "true"), resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("testaccfrontdoorsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), + ), + }, + { + Config: update, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.name", fmt.Sprintf("testAccBackendPool2-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.address", fmt.Sprintf("tafdsatwo%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), + ), + }, + }, + }) +} + +func TestAccAzureRMFrontDoor_keyVault(t *testing.T) { + resourceName := "azurerm_frontdoor.test" + ri := tf.AccRandTimeInt() + rs := strings.ToLower(acctest.RandString(5)) + config := testAccAzureRMFrontDoor_basic(ri, rs, testLocation()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMFunctionAppDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), @@ -180,7 +276,7 @@ resource "azurerm_resource_group" "test" { } resource "azurerm_storage_account" "test" { - name = "testaccfrontdoorsa%[2]s" + name = "tafdsa%[2]s" resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" account_tier = "Standard" @@ -227,8 +323,8 @@ resource "azurerm_frontdoor" "test" { name = "testAccBackendPool1-%[1]d" backend { enabled = true - host_header = "${azurerm_storage_account.test.name}.blob.core.windows.net" - address = "${azurerm_storage_account.test.name}.blob.core.windows.net" + host_header = "${azurerm_storage_account.test.primary_blob_host}" + address = "${azurerm_storage_account.test.primary_blob_host}" http_port = 80 https_port = 443 weight = 50 @@ -250,4 +346,238 @@ resource "azurerm_frontdoor" "test" { } } `, rInt, rString, location) +} + +func testAccAzureRMFrontDoor_update(rInt int, rString string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testAccRG-%[1]d" + location = "%[3]s" +} + +resource "azurerm_storage_account" "test" { + name = "tafdsa%[2]s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_account" "test2" { + name = "tafdsatwo%[2]s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_frontdoor" "test" { + name = "testAccFrontDoor-%[1]d" + friendly_name = "tafd" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + enabled = true + + routing_rule { + name = "testAccRoutingRulerule1-%[1]d" + enabled = true + accepted_protocols = ["Http", "Https"] + patterns_to_match = ["/*"] + frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] + forwarding_configuration { + forwarding_protocol = "MatchRequest" + cache_use_dynamic_compression = true + backend_pool_name = "testAccBackendPool1-%[1]d" + } + } + + enforce_backend_pools_certificate_name_check = true + + backend_pool_load_balancing { + name = "testAccLoadBalancingSettings1-%[1]d" + sample_size = 4 + successful_samples_required = 2 + additional_latency_milliseconds = 0 + } + + backend_pool_health_probe { + name = "testAccHealthProbeSetting1-%[1]d" + path = "/" + protocol = "Https" + interval_in_seconds = 30 + } + + backend_pool { + name = "testAccBackendPool1-%[1]d" + backend { + enabled = true + host_header = "${azurerm_storage_account.test.primary_blob_host}" + address = "${azurerm_storage_account.test.primary_blob_host}" + http_port = 80 + https_port = 443 + weight = 50 + priority = 1 + } + + load_balancing_name = "testAccLoadBalancingSettings1-%[1]d" + health_probe_name = "testAccHealthProbeSetting1-%[1]d" + } + + backend_pool { + name = "testAccBackendPool2-%[1]d" + backend { + enabled = true + host_header = "${azurerm_storage_account.test2.primary_blob_host}" + address = "${azurerm_storage_account.test2.primary_blob_host}" + http_port = 80 + https_port = 443 + weight = 50 + priority = 1 + } + + load_balancing_name = "testAccLoadBalancingSettings1-%[1]d" + health_probe_name = "testAccHealthProbeSetting1-%[1]d" + } + + frontend_endpoint { + name = "testAccFrontendEndpoint1-%[1]d" + host_name = "testAccFrontDoor-%[1]d.azurefd.net" + session_affinity_enabled = true + session_affinity_ttl_seconds = 0 + custom_https_configuration { + certificate_source = "FrontDoor" + } + } +} +`, rInt, rString, location) +} + +func testAccAzureRMFrontDoor_keyVault(rInt int, rString string, location string) string { + return fmt.Sprintf(` +data "azurerm_client_config" "current" {} + +resource "random_id" "server" { + keepers = { + azi_id = 1 + } + + byte_length = 8 +} + +resource "azurerm_resource_group" "test" { + name = "testAccRG-%[1]d" + location = "%[3]s" +} + +resource "azurerm_cdn_profile" "test" { + name = "testCdnProfile" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard_Verizon" +} + +resource "azurerm_cdn_endpoint" "test" { + name = "${random_id.server.hex}" + profile_name = "${azurerm_cdn_profile.test.name}" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + + origin { + name = "testCdnOrigin" + host_name = "www.fdcustomhost.com" + } +} + +resource "azurerm_key_vault" "test" { + name = "tfex-key-vault" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + enabled_for_disk_encryption = false + tenant_id = "${data.azurerm_client_config.current.tenant_id}" + sku_name = "standard" + } +} + +resource "azurerm_key_vault_key" "test" { + name = "tfex-key" + key_vault_id = "${azurerm_key_vault.test.id}" + key_type = "RSA" + key_size = 2048 + key_opts = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"] +} + +resource "azurerm_storage_account" "test" { + name = "tafdsa%[2]s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_frontdoor" "test" { + name = "testAccFrontDoor-%[1]d" + friendly_name = "tafd" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + enabled = true + + routing_rule { + name = "testAccRoutingRulerule1-%[1]d" + enabled = true + accepted_protocols = ["Http", "Https"] + patterns_to_match = ["/*"] + frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] + forwarding_configuration { + forwarding_protocol = "MatchRequest" + cache_use_dynamic_compression = true + backend_pool_name = "testAccBackendPool1-%[1]d" + } + } + + enforce_backend_pools_certificate_name_check = true + + backend_pool_load_balancing { + name = "testAccLoadBalancingSettings1-%[1]d" + sample_size = 4 + successful_samples_required = 2 + additional_latency_milliseconds = 0 + } + + backend_pool_health_probe { + name = "testAccHealthProbeSetting1-%[1]d" + path = "/" + protocol = "Https" + interval_in_seconds = 30 + } + + backend_pool { + name = "testAccBackendPool1-%[1]d" + backend { + enabled = true + host_header = "${azurerm_storage_account.test.primary_blob_host}" + address = "${azurerm_storage_account.test.primary_blob_host}" + http_port = 80 + https_port = 443 + weight = 50 + priority = 1 + } + + load_balancing_name = "testAccLoadBalancingSettings1-%[1]d" + health_probe_name = "testAccHealthProbeSetting1-%[1]d" + } + + frontend_endpoint { + name = "testAccFrontendEndpoint1-%[1]d" + host_name = "testAccFrontDoor-%[1]d.azurefd.net" + session_affinity_enabled = true + session_affinity_ttl_seconds = 0 + custom_https_configuration { + certificate_source = "AzureKeyVault" + azure_key_vault_certificate_vault_id = "${azurerm_key_vault_key.test.id}" + azure_key_vault_certificate_secret_name = "" + azure_key_vault_certificate_secret_version = "" + } + } +} +`, rInt, rString, location) } \ No newline at end of file diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index e34e8b20e72c..a7242004957d 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -10,7 +10,6 @@ description: |- Manage Azure FrontDoor instance. - ## Argument Reference The following arguments are supported: @@ -19,25 +18,25 @@ The following arguments are supported: * `resource_group` - (Required) Name of the Resource group within the Azure subscription. Changing this forces a new resource to be created. -* `location` - (Optional) Resource location. Changing this forces a new resource to be created. +* `location` - (Required) Resource location. Changing this forces a new resource to be created. -* `backend_pools` - (Optional) One `backend_pool` block defined below. +* `backend_pool` - (Required) One `backend_pool` block defined below. -* `backend_pools_settings` - (Optional) One `backend_pools_setting` block defined below. +* `backend_pools_settings` - (Required) One `backend_pools_setting` block defined below. -* `enabled_state` - (Optional) Operational status of the Front Door load balancer. Permitted values are 'Enabled' or 'Disabled' Defaults to `Enabled`. +* `enabled` - (Optional) Operational status of the Front Door load balancer. Permitted values are 'true' or 'false' Defaults to `true`. * `friendly_name` - (Optional) A friendly name for the frontDoor -* `frontend_endpoints` - (Optional) One `frontend_endpoint` block defined below. +* `frontend_endpoints` - (Required) One `frontend_endpoint` block defined below. -* `health_probe_settings` - (Optional) One `health_probe_setting` block defined below. +* `health_probe_settings` - (Required) One `health_probe_setting` block defined below. -* `load_balancing_settings` - (Optional) One `load_balancing_setting` block defined below. +* `load_balancing_settings` - (Required) One `load_balancing_setting` block defined below. * `resource_state` - (Optional) Resource status of the Front Door. Defaults to `Creating`. -* `routing_rules` - (Optional) One `routing_rule` block defined below. +* `routing_rules` - (Required) One `routing_rule` block defined below. * `tags` - (Optional) Resource tags. Changing this forces a new resource to be created. From aab4fafbf4df691d3dcac32ce556a864a22ceb72 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 31 Jul 2019 12:03:46 -0700 Subject: [PATCH 20/74] Bug fix for Frontend Endpoint flatten --- azurerm/resource_arm_front_door.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index ab472dff263b..b98ffd866bf8 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -1059,11 +1059,10 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] output := make([]interface{}, 0) - customHttpsConfiguration := make([]interface{}, 0) - chc := make(map[string]interface{}, 0) - for _, v := range *input { result := make(map[string]interface{}) + customHttpsConfiguration := make([]interface{}, 0) + chc := make(map[string]interface{}, 0) if id := v.ID; id != nil { result["id"] = *id From f871c66f21c03a1c76c2872ca6c04bc8421e5683 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 31 Jul 2019 18:30:37 -0700 Subject: [PATCH 21/74] Add data source --- azurerm/data_source_front_door.go | 392 ++++++++++++++++++++++++ azurerm/resource_arm_front_door.go | 7 +- website/docs/r/front_door.html.markdown | 8 + 3 files changed, 404 insertions(+), 3 deletions(-) create mode 100644 azurerm/data_source_front_door.go diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go new file mode 100644 index 000000000000..82a46b81edcf --- /dev/null +++ b/azurerm/data_source_front_door.go @@ -0,0 +1,392 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func dataSourceArmFrontDoor() *schema.Resource { + return &schema.Resource{ + Read: dataSourceArmFrontDoorRead, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateFrontDoorName, + }, + + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + + "location": azure.SchemaLocation(), + + "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), + + "routing_rule": { + Type: schema.TypeList, + MaxItems: 100, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "accepted_protocols": { + Type: schema.TypeList, + Computed: true, + MaxItems: 2, + Elem: &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + "patterns_to_match": { + Type: schema.TypeList, + Computed: true, + MaxItems: 25, + Elem: &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + "frontend_endpoints": { + Type: schema.TypeList, + Computed: true, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + "redirect_configuration": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "custom_fragment": { + Type: schema.TypeString, + Computed: true, + }, + "custom_host": { + Type: schema.TypeString, + Computed: true, + }, + "custom_path": { + Type: schema.TypeString, + Computed: true, + }, + "custom_query_string": { + Type: schema.TypeString, + Computed: true, + }, + "redirect_protocol": { + Type: schema.TypeString, + Computed: true, + }, + "redirect_type": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "forwarding_configuration": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "backend_pool_name": { + Type: schema.TypeString, + Computed: true, + }, + "cache_use_dynamic_compression": { + Type: schema.TypeBool, + Computed: true, + }, + "cache_query_parameter_strip_directive": { + Type: schema.TypeString, + Computed: true, + }, + "custom_forwarding_path": { + Type: schema.TypeString, + Computed: true, + }, + "forwarding_protocol": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "enforce_backend_pools_certificate_name_check": { + Type: schema.TypeBool, + Computed: true, + }, + "backend_pool_load_balancing": { + Type: schema.TypeList, + MaxItems: 5000, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "sample_size": { + Type: schema.TypeInt, + Computed: true, + }, + "successful_samples_required": { + Type: schema.TypeInt, + Computed: true, + }, + "additional_latency_milliseconds": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "backend_pool_health_probe": { + Type: schema.TypeList, + MaxItems: 5000, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "path": { + Type: schema.TypeString, + Computed: true, + }, + "protocol": { + Type: schema.TypeString, + Computed: true, + }, + "interval_in_seconds": { + Type: schema.TypeInt, + Computed: true, + }, + }, + }, + }, + "backend_pool": { + Type: schema.TypeList, + MaxItems: 50, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "backend": { + Type: schema.TypeList, + MaxItems: 100, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "address": { + Type: schema.TypeString, + Computed: true, + }, + "http_port": { + Type: schema.TypeInt, + Computed: true, + }, + "https_port": { + Type: schema.TypeInt, + Computed: true, + }, + "weight": { + Type: schema.TypeInt, + Computed: true, + }, + "priority": { + Type: schema.TypeInt, + Computed: true, + }, + "host_header": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "health_probe_name": { + Type: schema.TypeString, + Computed: true, + }, + "load_balancing_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "frontend_endpoint": { + Type: schema.TypeList, + MaxItems: 100, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Computed: true, + }, + "host_name": { + Type: schema.TypeString, + Computed: true, + }, + "session_affinity_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "session_affinity_ttl_seconds": { + Type: schema.TypeInt, + Computed: true, + }, + "custom_https_configuration": { + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "certificate_source": { + Type: schema.TypeString, + Computed: true, + }, + // NOTE: None of these attributes are valid if + // certificate_source is set to FrontDoor + "azure_key_vault_certificate_secret_name": { + Type: schema.TypeString, + Computed: true, + }, + "azure_key_vault_certificate_secret_version": { + Type: schema.TypeString, + Computed: true, + }, + "azure_key_vault_certificate_vault_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + + "friendly_name": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func dataSourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontDoorsClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + name := id.Path["frontdoors"] + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] Front Door %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("Error reading Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resourceGroup) + if location := resp.Location; location != nil { + d.Set("location", azure.NormalizeLocation(*location)) + } + if properties := resp.Properties; properties != nil { + if err := d.Set("backend_pool", flattenArmFrontDoorBackendPools(properties.BackendPools)); err != nil { + return fmt.Errorf("Error setting `backend_pool`: %+v", err) + } + if err := d.Set("enforce_backend_pools_certificate_name_check", flattenArmFrontDoorBackendPoolsSettings(properties.BackendPoolsSettings)); err != nil { + return fmt.Errorf("Error setting `enforce_backend_pools_certificate_name_check`: %+v", err) + } + d.Set("cname", properties.Cname) + if properties.EnabledState == frontdoor.EnabledStateEnabled { + d.Set("enabled", true) + } else { + d.Set("enabled", false) + } + d.Set("friendly_name", properties.FriendlyName) + if err := d.Set("frontend_endpoint", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { + return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) + } + if err := d.Set("backend_pool_health_probe", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { + return fmt.Errorf("Error setting `backend_pool_health_probe`: %+v", err) + } + if err := d.Set("backend_pool_load_balancing", flattenArmFrontDoorLoadBalancingSettingsModel(properties.LoadBalancingSettings)); err != nil { + return fmt.Errorf("Error setting `backend_pool_load_balancing`: %+v", err) + } + if err := d.Set("routing_rule", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { + return fmt.Errorf("Error setting `routing_rules`: %+v", err) + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index b98ffd866bf8..94d1ead25df8 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -1176,9 +1176,10 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ } output := make([]interface{}, 0) - result := make(map[string]interface{}) for _, v := range *input { + result := make(map[string]interface{}) + if id := v.ID; id != nil { result["id"] = *id } @@ -1236,9 +1237,9 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ } } } - } - output = append(output, result) + output = append(output, result) + } return output } diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index a7242004957d..3bead695b345 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -186,3 +186,11 @@ The following attributes are exported: * `id` - Resource ID. * `type` - Resource type. + +## Import + +Front Doors can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_frontdoor.frontdoor1 /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/mygroup1/providers/Microsoft.Network/frontdoors/frontdoor1 +``` \ No newline at end of file From 0b8f25991af10953211f23b9dd262e076d88e529 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 31 Jul 2019 19:12:55 -0700 Subject: [PATCH 22/74] Slight update to documentation --- website/docs/r/front_door.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 3bead695b345..7c3ee7443bcb 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -192,5 +192,5 @@ The following attributes are exported: Front Doors can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_frontdoor.frontdoor1 /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/mygroup1/providers/Microsoft.Network/frontdoors/frontdoor1 +terraform import azurerm_frontdoor.test /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/mygroup1/providers/Microsoft.Network/frontdoors/frontdoor1 ``` \ No newline at end of file From e2ebb0a815795b6b322de0dcf1157dff4eb91747 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 6 Aug 2019 16:37:23 -0700 Subject: [PATCH 23/74] Added Frontend client code --- azurerm/config.go | 11 ++- azurerm/data_source_front_door.go | 10 ++- azurerm/resource_arm_front_door.go | 125 +++++++++++++++++++---------- 3 files changed, 100 insertions(+), 46 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index accfb21c38a5..c1871c655afc 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -201,6 +201,7 @@ type ArmClient struct { // Frontdoor frontDoorsClient frontdoor.FrontDoorsClient + frontDoorsFrontendClient frontdoor.FrontendEndpointsClient // KeyVault keyVaultClient keyvault.VaultsClient @@ -693,9 +694,13 @@ func (c *ArmClient) registerMonitorClients(endpoint, subscriptionId string, auth } func (c *ArmClient) registerFrontdoorInstanceClients(endpoint, subscriptionId string, auth autorest.Authorizer) { - fdc := frontdoor.NewFrontDoorsClientWithBaseURI(endpoint, subscriptionId) - c.configureClient(&fdc.Client, auth) - c.frontDoorsClient = fdc + frontDoorsClient := frontdoor.NewFrontDoorsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&frontDoorsClient.Client, auth) + c.frontDoorsClient = frontDoorsClient + + frontDoorsFrontendClient := frontdoor.NewFrontendEndpointsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&frontDoorsFrontendClient.Client, auth) + c.frontDoorsFrontendClient = frontDoorsFrontendClient } func (c *ArmClient) registerNetworkingClients(endpoint, subscriptionId string, auth autorest.Authorizer) { diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go index 82a46b81edcf..f974a6b5ed46 100644 --- a/azurerm/data_source_front_door.go +++ b/azurerm/data_source_front_door.go @@ -372,8 +372,14 @@ func dataSourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error d.Set("enabled", false) } d.Set("friendly_name", properties.FriendlyName) - if err := d.Set("frontend_endpoint", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { - return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) + frontDoorFrontendEndpoint, flattenErr := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta) + + if flattenErr == nil { + if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoint); err != nil { + return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) + } + } else { + return fmt.Errorf("Error setting `frontend_endpoint`: %+v", flattenErr) } if err := d.Set("backend_pool_health_probe", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { return fmt.Errorf("Error setting `backend_pool_health_probe`: %+v", err) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 94d1ead25df8..ee6ba11a9d12 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -511,8 +511,13 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { d.Set("enabled", false) } d.Set("friendly_name", properties.FriendlyName) - if err := d.Set("frontend_endpoint", flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints)); err != nil { - return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) + + if frontDoorFrontendEndpoint, err := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta); err != nil { + if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoint); err != nil { + return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) + } + } else { + return fmt.Errorf("Error flattening `frontend_endpoint`: %+v", err) } if err := d.Set("backend_pool_health_probe", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { return fmt.Errorf("Error setting `backend_pool_health_probe`: %+v", err) @@ -1052,11 +1057,11 @@ func flattenArmFrontDoorBackend(input *[]frontdoor.Backend) []interface{} { return output } -func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) []interface{} { +func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, resourceGroup string, frontDoorName string, meta interface{}) ([]interface{}, error) { if input == nil { - return make([]interface{}, 0) + return make([]interface{}, 0), fmt.Errorf("Cannot read Front Door Frontend Endpoint (Resource Group %q): slice is empty", resourceGroup) } - + output := make([]interface{}, 0) for _, v := range *input { @@ -1064,54 +1069,80 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint) [] customHttpsConfiguration := make([]interface{}, 0) chc := make(map[string]interface{}, 0) - if id := v.ID; id != nil { - result["id"] = *id - } if name := v.Name; name != nil { result["name"] = *name - } - if properties := v.FrontendEndpointProperties; properties != nil { - if hostName := properties.HostName; hostName != nil { - result["host_name"] = *hostName + // Need to call frontEndEndpointVlient here to get customConfiguration information from that client + // because the information is hidden from the main frontDoorClient "by design"... + // + // Get gets a Frontend endpoint with the specified name within the specified Front Door. + // Parameters: + // resourceGroupName - name of the Resource group within the Azure subscription. + // frontDoorName - name of the Front Door which is globally unique. + // frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. + + client := meta.(*ArmClient).frontDoorsFrontendClient + ctx := meta.(*ArmClient).StopContext + + resp, err := client.Get(ctx, resourceGroup, frontDoorName, *name) + if err != nil { + return make([]interface{}, 0), fmt.Errorf("Error retrieving Front Door Frontend Endpoint Custom HTTPS Configuration %q (Resource Group %q): %+v", name, resourceGroup, err) } - if sessionAffinityEnabled := properties.SessionAffinityEnabledState; sessionAffinityEnabled != "" { - if sessionAffinityEnabled == frontdoor.SessionAffinityEnabledStateEnabled { - result["session_affinity_enabled"] = true - } else { - result["session_affinity_enabled"] = false - } + if resp.ID == nil { + return make([]interface{}, 0), fmt.Errorf("Cannot read Front Door Frontend Endpoint Custom HTTPS Configuration %q (Resource Group %q) ID", name, resourceGroup) } - if sessionAffinityTtlSeconds := properties.SessionAffinityTTLSeconds; sessionAffinityTtlSeconds != nil { - result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds - } + result["id"] = resp.ID - if properties.CustomHTTPSConfiguration != nil { - chc["certificate_source"] = string(properties.CustomHTTPSConfiguration.CertificateSource) + if properties := resp.FrontendEndpointProperties; properties != nil { + log.Printf("********\n\nProperties:\n%+v\n", properties) - if properties.CustomHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { - kvcsp := properties.CustomHTTPSConfiguration.KeyVaultCertificateSourceParameters - chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID - chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName - chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion + if hostName := properties.HostName; hostName != nil { + result["host_name"] = *hostName + } + if sessionAffinityEnabled := properties.SessionAffinityEnabledState; sessionAffinityEnabled != "" { + if sessionAffinityEnabled == frontdoor.SessionAffinityEnabledStateEnabled { + result["session_affinity_enabled"] = true + } else { + result["session_affinity_enabled"] = false + } + } + + if sessionAffinityTtlSeconds := properties.SessionAffinityTTLSeconds; sessionAffinityTtlSeconds != nil { + result["session_affinity_ttl_seconds"] = *sessionAffinityTtlSeconds + } + + if properties.CustomHTTPSConfiguration != nil { + customHTTPSConfiguration := properties.CustomHTTPSConfiguration + log.Printf("\ncustomHTTPSConfiguration:\n%+v\n", customHTTPSConfiguration) + + chc["certificate_source"] = string(customHTTPSConfiguration.CertificateSource) + + if customHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { + log.Printf("\nCertificateSourceAzureKeyVault:\n%+v\n\n\n\n\n\n\n\n\n\n\n\n********", *customHTTPSConfiguration.KeyVaultCertificateSourceParameters) + + if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { + chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID + chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName + chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion + } + } else { + chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) + } + + customHttpsConfiguration = append(customHttpsConfiguration, chc) + result["custom_https_configuration"] = customHttpsConfiguration } - } else { - // since FrontDoor is the default the API does not set this value (e.g. null) in Azure, - // Set default value for state file - chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) - } - customHttpsConfiguration = append(customHttpsConfiguration, chc) - result["custom_https_configuration"] = customHttpsConfiguration + //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) + } - //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) } output = append(output, result) } - return output + return output, nil } func flattenArmFrontDoorHealthProbeSettingsModel(input *[]frontdoor.HealthProbeSettingsModel) []interface{} { @@ -1213,11 +1244,23 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ c["custom_forwarding_path"] = v.CustomForwardingPath c["forwarding_protocol"] = string(v.ForwardingProtocol) - cc := v.CacheConfiguration - c["cache_query_parameter_strip_directive"] = string(cc.QueryParameterStripDirective) - if cc.DynamicCompression == frontdoor.DynamicCompressionEnabledEnabled { - c["cache_use_dynamic_compression"] = true + if cacheConfiguration := v.CacheConfiguration; cacheConfiguration != nil { + if queryParameter := cacheConfiguration.QueryParameterStripDirective; queryParameter != "" { + c["cache_query_parameter_strip_directive"] = string(queryParameter) + } else { + c["cache_query_parameter_strip_directive"] = string(frontdoor.StripNone) + } + + c["cache_use_dynamic_compression"] = false + + if dynamicCompression := cacheConfiguration.DynamicCompression; dynamicCompression != "" { + if dynamicCompression == frontdoor.DynamicCompressionEnabledEnabled { + c["cache_use_dynamic_compression"] = true + } + } } else { + // Set Defaults + c["cache_query_parameter_strip_directive"] = string(frontdoor.StripNone) c["cache_use_dynamic_compression"] = false } From 36fd014b11d586173d40aff75fc4b21198234e1f Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 6 Aug 2019 18:12:41 -0700 Subject: [PATCH 24/74] Extending frontend endpoints schema --- azurerm/data_source_front_door.go | 12 ++++++++++++ azurerm/resource_arm_front_door.go | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go index f974a6b5ed46..167edc087143 100644 --- a/azurerm/data_source_front_door.go +++ b/azurerm/data_source_front_door.go @@ -291,6 +291,10 @@ func dataSourceArmFrontDoor() *schema.Resource { Type: schema.TypeInt, Computed: true, }, + "enable_custom_https_provisioning": { + Type: schema.TypeBool, + Computed: true, + }, "custom_https_configuration": { Type: schema.TypeList, Computed: true, @@ -301,6 +305,14 @@ func dataSourceArmFrontDoor() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "provisioning_state": { + Type: schema.TypeString, + Computed: true, + }, + "provisioning_substate": { + Type: schema.TypeString, + Computed: true, + }, // NOTE: None of these attributes are valid if // certificate_source is set to FrontDoor "azure_key_vault_certificate_secret_name": { diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index ee6ba11a9d12..3d2924e2b3d8 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -351,6 +351,10 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeInt, Optional: true, }, + "enable_custom_https_provisioning": { + Type: schema.TypeBool, + Required: true, + }, "custom_https_configuration": { Type: schema.TypeList, Optional: true, @@ -366,6 +370,14 @@ func resourceArmFrontDoor() *schema.Resource { }, false), Default: string(frontdoor.CertificateSourceFrontDoor), }, + "provisioning_state": { + Type: schema.TypeString, + Computed: true, + }, + "provisioning_substate": { + Type: schema.TypeString, + Computed: true, + }, // NOTE: None of these attributes are valid if // certificate_source is set to FrontDoor "azure_key_vault_certificate_secret_name": { From 51bef98e3d336ed0c0ee21cbbe37d356025c7070 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 8 Aug 2019 18:46:25 -0700 Subject: [PATCH 25/74] schema and exposed enable and disable for frontend --- azurerm/data_source_front_door.go | 9 +- azurerm/helpers/azure/frontdoor.go | 15 +- azurerm/resource_arm_front_door.go | 194 +++++++++++++++++++----- website/docs/r/front_door.html.markdown | 28 +++- 4 files changed, 199 insertions(+), 47 deletions(-) diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go index 167edc087143..0a1b8d77af6b 100644 --- a/azurerm/data_source_front_door.go +++ b/azurerm/data_source_front_door.go @@ -22,7 +22,7 @@ func dataSourceArmFrontDoor() *schema.Resource { ValidateFunc: azure.ValidateFrontDoorName, }, - "enabled": { + "load_balancer_enabled": { Type: schema.TypeBool, Computed: true, }, @@ -291,7 +291,7 @@ func dataSourceArmFrontDoor() *schema.Resource { Type: schema.TypeInt, Computed: true, }, - "enable_custom_https_provisioning": { + "custom_https_provisioning_enabled": { Type: schema.TypeBool, Computed: true, }, @@ -379,11 +379,12 @@ func dataSourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error } d.Set("cname", properties.Cname) if properties.EnabledState == frontdoor.EnabledStateEnabled { - d.Set("enabled", true) + d.Set("load_balancer_enabled", true) } else { - d.Set("enabled", false) + d.Set("load_balancer_enabled", false) } d.Set("friendly_name", properties.FriendlyName) + frontDoorFrontendEndpoint, flattenErr := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta) if flattenErr == nil { diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 55330b327ada..9cc0dcde3de4 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -169,12 +169,21 @@ func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]inter return false } -func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, serviceName string, resourceType string, resourceName string) string { - if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(serviceName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { +func IsFrontDoorFrontendEndpointConfigurable(currentState frontdoor.CustomHTTPSProvisioningState) bool { + switch currentState { + case frontdoor.CustomHTTPSProvisioningStateDisabling, frontdoor.CustomHTTPSProvisioningStateEnabling, frontdoor.CustomHTTPSProvisioningStateFailed: + return false + default: + return true + } +} + +func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { + if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { return "" } - return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, serviceName, resourceType, resourceName) + return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName) } func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 3d2924e2b3d8..72d67f6b4617 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -32,7 +32,7 @@ func resourceArmFrontDoor() *schema.Resource { ValidateFunc: azure.ValidateFrontDoorName, }, - "enabled": { + "load_balancer_enabled": { Type: schema.TypeBool, Optional: true, Default: true, @@ -351,7 +351,7 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeInt, Optional: true, }, - "enable_custom_https_provisioning": { + "custom_https_provisioning_enabled": { Type: schema.TypeBool, Required: true, }, @@ -433,10 +433,6 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } } - // if subId := azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, name, resourceType, resourceName); subId == "" { - // return fmt.Errorf("Error Front Door %q (Resource Group %q): unable to creating ID for sub resource", name, resourceGroup) - // } - location := azure.NormalizeLocation(d.Get("location").(string)) friendlyName := d.Get("friendly_name").(string) routingRules := d.Get("routing_rule").([]interface{}) @@ -445,7 +441,7 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) backendPools := d.Get("backend_pool").([]interface{}) frontendEndpoints := d.Get("frontend_endpoint").([]interface{}) backendPoolsSettings := d.Get("enforce_backend_pools_certificate_name_check").(bool) - enabledState := d.Get("enabled").(bool) + enabledState := d.Get("load_balancer_enabled").(bool) tags := d.Get("tags").(map[string]interface{}) frontDoorParameters := frontdoor.FrontDoor{ @@ -480,9 +476,110 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } d.SetId(*resp.ID) + // Now loop through the FrontendEndpoints and enable/disable Custom Domain HTTPS + // on each individual Frontend Endpoint if required + + for _, v := range frontendEndpoints { + frontendEndpoint := v.(map[string]interface{}) + + customHttpsProvisioningEnabled := frontendEndpoint["custom_https_provisioning_enabled"].(bool) + frontendEndpointName := frontendEndpoint["name"].(string) + chc := frontendEndpoint["custom_https_configuration"].([]interface{}) + + if len(chc) > 0 { + customHttpsConfiguration := chc[0].(map[string]interface{}) + + // Get current state of endpoint from Azure + client := meta.(*ArmClient).frontDoorsFrontendClient + ctx := meta.(*ArmClient).StopContext + + resp, err := client.Get(ctx, resourceGroup, name, frontendEndpointName) + if err != nil { + return fmt.Errorf("Error retrieving Front Door Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) + } + if resp.ID == nil { + return fmt.Errorf("Cannot read Front Door Frontend Endpoint %q (Resource Group %q) ID", frontendEndpointName, resourceGroup) + } + + if properties := resp.FrontendEndpointProperties; properties != nil { + if provisioningState := properties.CustomHTTPSProvisioningState; provisioningState != "" { + // return an error if the Frontend Endpoint is in a state that is unconfigurable + if azure.IsFrontDoorFrontendEndpointConfigurable(provisioningState) { + return fmt.Errorf("Unable to set Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because because the Frontend Endpoint is currently in the %q state", frontendEndpointName, resourceGroup, provisioningState) + } + + if customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateDisabled { + // build a custom Https configuration based off the config file to send to the enable call + // TODO: Consolidate this into a helper function since I do the same thing in two places... + customHTTPSConfigurationUpdate := frontdoor.CustomHTTPSConfiguration{ + ProtocolType: frontdoor.ServerNameIndication, + } + + if customHttpsConfiguration["certificate_source"].(string) == "AzureKeyVault" { + vaultSecret := customHttpsConfiguration["azure_key_vault_certificate_secret_name"].(string) + vaultVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"].(string) + vaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"].(string) + + customHTTPSConfigurationUpdate.CertificateSource = frontdoor.CertificateSourceAzureKeyVault + customHTTPSConfigurationUpdate.KeyVaultCertificateSourceParameters = &frontdoor.KeyVaultCertificateSourceParameters{ + Vault: &frontdoor.KeyVaultCertificateSourceParametersVault{ + ID: utils.String(vaultId), + }, + SecretName: utils.String(vaultSecret), + SecretVersion: utils.String(vaultVersion), + } + } else { + customHTTPSConfigurationUpdate.CertificateSource = frontdoor.CertificateSourceFrontDoor + customHTTPSConfigurationUpdate.CertificateSourceParameters = &frontdoor.CertificateSourceParameters{ + CertificateType: frontdoor.Dedicated, + } + } + + // Enable Custom Domain HTTPS for the Frontend Endpoint + if err := resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(true, name, frontendEndpointName, resourceGroup, customHTTPSConfigurationUpdate, meta); err != nil { + return fmt.Errorf("Unable enable Custom Domain HTTPS for Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) + } + } else if !customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled { + // Disable Custom Domain HTTPS for the Frontend Endpoint + if err := resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(false, name, frontendEndpointName, resourceGroup, frontdoor.CustomHTTPSConfiguration{}, meta); err != nil { + return fmt.Errorf("Unable to disable Custom Domain HTTPS for Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) + } + } + } + } + } + } + return resourceArmFrontDoorRead(d, meta) } +func resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(enableCustomHttpsProvisioning bool, frontDoorName string, frontendEndpointName string, resourceGroup string, customHTTPSConfiguration frontdoor.CustomHTTPSConfiguration, meta interface{}) error { + client := meta.(*ArmClient).frontDoorsFrontendClient + ctx := meta.(*ArmClient).StopContext + + if enableCustomHttpsProvisioning { + future, err := client.EnableHTTPS(ctx, resourceGroup, frontDoorName, frontendEndpointName, customHTTPSConfiguration) + + if err != nil { + return fmt.Errorf("Error enabling Custom Domain HTTPS for Frontend Endpoint: %+v", err) + } + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Error waiting to enable Custom Domain HTTPS for Frontend Endpoint: %+v", err) + } + } else { + future, err := client.DisableHTTPS(ctx, resourceGroup, frontDoorName, frontendEndpointName) + + if err != nil { + return fmt.Errorf("Error disabling Custom Domain HTTPS for Frontend Endpoint: %+v", err) + } + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Error waiting to disable Custom Domain HTTPS for Frontend Endpoint: %+v", err) + } + } + + return nil +} + func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext @@ -518,25 +615,28 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } d.Set("cname", properties.Cname) if properties.EnabledState == frontdoor.EnabledStateEnabled { - d.Set("enabled", true) + d.Set("load_balancer_enabled", true) } else { - d.Set("enabled", false) + d.Set("load_balancer_enabled", false) } d.Set("friendly_name", properties.FriendlyName) - if frontDoorFrontendEndpoint, err := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta); err != nil { + if frontDoorFrontendEndpoint, err := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta); frontDoorFrontendEndpoint != nil { if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoint); err != nil { return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) } } else { return fmt.Errorf("Error flattening `frontend_endpoint`: %+v", err) } + if err := d.Set("backend_pool_health_probe", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { return fmt.Errorf("Error setting `backend_pool_health_probe`: %+v", err) } + if err := d.Set("backend_pool_load_balancing", flattenArmFrontDoorLoadBalancingSettingsModel(properties.LoadBalancingSettings)); err != nil { return fmt.Errorf("Error setting `backend_pool_load_balancing`: %+v", err) } + if err := d.Set("routing_rule", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { return fmt.Errorf("Error setting `routing_rules`: %+v", err) } @@ -575,7 +675,7 @@ func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error return nil } -func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.BackendPool { +func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, resourceGroup string, frontDoorName string) *[]frontdoor.BackendPool { if len(input) == 0 { return &[]frontdoor.BackendPool{} } @@ -592,13 +692,13 @@ func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, backends := backendPool["backend"].([]interface{}) result := frontdoor.BackendPool{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "BackendPools", backendPoolName)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "BackendPools", backendPoolName)), Name: utils.String(backendPoolName), BackendPoolProperties: &frontdoor.BackendPoolProperties{ // ResourceState Backends: expandArmFrontDoorBackend(backends), - LoadBalancingSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "LoadBalancingSettings", backendPoolLoadBalancingName), - HealthProbeSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "HealthProbeSettings", backendPoolHealthProbeName), + LoadBalancingSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, frontDoorName, "LoadBalancingSettings", backendPoolLoadBalancingName), + HealthProbeSettings: expandArmFrontDoorSubResource(subscriptionId, resourceGroup, frontDoorName, "HealthProbeSettings", backendPoolHealthProbeName), }, } @@ -664,7 +764,7 @@ func expandArmFrontDoorBackendPoolsSettings(enforceCertificateNameCheck bool) *f return &result } -func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.FrontendEndpoint { +func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId string, resourceGroup string, frontDoorName string) *[]frontdoor.FrontendEndpoint { if len(input) == 0 { return &[]frontdoor.FrontendEndpoint{} } @@ -679,7 +779,7 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri sessionAffinityTtlSeconds := int32(frontendEndpoint["session_affinity_ttl_seconds"].(int)) customHttpsConfiguration := frontendEndpoint["custom_https_configuration"].([]interface{}) name := frontendEndpoint["name"].(string) - id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "FrontendEndpoints", name)) + id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "FrontendEndpoints", name)) sessionAffinityEnabled := frontdoor.SessionAffinityEnabledStateDisabled @@ -699,7 +799,6 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri SessionAffinityEnabledState: sessionAffinityEnabled, SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), // WebApplicationFirewallPolicyLink: - }, } @@ -744,7 +843,7 @@ func expandArmFrontDoorCustomHTTPSConfiguration(input []interface{}) *frontdoor. return &result } -func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.HealthProbeSettingsModel { +func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, frontDoorName string) *[]frontdoor.HealthProbeSettingsModel { if len(input) == 0 { return &[]frontdoor.HealthProbeSettingsModel{} } @@ -760,7 +859,7 @@ func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptio name := v["name"].(string) result := frontdoor.HealthProbeSettingsModel{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "HealthProbeSettings", name)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "HealthProbeSettings", name)), Name: utils.String(name), HealthProbeSettingsProperties: &frontdoor.HealthProbeSettingsProperties{ IntervalInSeconds: utils.Int32(intervalInSeconds), @@ -775,7 +874,7 @@ func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptio return &output } -func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.LoadBalancingSettingsModel { +func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, frontDoorName string) *[]frontdoor.LoadBalancingSettingsModel { if len(input) == 0 { return &[]frontdoor.LoadBalancingSettingsModel{} } @@ -789,7 +888,7 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscript sampleSize := int32(loadBalanceSetting["sample_size"].(int)) successfulSamplesRequired := int32(loadBalanceSetting["successful_samples_required"].(int)) additionalLatencyMilliseconds := int32(loadBalanceSetting["additional_latency_milliseconds"].(int)) - id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "LoadBalancingSettings", name)) + id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "LoadBalancingSettings", name)) result := frontdoor.LoadBalancingSettingsModel{ ID: id, @@ -807,7 +906,7 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscript return &output } -func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, resourceGroup, serviceName string) *[]frontdoor.RoutingRule { +func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, resourceGroup, frontDoorName string) *[]frontdoor.RoutingRule { if len(input) == 0 { return nil } @@ -835,7 +934,7 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r if rc := routingRule["redirect_configuration"].([]interface{}); len(rc) != 0 { routingConfiguration = expandArmFrontDoorRedirectConfiguration(rc) } else if fc := routingRule["forwarding_configuration"].([]interface{}); len(fc) != 0 { - routingConfiguration = expandArmFrontDoorForwardingConfiguration(fc, subscriptionId, resourceGroup, serviceName) + routingConfiguration = expandArmFrontDoorForwardingConfiguration(fc, subscriptionId, resourceGroup, frontDoorName) } currentRoutingRule := frontdoor.RoutingRule{ @@ -843,7 +942,7 @@ func expandArmFrontDoorRoutingRule(input []interface{}, subscriptionId string, r Name: utils.String(name), RoutingRuleProperties: &frontdoor.RoutingRuleProperties{ //ResourceState: - FrontendEndpoints: expandArmFrontDoorFrontEndEndpoints(frontendEndpoints, subscriptionId, resourceGroup, serviceName), + FrontendEndpoints: expandArmFrontDoorFrontEndEndpoints(frontendEndpoints, subscriptionId, resourceGroup, frontDoorName), AcceptedProtocols: expandArmFrontDoorAcceptedProtocols(acceptedProtocols), PatternsToMatch: &patternsToMatch, EnabledState: frontdoor.RoutingRuleEnabledState(expandArmFrontDoorEnabledState(enabled)), @@ -877,15 +976,15 @@ func expandArmFrontDoorAcceptedProtocols(input []interface{}) *[]frontdoor.Proto return &output } -func expandArmFrontDoorSubResource(subscriptionId string, resourceGroup string, serviceName string, resourceType string, resourceName string) *frontdoor.SubResource { +func expandArmFrontDoorSubResource(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) *frontdoor.SubResource { result := frontdoor.SubResource{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, resourceType, resourceName)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName)), } return &result } -func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId string, resourceGroup string, serviceName string) *[]frontdoor.SubResource { +func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId string, resourceGroup string, frontDoorName string) *[]frontdoor.SubResource { if len(input) == 0 { return &[]frontdoor.SubResource{} } @@ -894,7 +993,7 @@ func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId str output := make([]frontdoor.SubResource, 0) for _, SubResource := range input { - result := *expandArmFrontDoorSubResource(subscriptionId, resourceGroup, serviceName, "FrontendEndpoints", SubResource.(string)) + result := *expandArmFrontDoorSubResource(subscriptionId, resourceGroup, frontDoorName, "FrontendEndpoints", SubResource.(string)) output = append(output, result) } @@ -937,7 +1036,7 @@ func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.Redi return redirectConfiguration } -func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscriptionId string, resourceGroup, serviceName string) frontdoor.ForwardingConfiguration { +func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscriptionId string, resourceGroup, frontDoorName string) frontdoor.ForwardingConfiguration { if len(input) == 0 { return frontdoor.ForwardingConfiguration{} } @@ -961,7 +1060,7 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription } backend := &frontdoor.SubResource{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, serviceName, "BackendPools", backendPoolName)), + ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "BackendPools", backendPoolName)), } forwardingConfiguration := frontdoor.ForwardingConfiguration{ @@ -1075,7 +1174,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re } output := make([]interface{}, 0) - + for _, v := range *input { result := make(map[string]interface{}) customHttpsConfiguration := make([]interface{}, 0) @@ -1084,7 +1183,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if name := v.Name; name != nil { result["name"] = *name - // Need to call frontEndEndpointVlient here to get customConfiguration information from that client + // Need to call frontEndEndpointVlient here to get customConfiguration information from that client // because the information is hidden from the main frontDoorClient "by design"... // // Get gets a Frontend endpoint with the specified name within the specified Front Door. @@ -1112,6 +1211,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if hostName := properties.HostName; hostName != nil { result["host_name"] = *hostName } + if sessionAffinityEnabled := properties.SessionAffinityEnabledState; sessionAffinityEnabled != "" { if sessionAffinityEnabled == frontdoor.SessionAffinityEnabledStateEnabled { result["session_affinity_enabled"] = true @@ -1126,22 +1226,38 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if properties.CustomHTTPSConfiguration != nil { customHTTPSConfiguration := properties.CustomHTTPSConfiguration - log.Printf("\ncustomHTTPSConfiguration:\n%+v\n", customHTTPSConfiguration) + //log.Printf("\ncustomHTTPSConfiguration:\n%+v\n", customHTTPSConfiguration) chc["certificate_source"] = string(customHTTPSConfiguration.CertificateSource) if customHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { - log.Printf("\nCertificateSourceAzureKeyVault:\n%+v\n\n\n\n\n\n\n\n\n\n\n\n********", *customHTTPSConfiguration.KeyVaultCertificateSourceParameters) + // log.Printf("\nCertificateSourceAzureKeyVault:\n%+v\n\n\n\n\n\n\n\n\n\n\n\n********", *customHTTPSConfiguration.KeyVaultCertificateSourceParameters) - if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { - chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID - chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName - chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion - } + // if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { + // chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID + // chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName + // chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion + // } + + // DEBUG: Only like this to unblock development once AFD fix is deployed revert code back + chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) } else { chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) } + if provisioningState := properties.CustomHTTPSProvisioningState; provisioningState != "" { + chc["provisioning_state"] = provisioningState + if provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled || provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabling { + result["custom_https_provisioning_enabled"] = true + } else { + result["custom_https_provisioning_enabled"] = false + } + } + + if provisioningSubstate := properties.CustomHTTPSProvisioningSubstate; provisioningSubstate != "" { + chc["provisioning_substate"] = provisioningSubstate + } + customHttpsConfiguration = append(customHttpsConfiguration, chc) result["custom_https_configuration"] = customHttpsConfiguration } diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 7c3ee7443bcb..9749625097c3 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -173,7 +173,31 @@ The `routing_rule` block supports the following: The `frontend_endpoint` block supports the following: -* `id` - (Optional) Resource ID. +* `name` - (Required) Name of the Frontend endpoint. + +* `host_name` - (Required) Name of the Frontend endpoint. + +* `session_affinity_enabled` - (Required) Name of the Frontend endpoint. + +* `session_affinity_ttl_seconds` - (Required) Name of the Frontend endpoint. + +* `enable_custom_https_provisioning` - (Required) Name of the Frontend endpoint. + +--- + +The `custom_https_configuration` block supports the following: + +* `certificate_source` - (Optional) Certificate source to encrypted HTTPS traffic with. Permitted values are `FrontDoor` or `AzureKeyVault` Defaults to `FrontDoor`. + +* `azure_key_vault_certificate_vault_id` - (Required) Name of the Frontend endpoint. (Only if `certificate_source` is set to `AzureKeyVault`) + +* `azure_key_vault_certificate_secret_name` - (Required) Name of the Frontend endpoint. (Only if `certificate_source` is set to `AzureKeyVault`) + +* `azure_key_vault_certificate_secret_version` - (Required) Name of the Frontend endpoint. (Only if `certificate_source` is set to `AzureKeyVault`) + +~> **Note:** In order to enable the use of your own custom HTTPS certificate you must grant Azure Front Door Service access to your key vault. For instuctions on how to configure your Key Vault correctly please refer to the product [documentation](https://docs.microsoft.com/en-us/azure/frontdoor/front-door-custom-domain-https#option-2-use-your-own-certificate). + +--- ## Attributes Reference @@ -181,6 +205,8 @@ The following attributes are exported: * `provisioning_state` - Provisioning state of the Front Door. +* `provisioning_substate` - Provisioning substate of the Front Door + * `cname` - The host that each frontendEndpoint must CNAME to. * `id` - Resource ID. From ea00b84f51028bda15a797338eb9570cb7a10f8c Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 9 Aug 2019 18:05:19 -0700 Subject: [PATCH 26/74] Enabled custom HTTPS domain setting --- azurerm/helpers/azure/frontdoor.go | 10 +++++- azurerm/resource_arm_front_door.go | 57 ++++++++++++++++-------------- 2 files changed, 40 insertions(+), 27 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index 9cc0dcde3de4..dd5169fd9d7e 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -26,7 +26,7 @@ func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, er return nil, errors } -func ValidateFrontdoor(d *schema.ResourceData) error { +func ValidateFrontdoor(d *schema.ResourceDiff) error { routingRules := d.Get("routing_rule").([]interface{}) configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) backendPools := d.Get("backend_pool").([]interface{}) @@ -132,7 +132,13 @@ func ValidateFrontdoor(d *schema.ResourceData) error { for _, configFrontendEndpoint := range configFrontendEndpoints { if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { FrontendName := configFrontend["name"] + customHttpsEnabled := configFrontend["custom_https_provisioning_enabled"].(bool) + if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { + if !customHttpsEnabled { + return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid because "custom_https_provisioning_enabled" is set to "false". please remove the "custom_https_configuration" block from the configuration file`, FrontendName) + } + customHttpsConfiguration := chc[0].(map[string]interface{}) certificateSource := customHttpsConfiguration["certificate_source"] if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { @@ -144,6 +150,8 @@ func ValidateFrontdoor(d *schema.ResourceData) error { return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must be removed from the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) } } + } else if customHttpsEnabled { + return fmt.Errorf(`"frontend_endpoint":%q configuration is invalid because "custom_https_provisioning_enabled" is set to "true" and the "custom_https_configuration" block is undefined. please add the "custom_https_configuration" block to the configuration file`, FrontendName) } } } diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 72d67f6b4617..cd8e6192ba06 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -406,19 +406,23 @@ func resourceArmFrontDoor() *schema.Resource { "tags": tagsSchema(), }, - } -} -func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) error { - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) + CustomizeDiff: func(d *schema.ResourceDiff, v interface{}) error { + if err := azure.ValidateFrontdoor(d); err != nil { + return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", d.Get("name").(string), d.Get("resource_group_name").(string), err) + } - if err := azure.ValidateFrontdoor(d); err != nil { - return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + return nil + }, } +} +func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient).frontDoorsClient ctx := meta.(*ArmClient).StopContext + + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) subscriptionId := meta.(*ArmClient).subscriptionId if requireResourcesToBeImported { @@ -504,8 +508,9 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) if properties := resp.FrontendEndpointProperties; properties != nil { if provisioningState := properties.CustomHTTPSProvisioningState; provisioningState != "" { // return an error if the Frontend Endpoint is in a state that is unconfigurable - if azure.IsFrontDoorFrontendEndpointConfigurable(provisioningState) { - return fmt.Errorf("Unable to set Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because because the Frontend Endpoint is currently in the %q state", frontendEndpointName, resourceGroup, provisioningState) + if !azure.IsFrontDoorFrontendEndpointConfigurable(provisioningState) { + log.Printf("\n\n******************************************** %v ************************************************\n\n", provisioningState) + return fmt.Errorf("Unable to set Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because the Frontend Endpoint is currently in the %q state", frontendEndpointName, resourceGroup, provisioningState) } if customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateDisabled { @@ -621,8 +626,9 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } d.Set("friendly_name", properties.FriendlyName) - if frontDoorFrontendEndpoint, err := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta); frontDoorFrontendEndpoint != nil { - if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoint); err != nil { + if frontDoorFrontendEndpoints, err := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta); frontDoorFrontendEndpoints != nil { + + if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoints); err != nil { return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) } } else { @@ -810,7 +816,14 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri func expandArmFrontDoorCustomHTTPSConfiguration(input []interface{}) *frontdoor.CustomHTTPSConfiguration { if len(input) == 0 { - return &frontdoor.CustomHTTPSConfiguration{} + defaultHttpsConfiguration := frontdoor.CustomHTTPSConfiguration{ + ProtocolType: frontdoor.ServerNameIndication, + CertificateSource: frontdoor.CertificateSourceFrontDoor, + CertificateSourceParameters: &frontdoor.CertificateSourceParameters{ + CertificateType: frontdoor.Dedicated, + }, + } + return &defaultHttpsConfiguration } v := input[0].(map[string]interface{}) @@ -1206,8 +1219,6 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re result["id"] = resp.ID if properties := resp.FrontendEndpointProperties; properties != nil { - log.Printf("********\n\nProperties:\n%+v\n", properties) - if hostName := properties.HostName; hostName != nil { result["host_name"] = *hostName } @@ -1226,13 +1237,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if properties.CustomHTTPSConfiguration != nil { customHTTPSConfiguration := properties.CustomHTTPSConfiguration - //log.Printf("\ncustomHTTPSConfiguration:\n%+v\n", customHTTPSConfiguration) - - chc["certificate_source"] = string(customHTTPSConfiguration.CertificateSource) - if customHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { - // log.Printf("\nCertificateSourceAzureKeyVault:\n%+v\n\n\n\n\n\n\n\n\n\n\n\n********", *customHTTPSConfiguration.KeyVaultCertificateSourceParameters) - // if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { // chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID // chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName @@ -1249,17 +1254,17 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re chc["provisioning_state"] = provisioningState if provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled || provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabling { result["custom_https_provisioning_enabled"] = true + + if provisioningSubstate := properties.CustomHTTPSProvisioningSubstate; provisioningSubstate != "" { + chc["provisioning_substate"] = provisioningSubstate + } } else { result["custom_https_provisioning_enabled"] = false } - } - if provisioningSubstate := properties.CustomHTTPSProvisioningSubstate; provisioningSubstate != "" { - chc["provisioning_substate"] = provisioningSubstate + customHttpsConfiguration = append(customHttpsConfiguration, chc) + result["custom_https_configuration"] = customHttpsConfiguration } - - customHttpsConfiguration = append(customHttpsConfiguration, chc) - result["custom_https_configuration"] = customHttpsConfiguration } //result["web_application_firewall_policy_link"] = flattenArmFrontDoorFrontendEndpointUpdateParameters_webApplicationFirewallPolicyLink(properties.WebApplicationFirewallPolicyLink) From 7bf9a731676c4ffb70352a9b96eae53d395bbbca Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 12 Aug 2019 16:46:27 -0700 Subject: [PATCH 27/74] [WIP] Last code changes --- azurerm/helpers/azure/frontdoor.go | 20 +++- azurerm/resource_arm_front_door.go | 169 ++++++++++++----------------- 2 files changed, 87 insertions(+), 102 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index dd5169fd9d7e..e52269844804 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -177,13 +177,27 @@ func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]inter return false } -func IsFrontDoorFrontendEndpointConfigurable(currentState frontdoor.CustomHTTPSProvisioningState) bool { +func IsFrontDoorFrontendEndpointConfigurable(currentState frontdoor.CustomHTTPSProvisioningState, customHttpsProvisioningEnabled bool, frontendEndpointName string, resourceGroup string) error { + action := "disable" + if customHttpsProvisioningEnabled { + action = "enable" + } + switch currentState { case frontdoor.CustomHTTPSProvisioningStateDisabling, frontdoor.CustomHTTPSProvisioningStateEnabling, frontdoor.CustomHTTPSProvisioningStateFailed: - return false + return fmt.Errorf("Unable to %s the Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because the Frontend Endpoint is currently in the %q state", action, frontendEndpointName, resourceGroup, currentState) default: - return true + return nil + } +} + +func NormalizeCustomHTTPSProvisioningStateToBool(provisioningState frontdoor.CustomHTTPSProvisioningState) bool { + isEnabled := false + if provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled || provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabling { + isEnabled = true } + + return isEnabled } func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index cd8e6192ba06..b8bb71c46ecf 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -482,73 +482,48 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) // Now loop through the FrontendEndpoints and enable/disable Custom Domain HTTPS // on each individual Frontend Endpoint if required - for _, v := range frontendEndpoints { frontendEndpoint := v.(map[string]interface{}) - customHttpsProvisioningEnabled := frontendEndpoint["custom_https_provisioning_enabled"].(bool) frontendEndpointName := frontendEndpoint["name"].(string) - chc := frontendEndpoint["custom_https_configuration"].([]interface{}) - if len(chc) > 0 { - customHttpsConfiguration := chc[0].(map[string]interface{}) - - // Get current state of endpoint from Azure - client := meta.(*ArmClient).frontDoorsFrontendClient - ctx := meta.(*ArmClient).StopContext + // Get current state of endpoint from Azure + client := meta.(*ArmClient).frontDoorsFrontendClient + ctx := meta.(*ArmClient).StopContext - resp, err := client.Get(ctx, resourceGroup, name, frontendEndpointName) - if err != nil { - return fmt.Errorf("Error retrieving Front Door Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) - } - if resp.ID == nil { - return fmt.Errorf("Cannot read Front Door Frontend Endpoint %q (Resource Group %q) ID", frontendEndpointName, resourceGroup) - } + resp, err := client.Get(ctx, resourceGroup, name, frontendEndpointName) + if err != nil { + return fmt.Errorf("Error retrieving Front Door Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) + } + if resp.ID == nil { + return fmt.Errorf("Cannot read Front Door Frontend Endpoint %q (Resource Group %q) ID", frontendEndpointName, resourceGroup) + } - if properties := resp.FrontendEndpointProperties; properties != nil { - if provisioningState := properties.CustomHTTPSProvisioningState; provisioningState != "" { - // return an error if the Frontend Endpoint is in a state that is unconfigurable - if !azure.IsFrontDoorFrontendEndpointConfigurable(provisioningState) { - log.Printf("\n\n******************************************** %v ************************************************\n\n", provisioningState) - return fmt.Errorf("Unable to set Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because the Frontend Endpoint is currently in the %q state", frontendEndpointName, resourceGroup, provisioningState) + if properties := resp.FrontendEndpointProperties; properties != nil { + if provisioningState := properties.CustomHTTPSProvisioningState; provisioningState != "" { + // Check to see if we are going to change the CustomHTTPSProvisioningState, if so check to + // see if its current state is configurable, if not return an error... + if customHttpsProvisioningEnabled != azure.NormalizeCustomHTTPSProvisioningStateToBool(provisioningState) { + if err := azure.IsFrontDoorFrontendEndpointConfigurable(provisioningState, customHttpsProvisioningEnabled, frontendEndpointName, resourceGroup); err != nil { + return err } + } - if customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateDisabled { - // build a custom Https configuration based off the config file to send to the enable call - // TODO: Consolidate this into a helper function since I do the same thing in two places... - customHTTPSConfigurationUpdate := frontdoor.CustomHTTPSConfiguration{ - ProtocolType: frontdoor.ServerNameIndication, - } - - if customHttpsConfiguration["certificate_source"].(string) == "AzureKeyVault" { - vaultSecret := customHttpsConfiguration["azure_key_vault_certificate_secret_name"].(string) - vaultVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"].(string) - vaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"].(string) - - customHTTPSConfigurationUpdate.CertificateSource = frontdoor.CertificateSourceAzureKeyVault - customHTTPSConfigurationUpdate.KeyVaultCertificateSourceParameters = &frontdoor.KeyVaultCertificateSourceParameters{ - Vault: &frontdoor.KeyVaultCertificateSourceParametersVault{ - ID: utils.String(vaultId), - }, - SecretName: utils.String(vaultSecret), - SecretVersion: utils.String(vaultVersion), - } - } else { - customHTTPSConfigurationUpdate.CertificateSource = frontdoor.CertificateSourceFrontDoor - customHTTPSConfigurationUpdate.CertificateSourceParameters = &frontdoor.CertificateSourceParameters{ - CertificateType: frontdoor.Dedicated, - } - } + if customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateDisabled { + // Build a custom Https configuration based off the config file to send to the enable call + // NOTE: I do not need to check to see if this exists since I already do that in the validation code + chc := frontendEndpoint["custom_https_configuration"].([]interface{}) + customHttpsConfiguration := chc[0].(map[string]interface{}) + customHTTPSConfigurationUpdate := makeCustomHttpsConfiguration(customHttpsConfiguration) - // Enable Custom Domain HTTPS for the Frontend Endpoint - if err := resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(true, name, frontendEndpointName, resourceGroup, customHTTPSConfigurationUpdate, meta); err != nil { - return fmt.Errorf("Unable enable Custom Domain HTTPS for Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) - } - } else if !customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled { - // Disable Custom Domain HTTPS for the Frontend Endpoint - if err := resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(false, name, frontendEndpointName, resourceGroup, frontdoor.CustomHTTPSConfiguration{}, meta); err != nil { - return fmt.Errorf("Unable to disable Custom Domain HTTPS for Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) - } + // Enable Custom Domain HTTPS for the Frontend Endpoint + if err := resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(true, name, frontendEndpointName, resourceGroup, customHTTPSConfigurationUpdate, meta); err != nil { + return fmt.Errorf("Unable enable Custom Domain HTTPS for Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) + } + } else if !customHttpsProvisioningEnabled && provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled { + // Disable Custom Domain HTTPS for the Frontend Endpoint + if err := resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(false, name, frontendEndpointName, resourceGroup, frontdoor.CustomHTTPSConfiguration{}, meta); err != nil { + return fmt.Errorf("Unable to disable Custom Domain HTTPS for Frontend Endpoint %q (Resource Group %q): %+v", frontendEndpointName, resourceGroup, err) } } } @@ -827,33 +802,9 @@ func expandArmFrontDoorCustomHTTPSConfiguration(input []interface{}) *frontdoor. } v := input[0].(map[string]interface{}) - certSource := v["certificate_source"].(string) - - result := frontdoor.CustomHTTPSConfiguration{ - ProtocolType: frontdoor.ServerNameIndication, - } - - if certSource == "AzureKeyVault" { - vaultSecret := v["azure_key_vault_certificate_secret_name"].(string) - vaultVersion := v["azure_key_vault_certificate_secret_version"].(string) - vaultId := v["azure_key_vault_certificate_vault_id"].(string) - - result.CertificateSource = frontdoor.CertificateSourceAzureKeyVault - result.KeyVaultCertificateSourceParameters = &frontdoor.KeyVaultCertificateSourceParameters{ - Vault: &frontdoor.KeyVaultCertificateSourceParametersVault{ - ID: utils.String(vaultId), - }, - SecretName: utils.String(vaultSecret), - SecretVersion: utils.String(vaultVersion), - } - } else { - result.CertificateSource = frontdoor.CertificateSourceFrontDoor - result.CertificateSourceParameters = &frontdoor.CertificateSourceParameters{ - CertificateType: frontdoor.Dedicated, - } - } + customHttpsConfiguration := makeCustomHttpsConfiguration(v) - return &result + return &customHttpsConfiguration } func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptionId string, resourceGroup string, frontDoorName string) *[]frontdoor.HealthProbeSettingsModel { @@ -1196,15 +1147,8 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if name := v.Name; name != nil { result["name"] = *name - // Need to call frontEndEndpointVlient here to get customConfiguration information from that client + // Need to call frontEndEndpointClient here to get customConfiguration information from that client // because the information is hidden from the main frontDoorClient "by design"... - // - // Get gets a Frontend endpoint with the specified name within the specified Front Door. - // Parameters: - // resourceGroupName - name of the Resource group within the Azure subscription. - // frontDoorName - name of the Front Door which is globally unique. - // frontendEndpointName - name of the Frontend endpoint which is unique within the Front Door. - client := meta.(*ArmClient).frontDoorsFrontendClient ctx := meta.(*ArmClient).StopContext @@ -1237,15 +1181,13 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if properties.CustomHTTPSConfiguration != nil { customHTTPSConfiguration := properties.CustomHTTPSConfiguration + log.Printf("\n**********************************************************\n%+v\n**********************************************************\n", customHTTPSConfiguration) if customHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { - // if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { - // chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID - // chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName - // chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion - // } - - // DEBUG: Only like this to unblock development once AFD fix is deployed revert code back - chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) + if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { + chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID + chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName + chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion + } } else { chc["certificate_source"] = string(frontdoor.CertificateSourceFrontDoor) } @@ -1465,3 +1407,32 @@ func flattenArmFrontDoorFrontendEndpointsSubResources(input *[]frontdoor.SubReso return output } + +func makeCustomHttpsConfiguration(customHttpsConfiguration map[string]interface{}) frontdoor.CustomHTTPSConfiguration { + + customHTTPSConfigurationUpdate := frontdoor.CustomHTTPSConfiguration{ + ProtocolType: frontdoor.ServerNameIndication, + } + + if customHttpsConfiguration["certificate_source"].(string) == "AzureKeyVault" { + vaultSecret := customHttpsConfiguration["azure_key_vault_certificate_secret_name"].(string) + vaultVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"].(string) + vaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"].(string) + + customHTTPSConfigurationUpdate.CertificateSource = frontdoor.CertificateSourceAzureKeyVault + customHTTPSConfigurationUpdate.KeyVaultCertificateSourceParameters = &frontdoor.KeyVaultCertificateSourceParameters{ + Vault: &frontdoor.KeyVaultCertificateSourceParametersVault{ + ID: utils.String(vaultId), + }, + SecretName: utils.String(vaultSecret), + SecretVersion: utils.String(vaultVersion), + } + } else { + customHTTPSConfigurationUpdate.CertificateSource = frontdoor.CertificateSourceFrontDoor + customHTTPSConfigurationUpdate.CertificateSourceParameters = &frontdoor.CertificateSourceParameters{ + CertificateType: frontdoor.Dedicated, + } + } + + return customHTTPSConfigurationUpdate +} \ No newline at end of file From 161ac42dd6a856da10d2a4ddbd4c4fc7cc1448be Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Aug 2019 19:03:05 -0700 Subject: [PATCH 28/74] Tweeking defaults and adding validation rules --- azurerm/helpers/azure/frontdoor.go | 84 ++++-- azurerm/resource_arm_front_door.go | 72 ++--- azurerm/resource_arm_front_door_test.go | 345 ++++-------------------- 3 files changed, 156 insertions(+), 345 deletions(-) diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/helpers/azure/frontdoor.go index e52269844804..7bda490e561c 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/helpers/azure/frontdoor.go @@ -47,15 +47,31 @@ func ValidateFrontdoor(d *schema.ResourceDiff) error { redirectConfig := routingRule["redirect_configuration"].([]interface{}) forwardConfig := routingRule["forwarding_configuration"].([]interface{}) + // Check 0. validate that at least one routing configuration exists per routing rule + if len(redirectConfig) == 0 && len(forwardConfig) == 0 { + return fmt.Errorf(`"routing_rule":%q is invalid. you must have either a "redirect_configuration" or a "forwarding_configuration" defined for the "routing_rule":%q `, routingRuleName, routingRuleName) + } + // Check 1. validate that only one configuration type is defined per routing rule if len(redirectConfig) == 1 && len(forwardConfig) == 1 { - return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per routing rule`, routingRuleName) + return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per each routing rule`, routingRuleName) + } + + // Check 2. routing rule is a forwarding_configuration type make sure the backend_pool_name exists in the configuration file + if len(forwardConfig) > 0 { + fc := forwardConfig[0].(map[string]interface{}) + if err := backendPoolExists(fc["backend_pool_name"].(string), backendPools); err != nil { + return fmt.Errorf(`"routing_rule":%q is invalid. %+v`, routingRuleName, err) + } } - // Check 2. validate that each routing rule frontend_endpoints are actually defined in the resource schema + // Check 3. validate that each routing rule frontend_endpoints are actually defined in the resource schema if routingRuleFrontends := routingRule["frontend_endpoints"].([]interface{}); len(routingRuleFrontends) > 0 { for _, routingRuleFrontend := range routingRuleFrontends { + // + //TODO: Refactor to helper function that returns an error + // // Get the name of the frontend defined in the routing rule routingRulefrontendName := routingRuleFrontend.(string) found = false @@ -84,45 +100,48 @@ func ValidateFrontdoor(d *schema.ResourceDiff) error { // Verify backend pool load balancing settings and health probe settings are defined in the resource schema if backendPools != nil { - for _, bp := range backendPools { - backendPool := bp.(map[string]interface{}) + for _, bps := range backendPools { + backendPool := bps.(map[string]interface{}) backendPoolName := backendPool["name"] backendPoolLoadBalancingName := backendPool["load_balancing_name"] backendPoolHealthProbeName := backendPool["health_probe_name"] found := false // Verify backend pool load balancing settings name exists - for _, lbs := range loadBalancingSettings { - loadBalancing := lbs.(map[string]interface{}) - loadBalancingName := loadBalancing["name"] - - if loadBalancingName == backendPoolLoadBalancingName { - found = true - break + if len(loadBalancingSettings) > 0 { + for _, lbs := range loadBalancingSettings { + loadBalancing := lbs.(map[string]interface{}) + loadBalancingName := loadBalancing["name"] + + if loadBalancingName == backendPoolLoadBalancingName { + found = true + break + } } - } - if !found { - return fmt.Errorf(`"backend_pool":%q "load_balancing_name":%q was not found in the configuration file. verify you have the "backend_pool_load_balancing":%q defined in the configuration file`, backendPoolName, backendPoolLoadBalancingName, backendPoolLoadBalancingName) + if !found { + return fmt.Errorf(`"backend_pool":%q "load_balancing_name":%q was not found in the configuration file. verify you have the "backend_pool_load_balancing":%q defined in the configuration file`, backendPoolName, backendPoolLoadBalancingName, backendPoolLoadBalancingName) + } } found = false // Verify health probe settings name exists - for _, hps := range healthProbeSettings { - healthProbe := hps.(map[string]interface{}) - healthProbeName := healthProbe["name"] - - if healthProbeName == backendPoolHealthProbeName { - found = true - break + if len(healthProbeSettings) > 0 { + for _, hps := range healthProbeSettings { + healthProbe := hps.(map[string]interface{}) + healthProbeName := healthProbe["name"] + + if healthProbeName == backendPoolHealthProbeName { + found = true + break + } } - } - if !found { - return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) + if !found { + return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) + } } - } } else { return fmt.Errorf(`"backend_pool": must have at least one "backend" defined`) @@ -159,6 +178,21 @@ func ValidateFrontdoor(d *schema.ResourceDiff) error { return nil } +func backendPoolExists(backendPoolName string, backendPools []interface{}) error { + if backendPoolName == "" { + return fmt.Errorf(`"backend_pool_name" cannot be empty`) + } + + for _, bps := range backendPools { + backendPool := bps.(map[string]interface{}) + if backendPool["name"].(string) == backendPoolName { + return nil + } + } + + return fmt.Errorf(`unable to locate "backend_pool_name":%q in configuration file`, backendPoolName) +} + func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]interface{}, MatchAllKeys bool) bool { certificateSecretName := customHttpsConfiguration["azure_key_vault_certificate_secret_name"] certificateSecretVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"] diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index b8bb71c46ecf..1c52319220d0 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -32,6 +32,11 @@ func resourceArmFrontDoor() *schema.Resource { ValidateFunc: azure.ValidateFrontDoorName, }, + "friendly_name": { + Type: schema.TypeString, + Optional: true, + }, + "load_balancer_enabled": { Type: schema.TypeBool, Optional: true, @@ -45,7 +50,7 @@ func resourceArmFrontDoor() *schema.Resource { "routing_rule": { Type: schema.TypeList, MaxItems: 100, - Optional: true, + Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "id": { @@ -64,7 +69,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "accepted_protocols": { Type: schema.TypeList, - Optional: true, + Required: true, MaxItems: 2, Elem: &schema.Schema{ Type: schema.TypeString, @@ -72,16 +77,14 @@ func resourceArmFrontDoor() *schema.Resource { string(frontdoor.HTTP), string(frontdoor.HTTPS), }, false), - Default: string(frontdoor.HTTP), }, }, "patterns_to_match": { Type: schema.TypeList, - Optional: true, + Required: true, MaxItems: 25, Elem: &schema.Schema{ - Type: schema.TypeString, - Default: "/*", + Type: schema.TypeString, }, }, "frontend_endpoints": { @@ -104,7 +107,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "custom_host": { Type: schema.TypeString, - Optional: true, + Required: true, }, "custom_path": { Type: schema.TypeString, @@ -143,8 +146,9 @@ func resourceArmFrontDoor() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "backend_pool_name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "cache_use_dynamic_compression": { Type: schema.TypeBool, @@ -187,7 +191,7 @@ func resourceArmFrontDoor() *schema.Resource { "backend_pool_load_balancing": { Type: schema.TypeList, MaxItems: 5000, - Optional: true, + Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "id": { @@ -212,7 +216,7 @@ func resourceArmFrontDoor() *schema.Resource { "additional_latency_milliseconds": { Type: schema.TypeInt, Optional: true, - Default: 2, + Default: 0, }, }, }, @@ -220,7 +224,7 @@ func resourceArmFrontDoor() *schema.Resource { "backend_pool_health_probe": { Type: schema.TypeList, MaxItems: 5000, - Optional: true, + Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "id": { @@ -293,12 +297,13 @@ func resourceArmFrontDoor() *schema.Resource { }, "priority": { Type: schema.TypeInt, - Required: true, + Optional: true, ValidateFunc: validation.IntBetween(1, 5), + Default: 1, }, "host_header": { Type: schema.TypeString, - Optional: true, + Required: true, }, }, }, @@ -314,11 +319,11 @@ func resourceArmFrontDoor() *schema.Resource { }, "health_probe_name": { Type: schema.TypeString, - Optional: true, + Required: true, }, "load_balancing_name": { Type: schema.TypeString, - Optional: true, + Required: true, }, }, }, @@ -335,7 +340,7 @@ func resourceArmFrontDoor() *schema.Resource { }, "name": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, }, "host_name": { @@ -345,11 +350,12 @@ func resourceArmFrontDoor() *schema.Resource { "session_affinity_enabled": { Type: schema.TypeBool, Optional: true, - Default: true, + Default: false, }, "session_affinity_ttl_seconds": { Type: schema.TypeInt, Optional: true, + Default: 0, }, "custom_https_provisioning_enabled": { Type: schema.TypeBool, @@ -399,11 +405,6 @@ func resourceArmFrontDoor() *schema.Resource { }, }, - "friendly_name": { - Type: schema.TypeString, - Optional: true, - }, - "tags": tagsSchema(), }, @@ -988,13 +989,22 @@ func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.Redi customQueryString := v["custom_query_string"].(string) redirectConfiguration := frontdoor.RedirectConfiguration{ - RedirectType: frontdoor.RedirectType(redirectType), - RedirectProtocol: frontdoor.RedirectProtocol(redirectProtocol), - CustomHost: utils.String(customHost), - CustomPath: utils.String(customPath), - CustomFragment: utils.String(customFragment), - CustomQueryString: utils.String(customQueryString), - OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration, + CustomHost: utils.String(customHost), + RedirectType: frontdoor.RedirectType(redirectType), + RedirectProtocol: frontdoor.RedirectProtocol(redirectProtocol), + OdataType: frontdoor.OdataTypeMicrosoftAzureFrontDoorModelsFrontdoorRedirectConfiguration, + } + + // The way the API works is if you don't include the attribute in the structure + // it is treated as Preserve instead of Replace... + if customPath != "" { + redirectConfiguration.CustomPath = utils.String(customPath) + } + if customFragment != "" { + redirectConfiguration.CustomFragment = utils.String(customFragment) + } + if customQueryString != "" { + redirectConfiguration.CustomQueryString = utils.String(customQueryString) } return redirectConfiguration @@ -1435,4 +1445,4 @@ func makeCustomHttpsConfiguration(customHttpsConfiguration map[string]interface{ } return customHTTPSConfigurationUpdate -} \ No newline at end of file +} diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 793ca6eec86f..608ba2e0ef58 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -28,11 +28,10 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMFrontDoorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), - resource.TestCheckResourceAttr(resourceName, "enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "load_balancer_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "false"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendBing-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", "www.bing.com"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), @@ -45,17 +44,17 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_provisioning_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "false"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccBackendBing-%d", ri)), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), ), }, @@ -85,7 +84,6 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMFrontDoorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), resource.TestCheckResourceAttr(resourceName, "enabled", "true"), resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), @@ -164,62 +162,6 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { }) } -func TestAccAzureRMFrontDoor_keyVault(t *testing.T) { - resourceName := "azurerm_frontdoor.test" - ri := tf.AccRandTimeInt() - rs := strings.ToLower(acctest.RandString(5)) - config := testAccAzureRMFrontDoor_basic(ri, rs, testLocation()) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMFunctionAppDestroy, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMFrontDoorExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), - resource.TestCheckResourceAttr(resourceName, "enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), - resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] @@ -275,60 +217,38 @@ resource "azurerm_resource_group" "test" { location = "%[3]s" } -resource "azurerm_storage_account" "test" { - name = "tafdsa%[2]s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - account_tier = "Standard" - account_replication_type = "LRS" -} - resource "azurerm_frontdoor" "test" { - name = "testAccFrontDoor-%[1]d" - friendly_name = "tafd" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - enabled = true + name = "testAccFrontDoor-%[1]d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + enforce_backend_pools_certificate_name_check = false routing_rule { - name = "testAccRoutingRulerule1-%[1]d" - enabled = true - accepted_protocols = ["Http", "Https"] - patterns_to_match = ["/*"] - frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] + name = "testAccRoutingRulerule1-%[1]d" + accepted_protocols = ["Http", "Https"] + patterns_to_match = ["/*"] + frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] forwarding_configuration { forwarding_protocol = "MatchRequest" - cache_use_dynamic_compression = true - backend_pool_name = "testAccBackendPool1-%[1]d" + backend_pool_name = "testAccBackendBing-%[1]d" } } - enforce_backend_pools_certificate_name_check = true - backend_pool_load_balancing { name = "testAccLoadBalancingSettings1-%[1]d" - sample_size = 4 - successful_samples_required = 2 - additional_latency_milliseconds = 0 } backend_pool_health_probe { name = "testAccHealthProbeSetting1-%[1]d" - path = "/" - protocol = "Https" - interval_in_seconds = 30 } backend_pool { - name = "testAccBackendPool1-%[1]d" + name = "testAccBackendBing-%[1]d" backend { - enabled = true - host_header = "${azurerm_storage_account.test.primary_blob_host}" - address = "${azurerm_storage_account.test.primary_blob_host}" - http_port = 80 - https_port = 443 - weight = 50 - priority = 1 + host_header = "www.bing.com" + address = "www.bing.com" + http_port = 80 + https_port = 443 } load_balancing_name = "testAccLoadBalancingSettings1-%[1]d" @@ -336,13 +256,9 @@ resource "azurerm_frontdoor" "test" { } frontend_endpoint { - name = "testAccFrontendEndpoint1-%[1]d" - host_name = "testAccFrontDoor-%[1]d.azurefd.net" - session_affinity_enabled = true - session_affinity_ttl_seconds = 0 - custom_https_configuration { - certificate_source = "FrontDoor" - } + name = "testAccFrontendEndpoint1-%[1]d" + host_name = "testAccFrontDoor-%[1]d.azurefd.net" + custom_https_provisioning_enabled = false } } `, rInt, rString, location) @@ -355,64 +271,47 @@ resource "azurerm_resource_group" "test" { location = "%[3]s" } -resource "azurerm_storage_account" "test" { - name = "tafdsa%[2]s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - account_tier = "Standard" - account_replication_type = "LRS" -} - -resource "azurerm_storage_account" "test2" { - name = "tafdsatwo%[2]s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - account_tier = "Standard" - account_replication_type = "LRS" -} - resource "azurerm_frontdoor" "test" { - name = "testAccFrontDoor-%[1]d" - friendly_name = "tafd" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - enabled = true + name = "testAccFrontDoor-%[1]d" + friendly_name = "tafd" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + load_balancer_enabled = true + enforce_backend_pools_certificate_name_check = true routing_rule { - name = "testAccRoutingRulerule1-%[1]d" - enabled = true - accepted_protocols = ["Http", "Https"] - patterns_to_match = ["/*"] - frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] + name = "testAccRoutingRulerule1-%[1]d" + enabled = true + accepted_protocols = ["Http", "Https"] + patterns_to_match = ["/*"] + frontend_endpoints = ["testAccFrontendBing-%[1]d", "testAccBackendGoogle-%[1]d"] forwarding_configuration { - forwarding_protocol = "MatchRequest" + forwarding_protocol = "MatchRequest" cache_use_dynamic_compression = true - backend_pool_name = "testAccBackendPool1-%[1]d" + backend_pool_name = "testAccBackendPool1-%[1]d" } } - enforce_backend_pools_certificate_name_check = true - backend_pool_load_balancing { - name = "testAccLoadBalancingSettings1-%[1]d" - sample_size = 4 - successful_samples_required = 2 + name = "testAccLoadBalancingSettings1-%[1]d" + sample_size = 4 + successful_samples_required = 2 additional_latency_milliseconds = 0 } backend_pool_health_probe { - name = "testAccHealthProbeSetting1-%[1]d" - path = "/" - protocol = "Https" - interval_in_seconds = 30 + name = "testAccHealthProbeSetting1-%[1]d" + path = "/" + protocol = "Https" + interval_in_seconds = 120 } backend_pool { - name = "testAccBackendPool1-%[1]d" + name = "testAccBackendBing-%[1]d" backend { enabled = true - host_header = "${azurerm_storage_account.test.primary_blob_host}" - address = "${azurerm_storage_account.test.primary_blob_host}" + host_header = "www.bing.com" + address = "www.bing.com" http_port = 80 https_port = 443 weight = 50 @@ -424,11 +323,11 @@ resource "azurerm_frontdoor" "test" { } backend_pool { - name = "testAccBackendPool2-%[1]d" + name = "testAccBackendGoogle-%[1]d" backend { enabled = true - host_header = "${azurerm_storage_account.test2.primary_blob_host}" - address = "${azurerm_storage_account.test2.primary_blob_host}" + host_header = "www.google.com" + address = "www.google.com" http_port = 80 https_port = 443 weight = 50 @@ -440,144 +339,12 @@ resource "azurerm_frontdoor" "test" { } frontend_endpoint { - name = "testAccFrontendEndpoint1-%[1]d" - host_name = "testAccFrontDoor-%[1]d.azurefd.net" - session_affinity_enabled = true - session_affinity_ttl_seconds = 0 - custom_https_configuration { - certificate_source = "FrontDoor" - } + name = "testAccFrontendBing-%[1]d" + host_name = "testAccFrontDoor-%[1]d.azurefd.net" + session_affinity_enabled = true + session_affinity_ttl_seconds = 0 + enforce_backend_pools_certificate_name_check = true } } `, rInt, rString, location) } - -func testAccAzureRMFrontDoor_keyVault(rInt int, rString string, location string) string { - return fmt.Sprintf(` -data "azurerm_client_config" "current" {} - -resource "random_id" "server" { - keepers = { - azi_id = 1 - } - - byte_length = 8 -} - -resource "azurerm_resource_group" "test" { - name = "testAccRG-%[1]d" - location = "%[3]s" -} - -resource "azurerm_cdn_profile" "test" { - name = "testCdnProfile" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard_Verizon" -} - -resource "azurerm_cdn_endpoint" "test" { - name = "${random_id.server.hex}" - profile_name = "${azurerm_cdn_profile.test.name}" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - - origin { - name = "testCdnOrigin" - host_name = "www.fdcustomhost.com" - } -} - -resource "azurerm_key_vault" "test" { - name = "tfex-key-vault" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - enabled_for_disk_encryption = false - tenant_id = "${data.azurerm_client_config.current.tenant_id}" - sku_name = "standard" - } -} - -resource "azurerm_key_vault_key" "test" { - name = "tfex-key" - key_vault_id = "${azurerm_key_vault.test.id}" - key_type = "RSA" - key_size = 2048 - key_opts = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"] -} - -resource "azurerm_storage_account" "test" { - name = "tafdsa%[2]s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - account_tier = "Standard" - account_replication_type = "LRS" -} - -resource "azurerm_frontdoor" "test" { - name = "testAccFrontDoor-%[1]d" - friendly_name = "tafd" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - enabled = true - - routing_rule { - name = "testAccRoutingRulerule1-%[1]d" - enabled = true - accepted_protocols = ["Http", "Https"] - patterns_to_match = ["/*"] - frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] - forwarding_configuration { - forwarding_protocol = "MatchRequest" - cache_use_dynamic_compression = true - backend_pool_name = "testAccBackendPool1-%[1]d" - } - } - - enforce_backend_pools_certificate_name_check = true - - backend_pool_load_balancing { - name = "testAccLoadBalancingSettings1-%[1]d" - sample_size = 4 - successful_samples_required = 2 - additional_latency_milliseconds = 0 - } - - backend_pool_health_probe { - name = "testAccHealthProbeSetting1-%[1]d" - path = "/" - protocol = "Https" - interval_in_seconds = 30 - } - - backend_pool { - name = "testAccBackendPool1-%[1]d" - backend { - enabled = true - host_header = "${azurerm_storage_account.test.primary_blob_host}" - address = "${azurerm_storage_account.test.primary_blob_host}" - http_port = 80 - https_port = 443 - weight = 50 - priority = 1 - } - - load_balancing_name = "testAccLoadBalancingSettings1-%[1]d" - health_probe_name = "testAccHealthProbeSetting1-%[1]d" - } - - frontend_endpoint { - name = "testAccFrontendEndpoint1-%[1]d" - host_name = "testAccFrontDoor-%[1]d.azurefd.net" - session_affinity_enabled = true - session_affinity_ttl_seconds = 0 - custom_https_configuration { - certificate_source = "AzureKeyVault" - azure_key_vault_certificate_vault_id = "${azurerm_key_vault_key.test.id}" - azure_key_vault_certificate_secret_name = "" - azure_key_vault_certificate_secret_version = "" - } - } -} -`, rInt, rString, location) -} \ No newline at end of file From e35c1931670dfc25896468df5e5e9457b50572d0 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 13 Aug 2019 19:52:43 -0700 Subject: [PATCH 29/74] [WIP] Update test case --- azurerm/resource_arm_front_door.go | 18 ++++--- azurerm/resource_arm_front_door_test.go | 68 +++---------------------- website/docs/r/front_door.html.markdown | 51 ++++++++++++++++++- 3 files changed, 68 insertions(+), 69 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 1c52319220d0..1bc65c0c2e8d 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -43,6 +43,11 @@ func resourceArmFrontDoor() *schema.Resource { Default: true, }, + "enforce_backend_pools_certificate_name_check": { + Type: schema.TypeBool, + Required: true, + }, + "location": azure.SchemaLocation(), "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), @@ -184,10 +189,7 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, - "enforce_backend_pools_certificate_name_check": { - Type: schema.TypeBool, - Required: true, - }, + "backend_pool_load_balancing": { Type: schema.TypeList, MaxItems: 5000, @@ -221,6 +223,7 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, + "backend_pool_health_probe": { Type: schema.TypeList, MaxItems: 5000, @@ -258,6 +261,7 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, + "backend_pool": { Type: schema.TypeList, MaxItems: 50, @@ -328,6 +332,7 @@ func resourceArmFrontDoor() *schema.Resource { }, }, }, + "frontend_endpoint": { Type: schema.TypeList, MaxItems: 100, @@ -1164,10 +1169,10 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re resp, err := client.Get(ctx, resourceGroup, frontDoorName, *name) if err != nil { - return make([]interface{}, 0), fmt.Errorf("Error retrieving Front Door Frontend Endpoint Custom HTTPS Configuration %q (Resource Group %q): %+v", name, resourceGroup, err) + return make([]interface{}, 0), fmt.Errorf("Error retrieving Front Door Frontend Endpoint Custom HTTPS Configuration %q (Resource Group %q): %+v", *name, resourceGroup, err) } if resp.ID == nil { - return make([]interface{}, 0), fmt.Errorf("Cannot read Front Door Frontend Endpoint Custom HTTPS Configuration %q (Resource Group %q) ID", name, resourceGroup) + return make([]interface{}, 0), fmt.Errorf("Cannot read Front Door Frontend Endpoint Custom HTTPS Configuration %q (Resource Group %q) ID", *name, resourceGroup) } result["id"] = resp.ID @@ -1191,7 +1196,6 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re if properties.CustomHTTPSConfiguration != nil { customHTTPSConfiguration := properties.CustomHTTPSConfiguration - log.Printf("\n**********************************************************\n%+v\n**********************************************************\n", customHTTPSConfiguration) if customHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 608ba2e0ef58..a960029487be 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -39,7 +39,7 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Http"), resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), @@ -54,7 +54,7 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "false"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccBackendBing-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), ), }, @@ -83,35 +83,6 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMFrontDoorExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), - resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), ), }, { @@ -120,42 +91,19 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { testCheckAzureRMFrontDoorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), - resource.TestCheckResourceAttr(resourceName, "enabled", "true"), resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendPool1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", fmt.Sprintf("tafdsa%s.blob.core.windows.net", rs)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), - resource.TestCheckResourceAttr(resourceName, "backend_pool.1.name", fmt.Sprintf("testAccBackendPool2-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.address", fmt.Sprintf("tafdsatwo%s.blob.core.windows.net", rs)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.name", fmt.Sprintf("testAccBackendGoogle-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.address", "www.google.com"), resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.1.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool.1.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.http_port", "80"), resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.priority", "1"), resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.weight", "50"), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), - resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_configuration.0.certificate_source", "FrontDoor"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), ), }, }, @@ -224,7 +172,7 @@ resource "azurerm_frontdoor" "test" { enforce_backend_pools_certificate_name_check = false routing_rule { - name = "testAccRoutingRulerule1-%[1]d" + name = "testAccRoutingRule1-%[1]d" accepted_protocols = ["Http", "Https"] patterns_to_match = ["/*"] frontend_endpoints = ["testAccFrontendEndpoint1-%[1]d"] @@ -280,7 +228,7 @@ resource "azurerm_frontdoor" "test" { enforce_backend_pools_certificate_name_check = true routing_rule { - name = "testAccRoutingRulerule1-%[1]d" + name = "testAccRoutingRule1-%[1]d" enabled = true accepted_protocols = ["Http", "Https"] patterns_to_match = ["/*"] @@ -288,7 +236,7 @@ resource "azurerm_frontdoor" "test" { forwarding_configuration { forwarding_protocol = "MatchRequest" cache_use_dynamic_compression = true - backend_pool_name = "testAccBackendPool1-%[1]d" + backend_pool_name = "testAccBackendBing-%[1]d" } } @@ -343,7 +291,7 @@ resource "azurerm_frontdoor" "test" { host_name = "testAccFrontDoor-%[1]d.azurefd.net" session_affinity_enabled = true session_affinity_ttl_seconds = 0 - enforce_backend_pools_certificate_name_check = true + custom_https_provisioning_enabled = false } } `, rInt, rString, location) diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 9749625097c3..ee1506a6918c 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -3,12 +3,59 @@ layout: "azurerm" page_title: "Azure Resource Manager: azurerm_front_door" sidebar_current: "docs-azurerm-resource-front-door" description: |- - Manage Azure FrontDoor instance. + Manage an Azure FrontDoor instance. --- # azurerm_front_door -Manage Azure FrontDoor instance. +Manage an Azure FrontDoor instance. + +``` +resource "azurerm_frontdoor" "example" { + name = "example-FrontDoor" + location = "${azurerm_resource_group.example.location}" + resource_group_name = "${azurerm_resource_group.example.name}" + enforce_backend_pools_certificate_name_check = false + + routing_rule { + name = "exampleRoutingRule1" + accepted_protocols = ["Http", "Https"] + patterns_to_match = ["/*"] + frontend_endpoints = ["exampleFrontendEndpoint1"] + forwarding_configuration { + forwarding_protocol = "MatchRequest" + backend_pool_name = "exampleBackendBing" + } + } + + backend_pool_load_balancing { + name = "exampleLoadBalancingSettings1" + } + + backend_pool_health_probe { + name = "exampleHealthProbeSetting1" + } + + backend_pool { + name = "exampleBackendBing" + backend { + host_header = "www.bing.com" + address = "www.bing.com" + http_port = 80 + https_port = 443 + } + + load_balancing_name = "exampleLoadBalancingSettings1" + health_probe_name = "exampleHealthProbeSetting1" + } + + frontend_endpoint { + name = "exampleFrontendEndpoint1" + host_name = "example-FrontDoor.azurefd.net" + custom_https_provisioning_enabled = false + } +} +``` ## Argument Reference From 011ac40c281302b5923b809ca575636f0b805b02 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 14 Aug 2019 15:19:09 -0700 Subject: [PATCH 30/74] Updated documentation and exposed cname --- azurerm/resource_arm_front_door.go | 5 + azurerm/resource_arm_front_door_test.go | 4 +- website/docs/r/front_door.html.markdown | 163 +++++++++--------------- 3 files changed, 70 insertions(+), 102 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 1bc65c0c2e8d..144681fccf90 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -32,6 +32,11 @@ func resourceArmFrontDoor() *schema.Resource { ValidateFunc: azure.ValidateFrontDoorName, }, + "cname": { + Type: schema.TypeString, + Computed: true, + }, + "friendly_name": { Type: schema.TypeString, Optional: true, diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index a960029487be..d219a4af7f5c 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -47,7 +47,7 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_provisioning_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRulerule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRule1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), @@ -232,7 +232,7 @@ resource "azurerm_frontdoor" "test" { enabled = true accepted_protocols = ["Http", "Https"] patterns_to_match = ["/*"] - frontend_endpoints = ["testAccFrontendBing-%[1]d", "testAccBackendGoogle-%[1]d"] + frontend_endpoints = ["testAccFrontendBing-%[1]d"] forwarding_configuration { forwarding_protocol = "MatchRequest" cache_use_dynamic_compression = true diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index ee1506a6918c..52a341d42767 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -3,14 +3,16 @@ layout: "azurerm" page_title: "Azure Resource Manager: azurerm_front_door" sidebar_current: "docs-azurerm-resource-front-door" description: |- - Manage an Azure FrontDoor instance. + Manage an Azure Front Door instance. --- # azurerm_front_door -Manage an Azure FrontDoor instance. +Manage an Azure Front Door instance. -``` +## Example Usage + +```hcl resource "azurerm_frontdoor" "example" { name = "example-FrontDoor" location = "${azurerm_resource_group.example.location}" @@ -67,182 +69,145 @@ The following arguments are supported: * `location` - (Required) Resource location. Changing this forces a new resource to be created. -* `backend_pool` - (Required) One `backend_pool` block defined below. - -* `backend_pools_settings` - (Required) One `backend_pools_setting` block defined below. - -* `enabled` - (Optional) Operational status of the Front Door load balancer. Permitted values are 'true' or 'false' Defaults to `true`. +* `backend_pool` - (Required) A `backend_pool` block as defined below. -* `friendly_name` - (Optional) A friendly name for the frontDoor +* `backend_pool_health_probe` - (Required) A `backend_pool_health_probe` block as defined below. -* `frontend_endpoints` - (Required) One `frontend_endpoint` block defined below. +* `backend_pool_load_balancing` - (Required) A `backend_pool_load_balancing` block as defined below. -* `health_probe_settings` - (Required) One `health_probe_setting` block defined below. +* `load_balancer_enabled` - (Optional) Operational status of the Front Door load balancer. Permitted values are `true` or `false` Defaults to `true`. -* `load_balancing_settings` - (Required) One `load_balancing_setting` block defined below. +* `friendly_name` - (Optional) A friendly name for the Front Door service. -* `resource_state` - (Optional) Resource status of the Front Door. Defaults to `Creating`. +* `frontend_endpoint` - (Required) A `frontend_endpoint` block as defined below. -* `routing_rules` - (Required) One `routing_rule` block defined below. +* `routing_rule` - (Required) A `routing_rule` block as defined below. -* `tags` - (Optional) Resource tags. Changing this forces a new resource to be created. +* `tags` - (Optional) Resource tags. --- The `backend_pool` block supports the following: -* `id` - (Optional) Resource ID. +* `id` - The Resource ID of the Azure Front Door Backend Pool. -* `backends` - (Optional) One `backend` block defined below. +* `name` - (Required) The name of the `Backend Pool`. -* `load_balancing_settings` - (Optional) One `load_balancing_setting` block defined below. +* `backend` - (Required) A `backend` block as defined below. -* `health_probe_settings` - (Optional) One `health_probe_setting` block defined below. - -* `resource_state` - (Optional) Resource status. Defaults to `Creating`. - -* `name` - (Optional) Resource name. +* `load_balancing_name` - (Required) The name of the `backend_pool_load_balancing` to use for the `Backend Pool`. +* `health_probe_name` - (Required) The name of the `backend_pool_health_probe` to use for the `Backend Pool`. --- The `backend` block supports the following: -* `address` - (Optional) Location of the backend (IP address or FQDN) - -* `http_port` - (Optional) The HTTP TCP port number. Must be between 1 and 65535. - -* `https_port` - (Optional) The HTTPS TCP port number. Must be between 1 and 65535. +* `id` - The Resource ID of the Azure Front Door Backend. -* `enabled_state` - (Optional) Whether to enable use of this backend. Permitted values are 'Enabled' or 'Disabled' Defaults to `Enabled`. +* `address` - (Required) Location of the backend (IP address or FQDN) -* `priority` - (Optional) Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy. +* `host_header` - (Required) The value to use as the host header sent to the backend. -* `weight` - (Optional) Weight of this endpoint for load balancing purposes. +* `http_port` - (Required) The HTTP TCP port number. Possible values are between `1` - `65535`. -* `backend_host_header` - (Optional) The value to use as the host header sent to the backend. If blank or unspecified, this defaults to the incoming host. +* `https_port` - (Required) The HTTPS TCP port number. Possible values are between `1` - `65535`. ---- - -The `load_balancing_setting` block supports the following: - -* `id` - (Optional) Resource ID. - ---- - -The `health_probe_setting` block supports the following: +* `priority` - (Optional) Priority to use for load balancing. Higher priorities will not be used for load balancing if any lower priority backend is healthy. Defaults to `1`. -* `id` - (Optional) Resource ID. - ---- - -The `backend_pools_setting` block supports the following: - -* `enforce_certificate_name_check` - (Optional) Whether to enforce certificate name check on HTTPS requests to all backend pools. No effect on non-HTTPS requests. Defaults to `Enabled`. +* `weight` - (Optional) Weight of this endpoint for load balancing purposes. Defaults to `50`. --- The `frontend_endpoint` block supports the following: -* `id` - (Optional) Resource ID. - -* `host_name` - (Optional) The host name of the frontendEndpoint. Must be a domain name. - -* `session_affinity_enabled_state` - (Optional) Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled' Defaults to `Enabled`. +* `id` - The Resource ID of the Azure Front Door Frontend Endpoint. -* `session_affinity_ttl_seconds` - (Optional) UNUSED. This field will be ignored. The TTL to use in seconds for session affinity, if applicable. +* `name` - (Required) The name of the Frontend Endpoint. -* `web_application_firewall_policy_link` - (Optional) One `web_application_firewall_policy_link` block defined below. +* `host_name` - (Required) The host name of the Frontend Endpoint. Must be a domain name. -* `resource_state` - (Optional) Resource status. Defaults to `Creating`. - -* `name` - (Optional) Resource name. - - ---- +* `session_affinity_enabled` - (Optional) Whether to allow session affinity on this host. Valid options are `true` or `false` Defaults to `false`. -The `web_application_firewall_policy_link` block supports the following: +* `session_affinity_ttl_seconds` - (Optional) The TTL to use in seconds for session affinity, if applicable. Defaults to `0`. -* `id` - (Optional) Resource ID. +[//]: * "* `web_application_firewall_policy_link_id` - (Optional) The `id` of the `web_application_firewall_policy_link` to use for this Frontend Endpoint." --- -The `health_probe_setting` block supports the following: +The `backend_pool_health_probe` block supports the following: -* `id` - (Optional) Resource ID. +* `id` - The Resource ID of the Azure Front Door Backend Health Probe. -* `path` - (Optional) The path to use for the health probe. Default is / +* `name` - (Required) The name of the Azure Front Door Backend Health Probe. -* `protocol` - (Optional) Protocol scheme to use for this probe Defaults to `Http`. +* `path` - (Optional) The path to use for the Backend Health Probe. Default is `/`. -* `interval_in_seconds` - (Optional) The number of seconds between health probes. +* `protocol` - (Optional) Protocol scheme to use for the Backend Health Probe. Defaults to `Http`. -* `resource_state` - (Optional) Resource status. Defaults to `Creating`. - -* `name` - (Optional) Resource name. +* `interval_in_seconds` - (Optional) The number of seconds between health probes. Defaults to `120`. --- -The `load_balancing_setting` block supports the following: - -* `id` - (Optional) Resource ID. +The `backend_pool_load_balancing` block supports the following: -* `sample_size` - (Optional) The number of samples to consider for load balancing decisions +* `id` - The Resource ID of the Azure Front Door Backend Load Balancer. -* `successful_samples_required` - (Optional) The number of samples within the sample period that must succeed +* `name` - (Required) The name of the Azure Front Door Backend Load Balancer. -* `additional_latency_milliseconds` - (Optional) The additional latency in milliseconds for probes to fall into the lowest latency bucket +* `sample_size` - (Optional) The number of samples to consider for load balancing decisions. Defaults to `4`. -* `resource_state` - (Optional) Resource status. Defaults to `Creating`. +* `successful_samples_required` - (Optional) The number of samples within the sample period that must succeed. Defaults to `2`. -* `name` - (Optional) Resource name. +* `additional_latency_milliseconds` - (Optional) The additional latency in milliseconds for probes to fall into the lowest latency bucket. Defaults to `0`. --- The `routing_rule` block supports the following: -* `id` - (Optional) Resource ID. - -* `frontend_endpoints` - (Optional) One `frontend_endpoint` block defined below. - -* `accepted_protocols` - (Optional) Protocol schemes to match for this rule Defaults to `Http`. +* `id` - The Resource ID of the Azure Front Door Backend Routing Rule. -* `patterns_to_match` - (Optional) The route patterns of the rule. +* `name` - (Required) The name of the Front Door Backend Routing Rule. -* `enabled_state` - (Optional) Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' Defaults to `Enabled`. +* `frontend_endpoints` - (Required) A `frontend_endpoint` block as defined below. -* `resource_state` - (Optional) Resource status. Defaults to `Creating`. +* `accepted_protocols` - (Optional) Protocol schemes to match for the Backend Routing Rule. Defaults to `Http`. -* `name` - (Optional) Resource name. +* `patterns_to_match` - (Optional) The route patterns for the Backend Routing Rule. Defaults to `/*`. +* `enabled` - (Optional) `Enable` or `Disable` use of this Backend Routing Rule. Permitted values are `true` or `false`. Defaults to `true`. --- The `frontend_endpoint` block supports the following: -* `name` - (Required) Name of the Frontend endpoint. +* `id` - The Resource ID of the Azure Front Door Frontend Endpoint. -* `host_name` - (Required) Name of the Frontend endpoint. +* `name` - (Required) The Name of the Azure Front Door Frontend Endpoint. -* `session_affinity_enabled` - (Required) Name of the Frontend endpoint. +* `host_name` - (Required) The host name of the Frontend Endpoint. Must be a domain name. -* `session_affinity_ttl_seconds` - (Required) Name of the Frontend endpoint. +* `session_affinity_enabled` - (Optional) Allow session affinity on the Frontend Endpoint. Valid options are `true` or `false`. Defaults to `false`. -* `enable_custom_https_provisioning` - (Required) Name of the Frontend endpoint. +* `session_affinity_ttl_seconds` - (Optional) The TTL to use, in seconds, for session affinity, if applicable. Defaults to `0`. + +* `enable_custom_https_provisioning` - (Required) Name of the Frontend Endpoint. --- The `custom_https_configuration` block supports the following: -* `certificate_source` - (Optional) Certificate source to encrypted HTTPS traffic with. Permitted values are `FrontDoor` or `AzureKeyVault` Defaults to `FrontDoor`. +* `certificate_source` - (Optional) Certificate source to encrypted `HTTPS` traffic with. Allowed values are `FrontDoor` or `AzureKeyVault`. Defaults to `FrontDoor`. + +The following attributes are only valid if `certificate_source` is set to `AzureKeyVault`: -* `azure_key_vault_certificate_vault_id` - (Required) Name of the Frontend endpoint. (Only if `certificate_source` is set to `AzureKeyVault`) +* `azure_key_vault_certificate_vault_id` - (Required) The `id` of the Key Vault containing the SSL certificate. -* `azure_key_vault_certificate_secret_name` - (Required) Name of the Frontend endpoint. (Only if `certificate_source` is set to `AzureKeyVault`) +* `azure_key_vault_certificate_secret_name` - (Required) The name of the Key Vault secret representing the full certificate PFX. -* `azure_key_vault_certificate_secret_version` - (Required) Name of the Frontend endpoint. (Only if `certificate_source` is set to `AzureKeyVault`) +* `azure_key_vault_certificate_secret_version` - (Required) The version of the Key Vault secret representing the full certificate PFX. -~> **Note:** In order to enable the use of your own custom HTTPS certificate you must grant Azure Front Door Service access to your key vault. For instuctions on how to configure your Key Vault correctly please refer to the product [documentation](https://docs.microsoft.com/en-us/azure/frontdoor/front-door-custom-domain-https#option-2-use-your-own-certificate). +~> **Note:** In order to enable the use of your own custom `HTTPS certificate` you must grant `Azure Front Door Service` access to your key vault. For instuctions on how to configure your `Key Vault` correctly please refer to the [product documentation](https://docs.microsoft.com/en-us/azure/frontdoor/front-door-custom-domain-https#option-2-use-your-own-certificate). --- @@ -258,8 +223,6 @@ The following attributes are exported: * `id` - Resource ID. -* `type` - Resource type. - ## Import Front Doors can be imported using the `resource id`, e.g. From df4d52375ed1634b3918bccda543720800e3c4fb Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 14 Aug 2019 15:57:42 -0700 Subject: [PATCH 31/74] fixed flatten for Cert Source AzureKeyVault --- azurerm/resource_arm_front_door.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 144681fccf90..5440522d093d 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -1203,6 +1203,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re customHTTPSConfiguration := properties.CustomHTTPSConfiguration if customHTTPSConfiguration.CertificateSource == frontdoor.CertificateSourceAzureKeyVault { if kvcsp := customHTTPSConfiguration.KeyVaultCertificateSourceParameters; kvcsp != nil { + chc["certificate_source"] = string(frontdoor.CertificateSourceAzureKeyVault) chc["azure_key_vault_certificate_vault_id"] = *kvcsp.Vault.ID chc["azure_key_vault_certificate_secret_name"] = *kvcsp.SecretName chc["azure_key_vault_certificate_secret_version"] = *kvcsp.SecretVersion From 5a004ae65d7a3ca41e4e533f964dd784476b37a1 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 15 Aug 2019 19:39:54 -0700 Subject: [PATCH 32/74] Update to latest --- azurerm/config.go | 5 +- azurerm/data_source_front_door.go | 5 +- azurerm/internal/services/frontdoor/client.go | 24 +++++ .../services/frontdoor/helper/helper.go | 85 +++++++++++++++++ .../services/frontdoor/validate/validate.go} | 93 ++----------------- azurerm/provider.go | 1 + azurerm/resource_arm_front_door.go | 48 +++++----- azurerm/resource_arm_front_door_test.go | 92 +++++++++--------- 8 files changed, 196 insertions(+), 157 deletions(-) create mode 100644 azurerm/internal/services/frontdoor/client.go create mode 100644 azurerm/internal/services/frontdoor/helper/helper.go rename azurerm/{helpers/azure/frontdoor.go => internal/services/frontdoor/validate/validate.go} (68%) diff --git a/azurerm/config.go b/azurerm/config.go index 485b488b01ec..f560adfcd8bb 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -37,6 +37,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/dns" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventhub" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/graph" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/hdinsight" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/iothub" @@ -110,6 +111,7 @@ type ArmClient struct { privateDns *privatedns.Client eventGrid *eventgrid.Client eventhub *eventhub.Client + frontdoor *frontdoor.Client graph *graph.Client hdinsight *hdinsight.Client iothub *iothub.Client @@ -247,6 +249,7 @@ func getArmClient(c *authentication.Config, skipProviderRegistration bool, partn client.dns = dns.BuildClient(o) client.eventGrid = eventgrid.BuildClient(o) client.eventhub = eventhub.BuildClient(o) + client.frontdoor = frontdoor.BuildClient(o) client.graph = graph.BuildClient(o) client.hdinsight = hdinsight.BuildClient(o) client.iothub = iothub.BuildClient(o) @@ -395,4 +398,4 @@ func (c *ArmClient) getBlobStorageClientForStorageAccount(ctx context.Context, r blobClient := storageClient.GetBlobService() return &blobClient, true, nil -} \ No newline at end of file +} diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go index 0a1b8d77af6b..d0de83499084 100644 --- a/azurerm/data_source_front_door.go +++ b/azurerm/data_source_front_door.go @@ -7,6 +7,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/hashicorp/terraform/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -19,7 +20,7 @@ func dataSourceArmFrontDoor() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateFrontDoorName, + ValidateFunc: validate.FrontDoorName, }, "load_balancer_enabled": { @@ -345,7 +346,7 @@ func dataSourceArmFrontDoor() *schema.Resource { } func dataSourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontDoorsClient + client := meta.(*ArmClient).frontdoor.FrontDoorsClient ctx := meta.(*ArmClient).StopContext id, err := parseAzureResourceID(d.Id()) diff --git a/azurerm/internal/services/frontdoor/client.go b/azurerm/internal/services/frontdoor/client.go new file mode 100644 index 000000000000..af7c6040c320 --- /dev/null +++ b/azurerm/internal/services/frontdoor/client.go @@ -0,0 +1,24 @@ +package frontdoor + +import ( + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/common" +) + +type Client struct { + FrontDoorsClient *frontdoor.FrontDoorsClient + FrontDoorsFrontendClient *frontdoor.FrontendEndpointsClient +} + +func BuildClient(o *common.ClientOptions) *Client { + frontDoorsClient := frontdoor.NewFrontDoorsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&frontDoorsClient.Client, o.ResourceManagerAuthorizer) + + frontDoorsFrontendClient := frontdoor.NewFrontendEndpointsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&frontDoorsFrontendClient.Client, o.ResourceManagerAuthorizer) + + return &Client{ + FrontDoorsClient: &frontDoorsClient, + FrontDoorsFrontendClient: &frontDoorsFrontendClient, + } +} diff --git a/azurerm/internal/services/frontdoor/helper/helper.go b/azurerm/internal/services/frontdoor/helper/helper.go new file mode 100644 index 000000000000..3c93e01623a9 --- /dev/null +++ b/azurerm/internal/services/frontdoor/helper/helper.go @@ -0,0 +1,85 @@ +package helper + +import ( + "fmt" + "strings" + + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" +) + +func DoesBackendPoolExists(backendPoolName string, backendPools []interface{}) error { + if backendPoolName == "" { + return fmt.Errorf(`"backend_pool_name" cannot be empty`) + } + + for _, bps := range backendPools { + backendPool := bps.(map[string]interface{}) + if backendPool["name"].(string) == backendPoolName { + return nil + } + } + + return fmt.Errorf(`unable to locate "backend_pool_name":%q in configuration file`, backendPoolName) +} + +func AzureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]interface{}, MatchAllKeys bool) bool { + certificateSecretName := customHttpsConfiguration["azure_key_vault_certificate_secret_name"] + certificateSecretVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"] + certificateVaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"] + + if MatchAllKeys { + if strings.TrimSpace(certificateSecretName.(string)) != "" && strings.TrimSpace(certificateSecretVersion.(string)) != "" && strings.TrimSpace(certificateVaultId.(string)) != "" { + return true + } + } else { + if strings.TrimSpace(certificateSecretName.(string)) != "" || strings.TrimSpace(certificateSecretVersion.(string)) != "" || strings.TrimSpace(certificateVaultId.(string)) != "" { + return true + } + } + + return false +} + +func IsFrontDoorFrontendEndpointConfigurable(currentState frontdoor.CustomHTTPSProvisioningState, customHttpsProvisioningEnabled bool, frontendEndpointName string, resourceGroup string) error { + action := "disable" + if customHttpsProvisioningEnabled { + action = "enable" + } + + switch currentState { + case frontdoor.CustomHTTPSProvisioningStateDisabling, frontdoor.CustomHTTPSProvisioningStateEnabling, frontdoor.CustomHTTPSProvisioningStateFailed: + return fmt.Errorf("Unable to %s the Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because the Frontend Endpoint is currently in the %q state", action, frontendEndpointName, resourceGroup, currentState) + default: + return nil + } +} + +func NormalizeCustomHTTPSProvisioningStateToBool(provisioningState frontdoor.CustomHTTPSProvisioningState) bool { + isEnabled := false + if provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled || provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabling { + isEnabled = true + } + + return isEnabled +} + +func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { + if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { + return "" + } + + return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName) +} + +func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { + _, ok := i.(frontdoor.ForwardingConfiguration) + if !ok { + _, ok := i.(frontdoor.RedirectConfiguration) + if !ok { + return "" + } + return "RedirectConfiguration" + } else { + return "ForwardingConfiguration" + } +} diff --git a/azurerm/helpers/azure/frontdoor.go b/azurerm/internal/services/frontdoor/validate/validate.go similarity index 68% rename from azurerm/helpers/azure/frontdoor.go rename to azurerm/internal/services/frontdoor/validate/validate.go index 7bda490e561c..c8ecd079acbc 100644 --- a/azurerm/helpers/azure/frontdoor.go +++ b/azurerm/internal/services/frontdoor/validate/validate.go @@ -1,16 +1,16 @@ -package azure +package validate import ( "fmt" - "strings" "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/hashicorp/terraform/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/helper" ) //Frontdoor name must begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens. -func ValidateFrontDoorName(i interface{}, k string) (_ []string, errors []error) { +func FrontDoorName(i interface{}, k string) (_ []string, errors []error) { if m, regexErrs := validate.RegExHelper(i, k, `(^[\da-zA-Z])([-\da-zA-Z]{3,61})([\da-zA-Z]$)`); !m { errors = append(regexErrs, fmt.Errorf(`%q must be between 5 and 63 characters in length and begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) } @@ -18,7 +18,7 @@ func ValidateFrontDoorName(i interface{}, k string) (_ []string, errors []error) return nil, errors } -func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, errors []error) { +func BackendPoolRoutingRuleName(i interface{}, k string) (_ []string, errors []error) { if m, regexErrs := validate.RegExHelper(i, k, `(^[\da-zA-Z])([-\da-zA-Z]{1,88})([\da-zA-Z]$)`); !m { errors = append(regexErrs, fmt.Errorf(`%q must be between 1 and 90 characters in length and begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) } @@ -26,7 +26,7 @@ func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, er return nil, errors } -func ValidateFrontdoor(d *schema.ResourceDiff) error { +func FrontdoorSettings(d *schema.ResourceDiff) error { routingRules := d.Get("routing_rule").([]interface{}) configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) backendPools := d.Get("backend_pool").([]interface{}) @@ -60,7 +60,7 @@ func ValidateFrontdoor(d *schema.ResourceDiff) error { // Check 2. routing rule is a forwarding_configuration type make sure the backend_pool_name exists in the configuration file if len(forwardConfig) > 0 { fc := forwardConfig[0].(map[string]interface{}) - if err := backendPoolExists(fc["backend_pool_name"].(string), backendPools); err != nil { + if err := helper.DoesBackendPoolExists(fc["backend_pool_name"].(string), backendPools); err != nil { return fmt.Errorf(`"routing_rule":%q is invalid. %+v`, routingRuleName, err) } } @@ -161,11 +161,11 @@ func ValidateFrontdoor(d *schema.ResourceDiff) error { customHttpsConfiguration := chc[0].(map[string]interface{}) certificateSource := customHttpsConfiguration["certificate_source"] if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { - if !azureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { + if !helper.AzureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must have values in the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) } } else { - if azureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { + if helper.AzureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must be removed from the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) } } @@ -177,80 +177,3 @@ func ValidateFrontdoor(d *schema.ResourceDiff) error { return nil } - -func backendPoolExists(backendPoolName string, backendPools []interface{}) error { - if backendPoolName == "" { - return fmt.Errorf(`"backend_pool_name" cannot be empty`) - } - - for _, bps := range backendPools { - backendPool := bps.(map[string]interface{}) - if backendPool["name"].(string) == backendPoolName { - return nil - } - } - - return fmt.Errorf(`unable to locate "backend_pool_name":%q in configuration file`, backendPoolName) -} - -func azureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]interface{}, MatchAllKeys bool) bool { - certificateSecretName := customHttpsConfiguration["azure_key_vault_certificate_secret_name"] - certificateSecretVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"] - certificateVaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"] - - if MatchAllKeys { - if strings.TrimSpace(certificateSecretName.(string)) != "" && strings.TrimSpace(certificateSecretVersion.(string)) != "" && strings.TrimSpace(certificateVaultId.(string)) != "" { - return true - } - } else { - if strings.TrimSpace(certificateSecretName.(string)) != "" || strings.TrimSpace(certificateSecretVersion.(string)) != "" || strings.TrimSpace(certificateVaultId.(string)) != "" { - return true - } - } - - return false -} - -func IsFrontDoorFrontendEndpointConfigurable(currentState frontdoor.CustomHTTPSProvisioningState, customHttpsProvisioningEnabled bool, frontendEndpointName string, resourceGroup string) error { - action := "disable" - if customHttpsProvisioningEnabled { - action = "enable" - } - - switch currentState { - case frontdoor.CustomHTTPSProvisioningStateDisabling, frontdoor.CustomHTTPSProvisioningStateEnabling, frontdoor.CustomHTTPSProvisioningStateFailed: - return fmt.Errorf("Unable to %s the Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because the Frontend Endpoint is currently in the %q state", action, frontendEndpointName, resourceGroup, currentState) - default: - return nil - } -} - -func NormalizeCustomHTTPSProvisioningStateToBool(provisioningState frontdoor.CustomHTTPSProvisioningState) bool { - isEnabled := false - if provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled || provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabling { - isEnabled = true - } - - return isEnabled -} - -func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { - if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { - return "" - } - - return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName) -} - -func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { - _, ok := i.(frontdoor.ForwardingConfiguration) - if !ok { - _, ok := i.(frontdoor.RedirectConfiguration) - if !ok { - return "" - } - return "RedirectConfiguration" - } else { - return "ForwardingConfiguration" - } -} diff --git a/azurerm/provider.go b/azurerm/provider.go index 14f25d56f651..d743de8a0478 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -234,6 +234,7 @@ func Provider() terraform.ResourceProvider { "azurerm_firewall_nat_rule_collection": resourceArmFirewallNatRuleCollection(), "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), "azurerm_firewall": resourceArmFirewall(), + "azurerm_frontdoor": resourceArmFrontDoor(), "azurerm_function_app": resourceArmFunctionApp(), "azurerm_hdinsight_hadoop_cluster": resourceArmHDInsightHadoopCluster(), "azurerm_hdinsight_hbase_cluster": resourceArmHDInsightHBaseCluster(), diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 5440522d093d..a5a1948868f7 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -10,6 +10,8 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/helper" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -29,7 +31,7 @@ func resourceArmFrontDoor() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateFrontDoorName, + ValidateFunc: validate.FrontDoorName, }, "cname": { @@ -70,7 +72,7 @@ func resourceArmFrontDoor() *schema.Resource { "name": { Type: schema.TypeString, Required: true, - ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + ValidateFunc: validate.BackendPoolRoutingRuleName, }, "enabled": { Type: schema.TypeBool, @@ -158,7 +160,7 @@ func resourceArmFrontDoor() *schema.Resource { "backend_pool_name": { Type: schema.TypeString, Required: true, - ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + ValidateFunc: validate.BackendPoolRoutingRuleName, }, "cache_use_dynamic_compression": { Type: schema.TypeBool, @@ -208,7 +210,7 @@ func resourceArmFrontDoor() *schema.Resource { "name": { Type: schema.TypeString, Required: true, - ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + ValidateFunc: validate.BackendPoolRoutingRuleName, }, "sample_size": { Type: schema.TypeInt, @@ -242,7 +244,7 @@ func resourceArmFrontDoor() *schema.Resource { "name": { Type: schema.TypeString, Required: true, - ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + ValidateFunc: validate.BackendPoolRoutingRuleName, }, "path": { Type: schema.TypeString, @@ -324,7 +326,7 @@ func resourceArmFrontDoor() *schema.Resource { "name": { Type: schema.TypeString, Required: true, - ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + ValidateFunc: validate.BackendPoolRoutingRuleName, }, "health_probe_name": { Type: schema.TypeString, @@ -351,7 +353,7 @@ func resourceArmFrontDoor() *schema.Resource { "name": { Type: schema.TypeString, Required: true, - ValidateFunc: azure.ValidateBackendPoolRoutingRuleName, + ValidateFunc: validate.BackendPoolRoutingRuleName, }, "host_name": { Type: schema.TypeString, @@ -419,7 +421,7 @@ func resourceArmFrontDoor() *schema.Resource { }, CustomizeDiff: func(d *schema.ResourceDiff, v interface{}) error { - if err := azure.ValidateFrontdoor(d); err != nil { + if err := validate.FrontdoorSettings(d); err != nil { return fmt.Errorf("Error creating Front Door %q (Resource Group %q): %+v", d.Get("name").(string), d.Get("resource_group_name").(string), err) } @@ -429,7 +431,7 @@ func resourceArmFrontDoor() *schema.Resource { } func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontDoorsClient + client := meta.(*ArmClient).frontdoor.FrontDoorsClient ctx := meta.(*ArmClient).StopContext name := d.Get("name").(string) @@ -499,7 +501,7 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) frontendEndpointName := frontendEndpoint["name"].(string) // Get current state of endpoint from Azure - client := meta.(*ArmClient).frontDoorsFrontendClient + client := meta.(*ArmClient).frontdoor.FrontDoorsFrontendClient ctx := meta.(*ArmClient).StopContext resp, err := client.Get(ctx, resourceGroup, name, frontendEndpointName) @@ -514,8 +516,8 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) if provisioningState := properties.CustomHTTPSProvisioningState; provisioningState != "" { // Check to see if we are going to change the CustomHTTPSProvisioningState, if so check to // see if its current state is configurable, if not return an error... - if customHttpsProvisioningEnabled != azure.NormalizeCustomHTTPSProvisioningStateToBool(provisioningState) { - if err := azure.IsFrontDoorFrontendEndpointConfigurable(provisioningState, customHttpsProvisioningEnabled, frontendEndpointName, resourceGroup); err != nil { + if customHttpsProvisioningEnabled != helper.NormalizeCustomHTTPSProvisioningStateToBool(provisioningState) { + if err := helper.IsFrontDoorFrontendEndpointConfigurable(provisioningState, customHttpsProvisioningEnabled, frontendEndpointName, resourceGroup); err != nil { return err } } @@ -545,7 +547,7 @@ func resourceArmFrontDoorCreateUpdate(d *schema.ResourceData, meta interface{}) } func resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(enableCustomHttpsProvisioning bool, frontDoorName string, frontendEndpointName string, resourceGroup string, customHTTPSConfiguration frontdoor.CustomHTTPSConfiguration, meta interface{}) error { - client := meta.(*ArmClient).frontDoorsFrontendClient + client := meta.(*ArmClient).frontdoor.FrontDoorsFrontendClient ctx := meta.(*ArmClient).StopContext if enableCustomHttpsProvisioning { @@ -572,7 +574,7 @@ func resourceArmFrontDoorFrontendEndpointEnableHttpsProvisioning(enableCustomHtt } func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontDoorsClient + client := meta.(*ArmClient).frontdoor.FrontDoorsClient ctx := meta.(*ArmClient).StopContext id, err := parseAzureResourceID(d.Id()) @@ -640,7 +642,7 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } func resourceArmFrontDoorDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontDoorsClient + client := meta.(*ArmClient).frontdoor.FrontDoorsClient ctx := meta.(*ArmClient).StopContext id, err := parseAzureResourceID(d.Id()) @@ -684,7 +686,7 @@ func expandArmFrontDoorBackendPools(input []interface{}, subscriptionId string, backends := backendPool["backend"].([]interface{}) result := frontdoor.BackendPool{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "BackendPools", backendPoolName)), + ID: utils.String(helper.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "BackendPools", backendPoolName)), Name: utils.String(backendPoolName), BackendPoolProperties: &frontdoor.BackendPoolProperties{ // ResourceState @@ -771,7 +773,7 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri sessionAffinityTtlSeconds := int32(frontendEndpoint["session_affinity_ttl_seconds"].(int)) customHttpsConfiguration := frontendEndpoint["custom_https_configuration"].([]interface{}) name := frontendEndpoint["name"].(string) - id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "FrontendEndpoints", name)) + id := utils.String(helper.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "FrontendEndpoints", name)) sessionAffinityEnabled := frontdoor.SessionAffinityEnabledStateDisabled @@ -834,7 +836,7 @@ func expandArmFrontDoorHealthProbeSettingsModel(input []interface{}, subscriptio name := v["name"].(string) result := frontdoor.HealthProbeSettingsModel{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "HealthProbeSettings", name)), + ID: utils.String(helper.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "HealthProbeSettings", name)), Name: utils.String(name), HealthProbeSettingsProperties: &frontdoor.HealthProbeSettingsProperties{ IntervalInSeconds: utils.Int32(intervalInSeconds), @@ -863,7 +865,7 @@ func expandArmFrontDoorLoadBalancingSettingsModel(input []interface{}, subscript sampleSize := int32(loadBalanceSetting["sample_size"].(int)) successfulSamplesRequired := int32(loadBalanceSetting["successful_samples_required"].(int)) additionalLatencyMilliseconds := int32(loadBalanceSetting["additional_latency_milliseconds"].(int)) - id := utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "LoadBalancingSettings", name)) + id := utils.String(helper.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "LoadBalancingSettings", name)) result := frontdoor.LoadBalancingSettingsModel{ ID: id, @@ -953,7 +955,7 @@ func expandArmFrontDoorAcceptedProtocols(input []interface{}) *[]frontdoor.Proto func expandArmFrontDoorSubResource(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) *frontdoor.SubResource { result := frontdoor.SubResource{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName)), + ID: utils.String(helper.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName)), } return &result @@ -1044,7 +1046,7 @@ func expandArmFrontDoorForwardingConfiguration(input []interface{}, subscription } backend := &frontdoor.SubResource{ - ID: utils.String(azure.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "BackendPools", backendPoolName)), + ID: utils.String(helper.GetFrontDoorSubResourceId(subscriptionId, resourceGroup, frontDoorName, "BackendPools", backendPoolName)), } forwardingConfiguration := frontdoor.ForwardingConfiguration{ @@ -1169,7 +1171,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re // Need to call frontEndEndpointClient here to get customConfiguration information from that client // because the information is hidden from the main frontDoorClient "by design"... - client := meta.(*ArmClient).frontDoorsFrontendClient + client := meta.(*ArmClient).frontdoor.FrontDoorsFrontendClient ctx := meta.(*ArmClient).StopContext resp, err := client.Get(ctx, resourceGroup, frontDoorName, *name) @@ -1327,7 +1329,7 @@ func flattenArmFrontDoorRoutingRule(input *[]frontdoor.RoutingRule) []interface{ } brc := properties.RouteConfiguration - if routeConfigType := azure.GetFrontDoorBasicRouteConfigurationType(brc.(interface{})); routeConfigType != "" { + if routeConfigType := helper.GetFrontDoorBasicRouteConfigurationType(brc.(interface{})); routeConfigType != "" { rc := make([]interface{}, 0) c := make(map[string]interface{}) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index d219a4af7f5c..45f4b874378a 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -1,15 +1,15 @@ package azurerm import ( - "fmt" - "strings" - "testing" - - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" - "github.com/hashicorp/terraform/helper/acctest" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) func TestAccAzureRMFrontDoor_basic(t *testing.T) { @@ -111,51 +111,51 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { } func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Front Door not found: %s", resourceName) - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - client := testAccProvider.Meta().(*ArmClient).frontDoorsClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext - - if resp, err := client.Get(ctx, resourceGroup, name); err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) - } - return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) - } - - return nil - } + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Front Door not found: %s", resourceName) + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + client := testAccProvider.Meta().(*ArmClient).frontDoorsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) + } + return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) + } + + return nil + } } func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).frontDoorsClient - ctx := testAccProvider.Meta().(*ArmClient).StopContext + client := testAccProvider.Meta().(*ArmClient).frontDoorsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_front_door" { - continue - } + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_front_door" { + continue + } - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] - if resp, err := client.Get(ctx, resourceGroup, name); err != nil { - if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) - } - } + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) + } + } - return nil - } + return nil + } - return nil + return nil } func testAccAzureRMFrontDoor_basic(rInt int, rString string, location string) string { From e471f1a4ce67eb5d0fb5bb2dfcce13eeefbace53 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 16 Aug 2019 14:07:29 -0700 Subject: [PATCH 33/74] Few changes per PR review --- azurerm/data_source_front_door.go | 6 +----- go.mod | 9 --------- website/docs/r/front_door.html.markdown | 4 ++-- 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go index d0de83499084..bf90f40e393b 100644 --- a/azurerm/data_source_front_door.go +++ b/azurerm/data_source_front_door.go @@ -379,11 +379,7 @@ func dataSourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("Error setting `enforce_backend_pools_certificate_name_check`: %+v", err) } d.Set("cname", properties.Cname) - if properties.EnabledState == frontdoor.EnabledStateEnabled { - d.Set("load_balancer_enabled", true) - } else { - d.Set("load_balancer_enabled", false) - } + d.Set("load_balancer_enabled", properties.EnabledState == frontdoor.EnabledStateEnabled) d.Set("friendly_name", properties.FriendlyName) frontDoorFrontendEndpoint, flattenErr := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta) diff --git a/go.mod b/go.mod index 38dfdeab1b31..ca5162aca1ce 100644 --- a/go.mod +++ b/go.mod @@ -13,14 +13,6 @@ require ( github.com/hashicorp/go-multierror v1.0.0 github.com/hashicorp/go-uuid v1.0.1 github.com/hashicorp/go-version v1.1.0 -<<<<<<< HEAD - github.com/hashicorp/terraform v0.12.0-alpha4.0.20190424121927-9327eedb0417 - github.com/katbyte/tctest v0.0.0-20190516150427-12a4ac6363f8 // indirect - github.com/satori/go.uuid v1.2.0 - github.com/satori/uuid v0.0.0-20160927100844-b061729afc07 - golang.org/x/crypto v0.0.0-20190506204251-e1dfcc566284 - golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 -======= github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/terraform v0.12.6 github.com/satori/go.uuid v1.2.0 @@ -29,6 +21,5 @@ require ( github.com/tombuildsstuff/giovanni v0.3.0 golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 golang.org/x/net v0.0.0-20190502183928-7f726cade0ab ->>>>>>> 03966b073d1d1a7ea0e51bbc4a8f3f8b267498d0 gopkg.in/yaml.v2 v2.2.2 ) \ No newline at end of file diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 52a341d42767..2389db419f56 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -25,8 +25,8 @@ resource "azurerm_frontdoor" "example" { patterns_to_match = ["/*"] frontend_endpoints = ["exampleFrontendEndpoint1"] forwarding_configuration { - forwarding_protocol = "MatchRequest" - backend_pool_name = "exampleBackendBing" + forwarding_protocol = "MatchRequest" + backend_pool_name = "exampleBackendBing" } } From cb3ba6c7010ffef15777d7ff6ce300844e9a2501 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 16 Aug 2019 14:18:04 -0700 Subject: [PATCH 34/74] Fixed lint errors --- .../services/frontdoor/validate/validate.go | 165 +++++++++--------- azurerm/resource_arm_front_door_test.go | 2 +- 2 files changed, 80 insertions(+), 87 deletions(-) diff --git a/azurerm/internal/services/frontdoor/validate/validate.go b/azurerm/internal/services/frontdoor/validate/validate.go index c8ecd079acbc..f09f66894f6a 100644 --- a/azurerm/internal/services/frontdoor/validate/validate.go +++ b/azurerm/internal/services/frontdoor/validate/validate.go @@ -37,114 +37,107 @@ func FrontdoorSettings(d *schema.ResourceDiff) error { return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) } - if routingRules != nil { - // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule - for _, rr := range routingRules { - routingRule := rr.(map[string]interface{}) - routingRuleName := routingRule["name"] - found := false - - redirectConfig := routingRule["redirect_configuration"].([]interface{}) - forwardConfig := routingRule["forwarding_configuration"].([]interface{}) - - // Check 0. validate that at least one routing configuration exists per routing rule - if len(redirectConfig) == 0 && len(forwardConfig) == 0 { - return fmt.Errorf(`"routing_rule":%q is invalid. you must have either a "redirect_configuration" or a "forwarding_configuration" defined for the "routing_rule":%q `, routingRuleName, routingRuleName) - } + // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule + for _, rr := range routingRules { + routingRule := rr.(map[string]interface{}) + routingRuleName := routingRule["name"] + found := false + + redirectConfig := routingRule["redirect_configuration"].([]interface{}) + forwardConfig := routingRule["forwarding_configuration"].([]interface{}) + + // Check 0. validate that at least one routing configuration exists per routing rule + if len(redirectConfig) == 0 && len(forwardConfig) == 0 { + return fmt.Errorf(`"routing_rule":%q is invalid. you must have either a "redirect_configuration" or a "forwarding_configuration" defined for the "routing_rule":%q `, routingRuleName, routingRuleName) + } - // Check 1. validate that only one configuration type is defined per routing rule - if len(redirectConfig) == 1 && len(forwardConfig) == 1 { - return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per each routing rule`, routingRuleName) - } + // Check 1. validate that only one configuration type is defined per routing rule + if len(redirectConfig) == 1 && len(forwardConfig) == 1 { + return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per each routing rule`, routingRuleName) + } - // Check 2. routing rule is a forwarding_configuration type make sure the backend_pool_name exists in the configuration file - if len(forwardConfig) > 0 { - fc := forwardConfig[0].(map[string]interface{}) - if err := helper.DoesBackendPoolExists(fc["backend_pool_name"].(string), backendPools); err != nil { - return fmt.Errorf(`"routing_rule":%q is invalid. %+v`, routingRuleName, err) - } + // Check 2. routing rule is a forwarding_configuration type make sure the backend_pool_name exists in the configuration file + if len(forwardConfig) > 0 { + fc := forwardConfig[0].(map[string]interface{}) + if err := helper.DoesBackendPoolExists(fc["backend_pool_name"].(string), backendPools); err != nil { + return fmt.Errorf(`"routing_rule":%q is invalid. %+v`, routingRuleName, err) } + } - // Check 3. validate that each routing rule frontend_endpoints are actually defined in the resource schema - if routingRuleFrontends := routingRule["frontend_endpoints"].([]interface{}); len(routingRuleFrontends) > 0 { - - for _, routingRuleFrontend := range routingRuleFrontends { - // - //TODO: Refactor to helper function that returns an error - // - // Get the name of the frontend defined in the routing rule - routingRulefrontendName := routingRuleFrontend.(string) - found = false - - // Loop over all of the defined frontend endpoints in the config - // seeing if we find the routing rule frontend in the list - for _, configFrontendEndpoint := range configFrontendEndpoints { - configFrontend := configFrontendEndpoint.(map[string]interface{}) - configFrontendName := configFrontend["name"] - if routingRulefrontendName == configFrontendName { - found = true - break - } + // Check 3. validate that each routing rule frontend_endpoints are actually defined in the resource schema + if routingRuleFrontends := routingRule["frontend_endpoints"].([]interface{}); len(routingRuleFrontends) > 0 { + + for _, routingRuleFrontend := range routingRuleFrontends { + // + //TODO: Refactor to helper function that returns an error + // + // Get the name of the frontend defined in the routing rule + routingRulefrontendName := routingRuleFrontend.(string) + found = false + + // Loop over all of the defined frontend endpoints in the config + // seeing if we find the routing rule frontend in the list + for _, configFrontendEndpoint := range configFrontendEndpoints { + configFrontend := configFrontendEndpoint.(map[string]interface{}) + configFrontendName := configFrontend["name"] + if routingRulefrontendName == configFrontendName { + found = true + break } + } - if !found { - return fmt.Errorf(`"routing_rule":%q "frontend_endpoints":%q was not found in the configuration file. verify you have the "frontend_endpoint":%q defined in the configuration file`, routingRuleName, routingRulefrontendName, routingRulefrontendName) - } + if !found { + return fmt.Errorf(`"routing_rule":%q "frontend_endpoints":%q was not found in the configuration file. verify you have the "frontend_endpoint":%q defined in the configuration file`, routingRuleName, routingRulefrontendName, routingRulefrontendName) } - } else { - return fmt.Errorf(`"routing_rule": %q must have at least one "frontend_endpoints" defined`, routingRuleName) } + } else { + return fmt.Errorf(`"routing_rule": %q must have at least one "frontend_endpoints" defined`, routingRuleName) } } // Verify backend pool load balancing settings and health probe settings are defined in the resource schema - if backendPools != nil { - - for _, bps := range backendPools { - backendPool := bps.(map[string]interface{}) - backendPoolName := backendPool["name"] - backendPoolLoadBalancingName := backendPool["load_balancing_name"] - backendPoolHealthProbeName := backendPool["health_probe_name"] - found := false - - // Verify backend pool load balancing settings name exists - if len(loadBalancingSettings) > 0 { - for _, lbs := range loadBalancingSettings { - loadBalancing := lbs.(map[string]interface{}) - loadBalancingName := loadBalancing["name"] - - if loadBalancingName == backendPoolLoadBalancingName { - found = true - break - } + for _, bps := range backendPools { + backendPool := bps.(map[string]interface{}) + backendPoolName := backendPool["name"] + backendPoolLoadBalancingName := backendPool["load_balancing_name"] + backendPoolHealthProbeName := backendPool["health_probe_name"] + found := false + + // Verify backend pool load balancing settings name exists + if len(loadBalancingSettings) > 0 { + for _, lbs := range loadBalancingSettings { + loadBalancing := lbs.(map[string]interface{}) + loadBalancingName := loadBalancing["name"] + + if loadBalancingName == backendPoolLoadBalancingName { + found = true + break } + } - if !found { - return fmt.Errorf(`"backend_pool":%q "load_balancing_name":%q was not found in the configuration file. verify you have the "backend_pool_load_balancing":%q defined in the configuration file`, backendPoolName, backendPoolLoadBalancingName, backendPoolLoadBalancingName) - } + if !found { + return fmt.Errorf(`"backend_pool":%q "load_balancing_name":%q was not found in the configuration file. verify you have the "backend_pool_load_balancing":%q defined in the configuration file`, backendPoolName, backendPoolLoadBalancingName, backendPoolLoadBalancingName) } + } - found = false + found = false - // Verify health probe settings name exists - if len(healthProbeSettings) > 0 { - for _, hps := range healthProbeSettings { - healthProbe := hps.(map[string]interface{}) - healthProbeName := healthProbe["name"] + // Verify health probe settings name exists + if len(healthProbeSettings) > 0 { + for _, hps := range healthProbeSettings { + healthProbe := hps.(map[string]interface{}) + healthProbeName := healthProbe["name"] - if healthProbeName == backendPoolHealthProbeName { - found = true - break - } + if healthProbeName == backendPoolHealthProbeName { + found = true + break } + } - if !found { - return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) - } + if !found { + return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) } } - } else { - return fmt.Errorf(`"backend_pool": must have at least one "backend" defined`) } // Verify frontend endpoints custom https configuration is valid if defined diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 45f4b874378a..7b275d73de73 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -135,7 +135,7 @@ func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc } func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).frontDoorsClient + client := testAccProvider.Meta().(*ArmClient).FrontDoorsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext for _, rs := range s.RootModule().Resources { From 1e505b486a1c8e96411b785b3bbe52e2cf2dcd6d Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 16 Aug 2019 14:19:30 -0700 Subject: [PATCH 35/74] Missed one client declaration --- azurerm/resource_arm_front_door_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 7b275d73de73..355383f2961f 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -120,7 +120,7 @@ func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc name := rs.Primary.Attributes["name"] resourceGroup := rs.Primary.Attributes["resource_group_name"] - client := testAccProvider.Meta().(*ArmClient).frontDoorsClient + client := testAccProvider.Meta().(*ArmClient).FrontDoorsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext if resp, err := client.Get(ctx, resourceGroup, name); err != nil { From ac6a9fa39ef3289997d4436068d73b41b072108b Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 16 Aug 2019 14:32:39 -0700 Subject: [PATCH 36/74] Fix test client --- azurerm/resource_arm_front_door_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index 355383f2961f..e7b111cc6d1e 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -120,14 +120,14 @@ func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc name := rs.Primary.Attributes["name"] resourceGroup := rs.Primary.Attributes["resource_group_name"] - client := testAccProvider.Meta().(*ArmClient).FrontDoorsClient + client := testAccProvider.Meta().(*ArmClient).frontdoor.FrontDoorsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext if resp, err := client.Get(ctx, resourceGroup, name); err != nil { if utils.ResponseWasNotFound(resp.Response) { return fmt.Errorf("Bad: Front Door %q (Resource Group %q) does not exist", name, resourceGroup) } - return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) + return fmt.Errorf("Bad: Get on FrontDoorsClient: %+v", err) } return nil @@ -135,7 +135,7 @@ func testCheckAzureRMFrontDoorExists(resourceName string) resource.TestCheckFunc } func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { - client := testAccProvider.Meta().(*ArmClient).FrontDoorsClient + client := testAccProvider.Meta().(*ArmClient).frontdoor.FrontDoorsClient ctx := testAccProvider.Meta().(*ArmClient).StopContext for _, rs := range s.RootModule().Resources { @@ -148,7 +148,7 @@ func testCheckAzureRMFrontDoorDestroy(s *terraform.State) error { if resp, err := client.Get(ctx, resourceGroup, name); err != nil { if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: Get on frontDoorsClient: %+v", err) + return fmt.Errorf("Bad: Get on FrontDoorsClient: %+v", err) } } From 5c9144ea5dd1f1db4221cad41a12f4fb31c068ee Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 16 Aug 2019 15:27:14 -0700 Subject: [PATCH 37/74] Removed data source fix lint errs --- azurerm/data_source_front_door.go | 408 ----------------------------- azurerm/resource_arm_front_door.go | 6 +- 2 files changed, 3 insertions(+), 411 deletions(-) delete mode 100644 azurerm/data_source_front_door.go diff --git a/azurerm/data_source_front_door.go b/azurerm/data_source_front_door.go deleted file mode 100644 index bf90f40e393b..000000000000 --- a/azurerm/data_source_front_door.go +++ /dev/null @@ -1,408 +0,0 @@ -package azurerm - -import ( - "fmt" - "log" - - "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" - "github.com/hashicorp/terraform/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func dataSourceArmFrontDoor() *schema.Resource { - return &schema.Resource{ - Read: dataSourceArmFrontDoorRead, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validate.FrontDoorName, - }, - - "load_balancer_enabled": { - Type: schema.TypeBool, - Computed: true, - }, - - "location": azure.SchemaLocation(), - - "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), - - "routing_rule": { - Type: schema.TypeList, - MaxItems: 100, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "accepted_protocols": { - Type: schema.TypeList, - Computed: true, - MaxItems: 2, - Elem: &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - }, - "patterns_to_match": { - Type: schema.TypeList, - Computed: true, - MaxItems: 25, - Elem: &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - }, - "frontend_endpoints": { - Type: schema.TypeList, - Computed: true, - MaxItems: 100, - Elem: &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - }, - "redirect_configuration": { - Type: schema.TypeList, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "custom_fragment": { - Type: schema.TypeString, - Computed: true, - }, - "custom_host": { - Type: schema.TypeString, - Computed: true, - }, - "custom_path": { - Type: schema.TypeString, - Computed: true, - }, - "custom_query_string": { - Type: schema.TypeString, - Computed: true, - }, - "redirect_protocol": { - Type: schema.TypeString, - Computed: true, - }, - "redirect_type": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "forwarding_configuration": { - Type: schema.TypeList, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "backend_pool_name": { - Type: schema.TypeString, - Computed: true, - }, - "cache_use_dynamic_compression": { - Type: schema.TypeBool, - Computed: true, - }, - "cache_query_parameter_strip_directive": { - Type: schema.TypeString, - Computed: true, - }, - "custom_forwarding_path": { - Type: schema.TypeString, - Computed: true, - }, - "forwarding_protocol": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - }, - }, - "enforce_backend_pools_certificate_name_check": { - Type: schema.TypeBool, - Computed: true, - }, - "backend_pool_load_balancing": { - Type: schema.TypeList, - MaxItems: 5000, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "sample_size": { - Type: schema.TypeInt, - Computed: true, - }, - "successful_samples_required": { - Type: schema.TypeInt, - Computed: true, - }, - "additional_latency_milliseconds": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "backend_pool_health_probe": { - Type: schema.TypeList, - MaxItems: 5000, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "path": { - Type: schema.TypeString, - Computed: true, - }, - "protocol": { - Type: schema.TypeString, - Computed: true, - }, - "interval_in_seconds": { - Type: schema.TypeInt, - Computed: true, - }, - }, - }, - }, - "backend_pool": { - Type: schema.TypeList, - MaxItems: 50, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "backend": { - Type: schema.TypeList, - MaxItems: 100, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "address": { - Type: schema.TypeString, - Computed: true, - }, - "http_port": { - Type: schema.TypeInt, - Computed: true, - }, - "https_port": { - Type: schema.TypeInt, - Computed: true, - }, - "weight": { - Type: schema.TypeInt, - Computed: true, - }, - "priority": { - Type: schema.TypeInt, - Computed: true, - }, - "host_header": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "health_probe_name": { - Type: schema.TypeString, - Computed: true, - }, - "load_balancing_name": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - "frontend_endpoint": { - Type: schema.TypeList, - MaxItems: 100, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, - "name": { - Type: schema.TypeString, - Computed: true, - }, - "host_name": { - Type: schema.TypeString, - Computed: true, - }, - "session_affinity_enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "session_affinity_ttl_seconds": { - Type: schema.TypeInt, - Computed: true, - }, - "custom_https_provisioning_enabled": { - Type: schema.TypeBool, - Computed: true, - }, - "custom_https_configuration": { - Type: schema.TypeList, - Computed: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "certificate_source": { - Type: schema.TypeString, - Computed: true, - }, - "provisioning_state": { - Type: schema.TypeString, - Computed: true, - }, - "provisioning_substate": { - Type: schema.TypeString, - Computed: true, - }, - // NOTE: None of these attributes are valid if - // certificate_source is set to FrontDoor - "azure_key_vault_certificate_secret_name": { - Type: schema.TypeString, - Computed: true, - }, - "azure_key_vault_certificate_secret_version": { - Type: schema.TypeString, - Computed: true, - }, - "azure_key_vault_certificate_vault_id": { - Type: schema.TypeString, - Computed: true, - }, - }, - }, - }, - }, - }, - }, - - "friendly_name": { - Type: schema.TypeString, - Computed: true, - }, - - "tags": tagsSchema(), - }, - } -} - -func dataSourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).frontdoor.FrontDoorsClient - ctx := meta.(*ArmClient).StopContext - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resourceGroup := id.ResourceGroup - name := id.Path["frontdoors"] - - resp, err := client.Get(ctx, resourceGroup, name) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[INFO] Front Door %q does not exist - removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error reading Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) - } - - d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - if properties := resp.Properties; properties != nil { - if err := d.Set("backend_pool", flattenArmFrontDoorBackendPools(properties.BackendPools)); err != nil { - return fmt.Errorf("Error setting `backend_pool`: %+v", err) - } - if err := d.Set("enforce_backend_pools_certificate_name_check", flattenArmFrontDoorBackendPoolsSettings(properties.BackendPoolsSettings)); err != nil { - return fmt.Errorf("Error setting `enforce_backend_pools_certificate_name_check`: %+v", err) - } - d.Set("cname", properties.Cname) - d.Set("load_balancer_enabled", properties.EnabledState == frontdoor.EnabledStateEnabled) - d.Set("friendly_name", properties.FriendlyName) - - frontDoorFrontendEndpoint, flattenErr := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta) - - if flattenErr == nil { - if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoint); err != nil { - return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) - } - } else { - return fmt.Errorf("Error setting `frontend_endpoint`: %+v", flattenErr) - } - if err := d.Set("backend_pool_health_probe", flattenArmFrontDoorHealthProbeSettingsModel(properties.HealthProbeSettings)); err != nil { - return fmt.Errorf("Error setting `backend_pool_health_probe`: %+v", err) - } - if err := d.Set("backend_pool_load_balancing", flattenArmFrontDoorLoadBalancingSettingsModel(properties.LoadBalancingSettings)); err != nil { - return fmt.Errorf("Error setting `backend_pool_load_balancing`: %+v", err) - } - if err := d.Set("routing_rule", flattenArmFrontDoorRoutingRule(properties.RoutingRules)); err != nil { - return fmt.Errorf("Error setting `routing_rules`: %+v", err) - } - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index a5a1948868f7..cd01673d705c 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -943,7 +943,7 @@ func expandArmFrontDoorAcceptedProtocols(input []interface{}) *[]frontdoor.Proto for _, ap := range input { result := frontdoor.HTTPS - if ap.(string) == fmt.Sprintf("%s", frontdoor.HTTP) { + if ap.(string) == string(frontdoor.HTTP) { result = frontdoor.HTTP } @@ -1100,7 +1100,7 @@ func flattenArmFrontDoorBackendPoolsSettings(input *frontdoor.BackendPoolsSettin result := false - if enforceCertificateNameCheck := frontdoor.EnforceCertificateNameCheckEnabledState(input.EnforceCertificateNameCheck); enforceCertificateNameCheck != "" { + if enforceCertificateNameCheck := input.EnforceCertificateNameCheck; enforceCertificateNameCheck != "" { if enforceCertificateNameCheck == frontdoor.EnforceCertificateNameCheckEnabledStateEnabled { result = true } @@ -1164,7 +1164,7 @@ func flattenArmFrontDoorFrontendEndpoint(input *[]frontdoor.FrontendEndpoint, re for _, v := range *input { result := make(map[string]interface{}) customHttpsConfiguration := make([]interface{}, 0) - chc := make(map[string]interface{}, 0) + chc := make(map[string]interface{}) if name := v.Name; name != nil { result["name"] = *name From b7214033429c70d47471a768f5054a2a30ada8ed Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 16 Aug 2019 15:44:51 -0700 Subject: [PATCH 38/74] update CheckDestroy func --- azurerm/resource_arm_front_door_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index e7b111cc6d1e..b43f7fe9e3f9 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -21,7 +21,7 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMFunctionAppDestroy, + CheckDestroy: testCheckAzureRMFrontDoorDestroy, Steps: []resource.TestStep{ { Config: config, @@ -77,7 +77,7 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMFunctionAppDestroy, + CheckDestroy: testCheckAzureRMFrontDoorDestroy, Steps: []resource.TestStep{ { Config: config, From 1efa68640ef64eda3b7847c6295633b9b51ebd4e Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 20 Aug 2019 12:04:32 -0700 Subject: [PATCH 39/74] [WIP] Initial check-in --- ...resource_arm_front_door_firewall_policy.go | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 azurerm/resource_arm_front_door_firewall_policy.go diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go new file mode 100644 index 000000000000..0739b8a071e2 --- /dev/null +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -0,0 +1,75 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/helper" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmFrontDoorFirewallPolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceArmFrontDoorFirewallPolicyCreateUpdate, + Read: resourceArmFrontDoorFirewallPolicyRead, + Update: resourceArmFrontDoorFirewallPolicyCreateUpdate, + Delete: resourceArmFrontDoorFirewallPolicyDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true + }, + + "location": azure.SchemaLocation(), + + "policy_settings": { + Type: schema.TypeList, + MaxItems: 100, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "policy_mode": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Detection), + string(frontdoor.Prevention), + }, false), + }, + "RedirectURL" : { + Type: schema.TypeString, + Optional: true, + }, + "custom_block_response_status_code": { + Type: schema.Int, + Optional: true, + }, + "custom_block_response_body": { + Type: schema.TypeString, + Optional: true, + } + }, + }, + }, + + "tags": tags.Schema(), + }, + } +} \ No newline at end of file From 98b946f4422eabd04b0b654383e1724c5d55feb4 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 20 Aug 2019 18:54:33 -0700 Subject: [PATCH 40/74] [WIP] Tuning Schema --- ...resource_arm_front_door_firewall_policy.go | 197 +++++++++++++++++- 1 file changed, 187 insertions(+), 10 deletions(-) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 0739b8a071e2..ca0cbdfa31a2 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -28,43 +28,220 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { Type: schema.TypeString, - Computed: true + Computed: true, + } + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "mode": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Detection), + string(frontdoor.Prevention), + }, false), }, - "location": azure.SchemaLocation(), + "custom_block_response_status_code": { + Type: schema.Int, + Optional: true, + }, + + "redirect_url" : { + Type: schema.TypeString, + Optional: true, + }, + + "custom_block_response_body": { + Type: schema.TypeString, + Optional: true, + }, - "policy_settings": { + "custom_rule": { Type: schema.TypeList, MaxItems: 100, Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "name" : { + Type: schema.TypeString, + Optional: true, + }, + "priority": { + Type: schema.Int, + Optional: true, + Default: 1, + }, "enabled": { Type: schema.TypeBool, Optional: true, Default: true, }, - "policy_mode": { + "rule_type": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Detection), - string(frontdoor.Prevention), + string(frontdoor.MatchRule), + string(frontdoor.RateLimitRule), }, false), }, - "RedirectURL" : { - Type: schema.TypeString, + "rate_limit_duration_in_minutes": { + Type: schema.Int, Optional: true, + Default: 1, }, - "custom_block_response_status_code": { + "rate_limit_threshold": { Type: schema.Int, Optional: true, + Default: 10, + }, + "action": { + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Allow), + string(frontdoor.Block), + string(frontdoor.Trim), + string(frontdoor.Log), + string(frontdoor.Redirect), + }, false), }, "custom_block_response_body": { Type: schema.TypeString, Optional: true, - } + }, + "match_condition" : { + Type: schema.TypeList, + Optional: true, + MaxItems: 100, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "match_variable": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Cookies), + string(frontdoor.PostArgs), + string(frontdoor.QueryString), + string(frontdoor.RemoteAddr), + string(frontdoor.RequestBody), + string(frontdoor.RequestHeader), + string(frontdoor.RequestMethod), + string(frontdoor.RequestURI), + }, false), + }, + "selector": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Cookies), + string(frontdoor.PostArgs), + string(frontdoor.QueryString), + string(frontdoor.RequestHeader), + }, false), + }, + "operator": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Any), + string(frontdoor.BeginsWith), + string(frontdoor.Contains), + string(frontdoor.EndsWith), + string(frontdoor.Equal), + string(frontdoor.GeoMatch), + string(frontdoor.GreaterThan), + string(frontdoor.GreaterThanOrEqual), + string(frontdoor.IPMatch), + string(frontdoor.LessThan), + string(frontdoor.LessThanOrEqual), + string(frontdoor.RegEx), + }, false), + }, + "condition": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "Is", + "Is Not", + "Contains", + "Not Contains", + }, false), + Default: "Is" + }, + "match_value": { + Type: schema.TypeList, + Required: true, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "transforms": { + Type: schema.TypeList, + Optional: true, + MaxItems: 6, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Lowercase), + string(frontdoor.RemoveNulls), + string(frontdoor.Trim), + string(frontdoor.Uppercase), + string(frontdoor.URLDecode), + string(frontdoor.URLEncode), + }, false), + }, + }, + }, + }, + }, + }, + }, + }, + + "managed_rule": { + Type: schema.TypeList, + MaxItems: 100, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type" : { + Type: schema.TypeString, + Optional: true, + }, + "version" : { + Type: schema.TypeString, + Optional: true, + }, + "override" : { + Type: schema.TypeList, + MaxItems: 100, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "rule_group_name" : { + Type: schema.TypeString, + Optional: true, + }, + "rules" : { + Type: schema.TypeString, + Optional: true, + }, + + }, + }, + }, }, }, }, From 162dd5b36178296983e9fc1faf17f4a3f7d9d32a Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 16:08:42 -0700 Subject: [PATCH 41/74] [WIP] Schema final --- ...resource_arm_front_door_firewall_policy.go | 102 ++++++++++++------ 1 file changed, 69 insertions(+), 33 deletions(-) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index ca0cbdfa31a2..379a181c5bd6 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -28,15 +28,15 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, }, "location": { Type: schema.TypeString, Computed: true, - } + }, "enabled": { Type: schema.TypeBool, @@ -45,7 +45,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, "mode": { - Type: schema.TypeString, + Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Detection), @@ -54,17 +54,17 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, "custom_block_response_status_code": { - Type: schema.Int, + Type: schema.Int, Optional: true, }, - "redirect_url" : { - Type: schema.TypeString, + "redirect_url": { + Type: schema.TypeString, Optional: true, }, "custom_block_response_body": { - Type: schema.TypeString, + Type: schema.TypeString, Optional: true, }, @@ -74,14 +74,14 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name" : { - Type: schema.TypeString, + "name": { + Type: schema.TypeString, Optional: true, }, "priority": { - Type: schema.Int, + Type: schema.Int, Optional: true, - Default: 1, + Default: 1, }, "enabled": { Type: schema.TypeBool, @@ -89,7 +89,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Default: true, }, "rule_type": { - Type: schema.TypeString, + Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.MatchRule), @@ -97,30 +97,29 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, "rate_limit_duration_in_minutes": { - Type: schema.Int, + Type: schema.Int, Optional: true, - Default: 1, + Default: 1, }, "rate_limit_threshold": { - Type: schema.Int, + Type: schema.Int, Optional: true, - Default: 10, + Default: 10, }, "action": { Type: schema.TypeString, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Allow), string(frontdoor.Block), - string(frontdoor.Trim), string(frontdoor.Log), string(frontdoor.Redirect), }, false), }, "custom_block_response_body": { - Type: schema.TypeString, + Type: schema.TypeString, Optional: true, }, - "match_condition" : { + "match_condition": { Type: schema.TypeList, Optional: true, MaxItems: 100, @@ -177,7 +176,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "Contains", "Not Contains", }, false), - Default: "Is" + Default: "Is", }, "match_value": { Type: schema.TypeList, @@ -216,29 +215,52 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "type" : { - Type: schema.TypeString, + "type": { + Type: schema.TypeString, Optional: true, }, - "version" : { - Type: schema.TypeString, + "version": { + Type: schema.TypeString, Optional: true, }, - "override" : { + "override": { Type: schema.TypeList, MaxItems: 100, Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "rule_group_name" : { - Type: schema.TypeString, + "rule_group_name": { + Type: schema.TypeString, Optional: true, }, - "rules" : { - Type: schema.TypeString, + "rule": { + Type: schema.TypeList, + MaxItems: 1000, Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "rule_id": { + Type: schema.TypeString, + Required: true, + }, + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "action": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(frontdoor.Allow), + string(frontdoor.Block), + string(frontdoor.Log), + string(frontdoor.Redirect), + }, false), + }, + }, + }, }, - }, }, }, @@ -246,7 +268,21 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, }, + "frontend_endpoints": { + Type: schema.TypeList, + MaxItems: 100, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + "tags": tags.Schema(), }, } -} \ No newline at end of file +} From 822ef9d04f625f491295066a8340366070199299 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 16:17:52 -0700 Subject: [PATCH 42/74] Update website/docs/r/front_door.html.markdown Co-Authored-By: kt --- website/docs/r/front_door.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 2389db419f56..290fb73f13db 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -95,7 +95,7 @@ The `backend_pool` block supports the following: * `backend` - (Required) A `backend` block as defined below. -* `load_balancing_name` - (Required) The name of the `backend_pool_load_balancing` to use for the `Backend Pool`. +* `load_balancing_name` - (Required) The name property of a `backend_pool_load_balancing` within this resource to use for the Backend Pool. * `health_probe_name` - (Required) The name of the `backend_pool_health_probe` to use for the `Backend Pool`. @@ -229,4 +229,4 @@ Front Doors can be imported using the `resource id`, e.g. ```shell terraform import azurerm_frontdoor.test /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/mygroup1/providers/Microsoft.Network/frontdoors/frontdoor1 -``` \ No newline at end of file +``` From d54b7fcd2f8ce1eb89d3ce71bf263487ff009812 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 16:18:11 -0700 Subject: [PATCH 43/74] Update azurerm/resource_arm_front_door.go Co-Authored-By: kt --- azurerm/resource_arm_front_door.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index cd01673d705c..ef76acbd7e57 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -608,7 +608,7 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } d.Set("cname", properties.Cname) if properties.EnabledState == frontdoor.EnabledStateEnabled { - d.Set("load_balancer_enabled", true) + d.Set("load_balancer_enabled", properties.EnabledState == frontdoor.EnabledStateEnabled) } else { d.Set("load_balancer_enabled", false) } From 262b1f974f058585015c4ff1b22363f59a0df3c2 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 16:18:37 -0700 Subject: [PATCH 44/74] Update azurerm/resource_arm_front_door.go Co-Authored-By: kt --- azurerm/resource_arm_front_door.go | 1 - 1 file changed, 1 deletion(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index ef76acbd7e57..d092a46037ed 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -615,7 +615,6 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { d.Set("friendly_name", properties.FriendlyName) if frontDoorFrontendEndpoints, err := flattenArmFrontDoorFrontendEndpoint(properties.FrontendEndpoints, resourceGroup, *resp.Name, meta); frontDoorFrontendEndpoints != nil { - if err := d.Set("frontend_endpoint", frontDoorFrontendEndpoints); err != nil { return fmt.Errorf("Error setting `frontend_endpoint`: %+v", err) } From ba08bca06aa46a4034924dbe39c428a28d2d4a7f Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 17:02:16 -0700 Subject: [PATCH 45/74] Update test and docs --- azurerm/resource_arm_front_door_test.go | 46 +++++++++++++++++++++++-- website/docs/r/front_door.html.markdown | 31 +++++++---------- 2 files changed, 55 insertions(+), 22 deletions(-) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index b43f7fe9e3f9..db49550e5988 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -67,12 +67,12 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { }) } -func TestAccAzureRMFrontDoor_update(t *testing.T) { +func TestAccAzureRMFrontDoor_complete(t *testing.T) { resourceName := "azurerm_frontdoor.test" ri := tf.AccRandTimeInt() rs := strings.ToLower(acctest.RandString(5)) config := testAccAzureRMFrontDoor_basic(ri, rs, testLocation()) - update := testAccAzureRMFrontDoor_update(ri, rs, testLocation()) + update := testAccAzureRMFrontDoor_complete(ri, rs, testLocation()) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -106,6 +106,46 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), ), }, + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "load_balancer_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "false"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendBing-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", "www.bing.com"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Http"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_provisioning_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "false"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, }, }) } @@ -212,7 +252,7 @@ resource "azurerm_frontdoor" "test" { `, rInt, rString, location) } -func testAccAzureRMFrontDoor_update(rInt int, rString string, location string) string { +func testAccAzureRMFrontDoor_complete(rInt int, rString string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "testAccRG-%[1]d" diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 2389db419f56..29b85268c675 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -10,6 +10,13 @@ description: |- Manage an Azure Front Door instance. +Azure Front Door Service is Microsoft's highly available and scalable web application acceleration platform and global HTTP(s) load balancer. It provides built-in DDoS protection and application layer security and caching. Front Door enables you to build applications that maximize and automate high-availability and performance for your end-users. Use Front Door with Azure services including Web/Mobile Apps, Cloud Services and Virtual Machines – or combine it with on-premises services for hybrid deployments and smooth cloud migration. + +Below are some of the key scenarios that Azure Front Door Service addresses: +* Use Front Door to improve application scale and availability with instant multi-region failover +* Use Front Door to improve application performance with SSL offload and routing requests to the fastest available application backend. +* Use Front Door for application layer security and DDoS protection for your application. + ## Example Usage ```hcl @@ -95,9 +102,9 @@ The `backend_pool` block supports the following: * `backend` - (Required) A `backend` block as defined below. -* `load_balancing_name` - (Required) The name of the `backend_pool_load_balancing` to use for the `Backend Pool`. +* `load_balancing_name` - (Required) The name property of the `backend_pool_load_balancing` block whithin this resource to use for the `Backend Pool`. -* `health_probe_name` - (Required) The name of the `backend_pool_health_probe` to use for the `Backend Pool`. +* `health_probe_name` - (Required) The name property of a `backend_pool_health_probe` block whithin this resource to use for the `Backend Pool`. --- @@ -131,6 +138,8 @@ The `frontend_endpoint` block supports the following: * `session_affinity_ttl_seconds` - (Optional) The TTL to use in seconds for session affinity, if applicable. Defaults to `0`. +* `enable_custom_https_provisioning` - (Required) Name of the Frontend Endpoint. + [//]: * "* `web_application_firewall_policy_link_id` - (Optional) The `id` of the `web_application_firewall_policy_link` to use for this Frontend Endpoint." --- @@ -169,7 +178,7 @@ The `routing_rule` block supports the following: * `name` - (Required) The name of the Front Door Backend Routing Rule. -* `frontend_endpoints` - (Required) A `frontend_endpoint` block as defined below. +* `frontend_endpoints` - (Required) The name property of the `frontend_endpoint` block whithin this resource to associate with this `routing_rule`. * `accepted_protocols` - (Optional) Protocol schemes to match for the Backend Routing Rule. Defaults to `Http`. @@ -179,22 +188,6 @@ The `routing_rule` block supports the following: --- -The `frontend_endpoint` block supports the following: - -* `id` - The Resource ID of the Azure Front Door Frontend Endpoint. - -* `name` - (Required) The Name of the Azure Front Door Frontend Endpoint. - -* `host_name` - (Required) The host name of the Frontend Endpoint. Must be a domain name. - -* `session_affinity_enabled` - (Optional) Allow session affinity on the Frontend Endpoint. Valid options are `true` or `false`. Defaults to `false`. - -* `session_affinity_ttl_seconds` - (Optional) The TTL to use, in seconds, for session affinity, if applicable. Defaults to `0`. - -* `enable_custom_https_provisioning` - (Required) Name of the Frontend Endpoint. - ---- - The `custom_https_configuration` block supports the following: * `certificate_source` - (Optional) Certificate source to encrypted `HTTPS` traffic with. Allowed values are `FrontDoor` or `AzureKeyVault`. Defaults to `FrontDoor`. From f25eed429f2fd27055499b082de7d277cdb5f71b Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 17:25:03 -0700 Subject: [PATCH 46/74] Added test case --- azurerm/resource_arm_front_door_test.go | 51 ++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index db49550e5988..e13366e0c5c3 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -67,7 +67,7 @@ func TestAccAzureRMFrontDoor_basic(t *testing.T) { }) } -func TestAccAzureRMFrontDoor_complete(t *testing.T) { +func TestAccAzureRMFrontDoor_update(t *testing.T) { resourceName := "azurerm_frontdoor.test" ri := tf.AccRandTimeInt() rs := strings.ToLower(acctest.RandString(5)) @@ -141,6 +141,55 @@ func TestAccAzureRMFrontDoor_complete(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), ), }, + }, + }) +} +func TestAccAzureRMFrontDoor_complete(t *testing.T) { + resourceName := "azurerm_frontdoor.test" + ri := tf.AccRandTimeInt() + rs := strings.ToLower(acctest.RandString(5)) + config := testAccAzureRMFrontDoor_complete(ri, rs, testLocation()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMFrontDoorDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "load_balancer_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "false"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendBing-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", "www.bing.com"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Http"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_provisioning_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRule1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "false"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), + ), + }, { ResourceName: resourceName, ImportState: true, From d21382e40012c7040f3d3593d3e5625bcedcb363 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 17:58:45 -0700 Subject: [PATCH 47/74] Update test per PR --- azurerm/resource_arm_front_door_test.go | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/azurerm/resource_arm_front_door_test.go b/azurerm/resource_arm_front_door_test.go index e13366e0c5c3..2b5acd763573 100644 --- a/azurerm/resource_arm_front_door_test.go +++ b/azurerm/resource_arm_front_door_test.go @@ -144,6 +144,7 @@ func TestAccAzureRMFrontDoor_update(t *testing.T) { }, }) } + func TestAccAzureRMFrontDoor_complete(t *testing.T) { resourceName := "azurerm_frontdoor.test" ri := tf.AccRandTimeInt() @@ -160,8 +161,9 @@ func TestAccAzureRMFrontDoor_complete(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMFrontDoorExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoor-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "friendly_name", "tafd"), resource.TestCheckResourceAttr(resourceName, "load_balancer_enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "false"), + resource.TestCheckResourceAttr(resourceName, "enforce_backend_pools_certificate_name_check", "true"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.name", fmt.Sprintf("testAccBackendBing-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.address", "www.bing.com"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.enabled", "true"), @@ -170,23 +172,30 @@ func TestAccAzureRMFrontDoor_complete(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.http_port", "80"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.priority", "1"), resource.TestCheckResourceAttr(resourceName, "backend_pool.0.backend.0.weight", "50"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.address", "www.google.com"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.load_balancing_name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.health_probe_name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.http_port", "80"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.priority", "1"), + resource.TestCheckResourceAttr(resourceName, "backend_pool.1.backend.0.weight", "50"), resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.name", fmt.Sprintf("testAccHealthProbeSetting1-%d", ri)), - resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Http"), + resource.TestCheckResourceAttr(resourceName, "backend_pool_health_probe.0.protocol", "Https"), resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.name", fmt.Sprintf("testAccLoadBalancingSettings1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "backend_pool_load_balancing.0.successful_samples_required", "2"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.name", fmt.Sprintf("testAccFrontendBing-%d", ri)), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.host_name", fmt.Sprintf("testAccFrontDoor-%d.azurefd.net", ri)), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.custom_https_provisioning_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "frontend_endpoint.0.session_affinity_ttl_seconds", "0"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.name", fmt.Sprintf("testAccRoutingRule1-%d", ri)), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.enabled", "true"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.0", "Http"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.accepted_protocols.1", "Https"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "false"), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_use_dynamic_compression", "true"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.forwarding_protocol", "MatchRequest"), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.forwarding_configuration.0.cache_query_parameter_strip_directive", "StripNone"), - resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendEndpoint1-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "routing_rule.0.frontend_endpoints.0", fmt.Sprintf("testAccFrontendBing-%d", ri)), resource.TestCheckResourceAttr(resourceName, "routing_rule.0.patterns_to_match.0", "/*"), ), }, From 28383a98550d285d72152a00c3b0be7f10af701c Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 21 Aug 2019 18:17:02 -0700 Subject: [PATCH 48/74] Address PR issues --- azurerm/resource_arm_front_door.go | 10 ++---- website/docs/r/front_door.html.markdown | 48 +++++++++++++++++-------- 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index d092a46037ed..3fa2f8de36f3 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -784,14 +784,10 @@ func expandArmFrontDoorFrontendEndpoint(input []interface{}, subscriptionId stri ID: id, Name: utils.String(name), FrontendEndpointProperties: &frontdoor.FrontendEndpointProperties{ - // ResourceState: - // CustomHTTPSProvisioningState: - // CustomHTTPSProvisioningSubstate: CustomHTTPSConfiguration: expandArmFrontDoorCustomHTTPSConfiguration(customHttpsConfiguration), HostName: utils.String(hostName), SessionAffinityEnabledState: sessionAffinityEnabled, SessionAffinityTTLSeconds: utils.Int32(sessionAffinityTtlSeconds), - // WebApplicationFirewallPolicyLink: }, } @@ -977,13 +973,11 @@ func expandArmFrontDoorFrontEndEndpoints(input []interface{}, subscriptionId str } func expandArmFrontDoorEnabledState(enabled bool) frontdoor.EnabledState { - result := frontdoor.EnabledStateDisabled - if enabled { - result = frontdoor.EnabledStateEnabled + return frontdoor.EnabledStateEnabled } - return result + return frontdoor.EnabledStateDisabled } func expandArmFrontDoorRedirectConfiguration(input []interface{}) frontdoor.RedirectConfiguration { diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 9acec8ddaff8..70517963d8b7 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -96,8 +96,6 @@ The following arguments are supported: The `backend_pool` block supports the following: -* `id` - The Resource ID of the Azure Front Door Backend Pool. - * `name` - (Required) The name of the `Backend Pool`. * `backend` - (Required) A `backend` block as defined below. @@ -110,8 +108,6 @@ The `backend_pool` block supports the following: The `backend` block supports the following: -* `id` - The Resource ID of the Azure Front Door Backend. - * `address` - (Required) Location of the backend (IP address or FQDN) * `host_header` - (Required) The value to use as the host header sent to the backend. @@ -128,8 +124,6 @@ The `backend` block supports the following: The `frontend_endpoint` block supports the following: -* `id` - The Resource ID of the Azure Front Door Frontend Endpoint. - * `name` - (Required) The name of the Frontend Endpoint. * `host_name` - (Required) The host name of the Frontend Endpoint. Must be a domain name. @@ -140,14 +134,10 @@ The `frontend_endpoint` block supports the following: * `enable_custom_https_provisioning` - (Required) Name of the Frontend Endpoint. -[//]: * "* `web_application_firewall_policy_link_id` - (Optional) The `id` of the `web_application_firewall_policy_link` to use for this Frontend Endpoint." - --- The `backend_pool_health_probe` block supports the following: -* `id` - The Resource ID of the Azure Front Door Backend Health Probe. - * `name` - (Required) The name of the Azure Front Door Backend Health Probe. * `path` - (Optional) The path to use for the Backend Health Probe. Default is `/`. @@ -160,8 +150,6 @@ The `backend_pool_health_probe` block supports the following: The `backend_pool_load_balancing` block supports the following: -* `id` - The Resource ID of the Azure Front Door Backend Load Balancer. - * `name` - (Required) The name of the Azure Front Door Backend Load Balancer. * `sample_size` - (Optional) The number of samples to consider for load balancing decisions. Defaults to `4`. @@ -174,8 +162,6 @@ The `backend_pool_load_balancing` block supports the following: The `routing_rule` block supports the following: -* `id` - The Resource ID of the Azure Front Door Backend Routing Rule. - * `name` - (Required) The name of the Front Door Backend Routing Rule. * `frontend_endpoints` - (Required) The name property of the `frontend_endpoint` block whithin this resource to associate with this `routing_rule`. @@ -206,12 +192,44 @@ The following attributes are only valid if `certificate_source` is set to `Azure ## Attributes Reference -The following attributes are exported: +`backend_pool` exports the following: + +* `id` - The Resource ID of the Azure Front Door Backend Pool. + + +`backend` exports the following: + +* `id` - The Resource ID of the Azure Front Door Backend. + + +`frontend_endpoint` exports the following: + +* `id` - The Resource ID of the Azure Front Door Frontend Endpoint. * `provisioning_state` - Provisioning state of the Front Door. * `provisioning_substate` - Provisioning substate of the Front Door +[//]: * "* `web_application_firewall_policy_link_id` - (Optional) The `id` of the `web_application_firewall_policy_link` to use for this Frontend Endpoint." + + +`backend_pool_health_probe` exports the following: + +* `id` - The Resource ID of the Azure Front Door Backend Health Probe. + + +`backend_pool_load_balancing` exports the following: + +* `id` - The Resource ID of the Azure Front Door Backend Load Balancer. + + +`routing_rule` exports the following: + +* `id` - The Resource ID of the Azure Front Door Backend Routing Rule. + + +The following attributes are exported: + * `cname` - The host that each frontendEndpoint must CNAME to. * `id` - Resource ID. From c592646b69a02bf03894d27cb73549cca235957b Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 22 Aug 2019 01:17:22 -0700 Subject: [PATCH 49/74] Update website/docs/r/front_door.html.markdown Co-Authored-By: kt --- website/docs/r/front_door.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/front_door.html.markdown b/website/docs/r/front_door.html.markdown index 70517963d8b7..7ed855363659 100644 --- a/website/docs/r/front_door.html.markdown +++ b/website/docs/r/front_door.html.markdown @@ -164,7 +164,7 @@ The `routing_rule` block supports the following: * `name` - (Required) The name of the Front Door Backend Routing Rule. -* `frontend_endpoints` - (Required) The name property of the `frontend_endpoint` block whithin this resource to associate with this `routing_rule`. +* `frontend_endpoints` - (Required) The names of the `frontend_endpoint` blocks whithin this resource to associate with this `routing_rule`. * `accepted_protocols` - (Optional) Protocol schemes to match for the Backend Routing Rule. Defaults to `Http`. From bc20eef2878e805252efe5f2a1cfcdaaf5ac5ee9 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 22 Aug 2019 16:51:10 -0700 Subject: [PATCH 50/74] [WIP] Adding CreateUpdate --- azurerm/internal/services/frontdoor/client.go | 5 + .../services/frontdoor/helper/helper.go | 16 ++ azurerm/provider.go | 1 + ...resource_arm_front_door_firewall_policy.go | 156 +++++++++++++----- 4 files changed, 139 insertions(+), 39 deletions(-) diff --git a/azurerm/internal/services/frontdoor/client.go b/azurerm/internal/services/frontdoor/client.go index af7c6040c320..60fee3730207 100644 --- a/azurerm/internal/services/frontdoor/client.go +++ b/azurerm/internal/services/frontdoor/client.go @@ -8,6 +8,7 @@ import ( type Client struct { FrontDoorsClient *frontdoor.FrontDoorsClient FrontDoorsFrontendClient *frontdoor.FrontendEndpointsClient + FrontDoorsPolicyClient *frontdoor.PoliciesClient } func BuildClient(o *common.ClientOptions) *Client { @@ -17,8 +18,12 @@ func BuildClient(o *common.ClientOptions) *Client { frontDoorsFrontendClient := frontdoor.NewFrontendEndpointsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&frontDoorsFrontendClient.Client, o.ResourceManagerAuthorizer) + frontDoorsPolicyClient := frontdoor.NewPoliciesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&frontDoorsPolicyClient.Client, o.ResourceManagerAuthorizer) + return &Client{ FrontDoorsClient: &frontDoorsClient, FrontDoorsFrontendClient: &frontDoorsFrontendClient, + FrontDoorsPolicyClient: &frontDoorsPolicyClient, } } diff --git a/azurerm/internal/services/frontdoor/helper/helper.go b/azurerm/internal/services/frontdoor/helper/helper.go index 3c93e01623a9..01044849d876 100644 --- a/azurerm/internal/services/frontdoor/helper/helper.go +++ b/azurerm/internal/services/frontdoor/helper/helper.go @@ -63,6 +63,22 @@ func NormalizeCustomHTTPSProvisioningStateToBool(provisioningState frontdoor.Cus return isEnabled } +func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabledState { + if isEnabled { + return frontdoor.PolicyEnabledStateEnabled + } + + return frontdoor.PolicyEnabledStateDisabled +} + +func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { + if policyMode == "Detection" { + return frontdoor.Detection + } + + return frontdoor.Prevention +} + func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { return "" diff --git a/azurerm/provider.go b/azurerm/provider.go index d743de8a0478..91f68df68ea6 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -235,6 +235,7 @@ func Provider() terraform.ResourceProvider { "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), "azurerm_firewall": resourceArmFirewall(), "azurerm_frontdoor": resourceArmFrontDoor(), + "azurerm_frontdoor_firewall_policy": resourceArmFrontDoorFirewallPolicy(), "azurerm_function_app": resourceArmFunctionApp(), "azurerm_hdinsight_hadoop_cluster": resourceArmHDInsightHadoopCluster(), "azurerm_hdinsight_hbase_cluster": resourceArmHDInsightHBaseCluster(), diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 379a181c5bd6..b0a00c997439 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -8,10 +8,11 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/helper" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" + //"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -28,9 +29,10 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.NoEmptyStrings, }, "location": { @@ -38,6 +40,8 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Computed: true, }, + "resource_group_name": azure.SchemaResourceGroupName(), + "enabled": { Type: schema.TypeBool, Optional: true, @@ -54,18 +58,20 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, "custom_block_response_status_code": { - Type: schema.Int, + Type: schema.TypeInt, Optional: true, }, "redirect_url": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "custom_block_response_body": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "custom_rule": { @@ -75,11 +81,12 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "priority": { - Type: schema.Int, + Type: schema.TypeInt, Optional: true, Default: 1, }, @@ -97,17 +104,18 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, "rate_limit_duration_in_minutes": { - Type: schema.Int, + Type: schema.TypeInt, Optional: true, Default: 1, }, "rate_limit_threshold": { - Type: schema.Int, + Type: schema.TypeInt, Optional: true, Default: 10, }, "action": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Allow), string(frontdoor.Block), @@ -116,8 +124,9 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, "custom_block_response_body": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "match_condition": { Type: schema.TypeList, @@ -125,9 +134,10 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { MaxItems: 100, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + // Conflicts with Selector "match_variable": { Type: schema.TypeString, - Required: true, + Optional: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Cookies), string(frontdoor.PostArgs), @@ -139,6 +149,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.RequestURI), }, false), }, + // Conflicts with match variable "selector": { Type: schema.TypeString, Optional: true, @@ -183,13 +194,14 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, MaxItems: 100, Elem: &schema.Schema{ - Type: schema.TypeString, + Type: schema.TypeString, + ValidateFunc: validate.NoEmptyStrings, }, }, "transforms": { Type: schema.TypeList, Optional: true, - MaxItems: 6, + MaxItems: 5, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.StringInSlice([]string{ @@ -216,22 +228,25 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "type": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "version": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "override": { Type: schema.TypeList, MaxItems: 100, - Required: true, + Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "rule_group_name": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "rule": { Type: schema.TypeList, @@ -240,8 +255,9 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "rule_id": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.NoEmptyStrings, }, "enabled": { Type: schema.TypeBool, @@ -268,21 +284,83 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, }, - "frontend_endpoints": { + "frontend_endpoint_ids": { Type: schema.TypeList, - MaxItems: 100, Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Required: true, - }, - }, + MaxItems: 1000, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validate.NoEmptyStrings, }, }, - "tags": tags.Schema(), + "tags": tagsSchema(), }, } } + +func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontdoor.FrontDoorsPolicyClient + ctx := meta.(*ArmClient).StopContext + + log.Printf("[INFO] preparing args for Front Door Firewall Policy") + + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) + + if requireResourcesToBeImported { + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Error checking for present of existing Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + if !utils.ResponseWasNotFound(resp.Response) { + return tf.ImportAsExistsError("azurerm_frontdoor_firewall_policy", *resp.ID) + } + } + + location := azure.NormalizeLocation("Global") + enabled := d.Get("enabled").(bool) + mode := d.Get("mode").(string) + redirectUrl := d.Get("redirect_url ").(string) + customBlockResponseStatusCode := d.Get("custom_block_response_status_code").(int32) + customBlockResponseBody := d.Get("custom_block_response_body").(string) + customRules := d.Get("custom_rule").([]interface{}) + managedRules := d.Get("managed_rule").([]interface{}) + frontendEndpoints := d.Get("frontend_endpoint_ids").([]interface{}) + tags := d.Get("tags").(map[string]interface{}) + + frontdoorWebApplicationFirewallPolicyProperties := frontdoor.WebApplicationFirewallPolicyProperties {} + frontDoorPolicySettings := frontdoor.PolicySettings { + EnabledState : helper.ConvertToPolicyEnabledStateFromBool(enabled), + Mode: helper.ConvertToPolicyModeFromString(mode), + RedirectURL: utils.String(redirectUrl), + CustomBlockResponseStatusCode: &customBlockResponseStatusCode, + CustomBlockResponseBody: utils.String(customBlockResponseBody), + + // Properties: &frontdoor.Properties{ + // FriendlyName: utils.String(friendlyName), + // RoutingRules: expandArmFrontDoorRoutingRule(routingRules, subscriptionId, resourceGroup, name), + // BackendPools: expandArmFrontDoorBackendPools(backendPools, subscriptionId, resourceGroup, name), + // BackendPoolsSettings: expandArmFrontDoorBackendPoolsSettings(backendPoolsSettings), + // FrontendEndpoints: expandArmFrontDoorFrontendEndpoint(frontendEndpoints, subscriptionId, resourceGroup, name), + // HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings, subscriptionId, resourceGroup, name), + // LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings, subscriptionId, resourceGroup, name), + // EnabledState: expandArmFrontDoorEnabledState(enabledState), + // }, + //Tags: expandTags(tags), + } + + return nil +} + +func resourceArmFrontDoorFirewallPolicyRead(d *schema.ResourceData, meta interface{}) error { + + return nil +} + +func resourceArmFrontDoorFirewallPolicyDelete(d *schema.ResourceData, meta interface{}) error { + + return nil +} From 5f494866ee2e0b4c83a4f98bd4095dbd15c9b257 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 22 Aug 2019 16:57:48 -0700 Subject: [PATCH 51/74] Added link to internal bug tracking casing issue --- azurerm/resource_arm_front_door.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 3fa2f8de36f3..5b9f23c631c4 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -57,6 +57,12 @@ func resourceArmFrontDoor() *schema.Resource { "location": azure.SchemaLocation(), + // Product Backlog Item #: 4642226 Resource id should not be case sensitive + // + // Description: + // Resource Group currently is case sensitive in AFD RP, but it should not be. + // To make it case insentivie, we need to migrate and normalize the existing values in storage. + // Multiple steps are needed to perform this migration. "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), "routing_rule": { From 0f862ca32cf72f433ccc34f779bd3cc866beae20 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 22 Aug 2019 18:44:58 -0700 Subject: [PATCH 52/74] [WIP] Progress --- ...resource_arm_front_door_firewall_policy.go | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index b0a00c997439..1d17d69b93fc 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -8,9 +8,9 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "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/internal/services/frontdoor/helper" //"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" @@ -331,25 +331,16 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta frontendEndpoints := d.Get("frontend_endpoint_ids").([]interface{}) tags := d.Get("tags").(map[string]interface{}) - frontdoorWebApplicationFirewallPolicyProperties := frontdoor.WebApplicationFirewallPolicyProperties {} - frontDoorPolicySettings := frontdoor.PolicySettings { - EnabledState : helper.ConvertToPolicyEnabledStateFromBool(enabled), - Mode: helper.ConvertToPolicyModeFromString(mode), - RedirectURL: utils.String(redirectUrl), - CustomBlockResponseStatusCode: &customBlockResponseStatusCode, - CustomBlockResponseBody: utils.String(customBlockResponseBody), + frontdoorWebApplicationFirewallPolicyProperties := frontdoor.WebApplicationFirewallPolicyProperties{ + PolicySettings: &frontdoor.PolicySettings{ + EnabledState: helper.ConvertToPolicyEnabledStateFromBool(enabled), + Mode: helper.ConvertToPolicyModeFromString(mode), + RedirectURL: utils.String(redirectUrl), + CustomBlockResponseStatusCode: &customBlockResponseStatusCode, + CustomBlockResponseBody: utils.String(customBlockResponseBody), + }, - // Properties: &frontdoor.Properties{ - // FriendlyName: utils.String(friendlyName), - // RoutingRules: expandArmFrontDoorRoutingRule(routingRules, subscriptionId, resourceGroup, name), - // BackendPools: expandArmFrontDoorBackendPools(backendPools, subscriptionId, resourceGroup, name), - // BackendPoolsSettings: expandArmFrontDoorBackendPoolsSettings(backendPoolsSettings), - // FrontendEndpoints: expandArmFrontDoorFrontendEndpoint(frontendEndpoints, subscriptionId, resourceGroup, name), - // HealthProbeSettings: expandArmFrontDoorHealthProbeSettingsModel(healthProbeSettings, subscriptionId, resourceGroup, name), - // LoadBalancingSettings: expandArmFrontDoorLoadBalancingSettingsModel(loadBalancingSettings, subscriptionId, resourceGroup, name), - // EnabledState: expandArmFrontDoorEnabledState(enabledState), - // }, - //Tags: expandTags(tags), + Tags: expandTags(tags), } return nil From 3ed1561bb7819f646a403da50e267c5c6181cd0a Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 23 Aug 2019 18:25:45 -0700 Subject: [PATCH 53/74] gofmt --- azurerm/resource_arm_front_door.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azurerm/resource_arm_front_door.go b/azurerm/resource_arm_front_door.go index 5b9f23c631c4..01c83bb8af36 100644 --- a/azurerm/resource_arm_front_door.go +++ b/azurerm/resource_arm_front_door.go @@ -60,9 +60,9 @@ func resourceArmFrontDoor() *schema.Resource { // Product Backlog Item #: 4642226 Resource id should not be case sensitive // // Description: - // Resource Group currently is case sensitive in AFD RP, but it should not be. + // Resource Group currently is case sensitive in AFD RP, but it should not be. // To make it case insentivie, we need to migrate and normalize the existing values in storage. - // Multiple steps are needed to perform this migration. + // Multiple steps are needed to perform this migration. "resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(), "routing_rule": { From d75b8a2e8b4ed5fa2b030f1338f4c9c1ac72d798 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 29 Aug 2019 17:55:54 -0700 Subject: [PATCH 54/74] [PIP] More progress --- azurerm/internal/services/frontdoor/validate/validate.go | 7 +++++++ azurerm/resource_arm_front_door_firewall_policy.go | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/azurerm/internal/services/frontdoor/validate/validate.go b/azurerm/internal/services/frontdoor/validate/validate.go index f09f66894f6a..389985d299d5 100644 --- a/azurerm/internal/services/frontdoor/validate/validate.go +++ b/azurerm/internal/services/frontdoor/validate/validate.go @@ -26,6 +26,13 @@ func BackendPoolRoutingRuleName(i interface{}, k string) (_ []string, errors []e return nil, errors } +func CustomResponseBody(i interface{}, k string) (_ []string, errors []error) { + if m, regexErrs := validate.RegExHelper(i, k, `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`); !m { + errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must contain only alphanumeric and equals sign characters.`, k)) + } + CustomBlockResponseBody + return nil, errors +} func FrontdoorSettings(d *schema.ResourceDiff) error { routingRules := d.Get("routing_rule").([]interface{}) configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 1d17d69b93fc..5a90f9e9ecd3 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -71,7 +71,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "custom_block_response_body": { Type: schema.TypeString, Optional: true, - ValidateFunc: validate.NoEmptyStrings, + ValidateFunc: validate.CustomBlockResponseBody, }, "custom_rule": { From 0a8a9e9855cec02260ac8c0005944e26c195c551 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 5 Sep 2019 19:03:49 -0700 Subject: [PATCH 55/74] [WIP] WAF progress for today --- .../services/frontdoor/validate/validate.go | 21 ++- ...resource_arm_front_door_firewall_policy.go | 137 ++++++++++++++++-- 2 files changed, 142 insertions(+), 16 deletions(-) diff --git a/azurerm/internal/services/frontdoor/validate/validate.go b/azurerm/internal/services/frontdoor/validate/validate.go index 389985d299d5..08a37f03ce28 100644 --- a/azurerm/internal/services/frontdoor/validate/validate.go +++ b/azurerm/internal/services/frontdoor/validate/validate.go @@ -2,6 +2,7 @@ package validate import ( "fmt" + "strings" "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" "github.com/hashicorp/terraform/helper/schema" @@ -26,11 +27,11 @@ func BackendPoolRoutingRuleName(i interface{}, k string) (_ []string, errors []e return nil, errors } -func CustomResponseBody(i interface{}, k string) (_ []string, errors []error) { +func CustomBlockResponseBody(i interface{}, k string) (_ []string, errors []error) { if m, regexErrs := validate.RegExHelper(i, k, `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`); !m { - errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must contain only alphanumeric and equals sign characters.`, k)) + errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must be a valid base64 string.`, k)) } - CustomBlockResponseBody + return nil, errors } func FrontdoorSettings(d *schema.ResourceDiff) error { @@ -177,3 +178,17 @@ func FrontdoorSettings(d *schema.ResourceDiff) error { return nil } + +// NoEmptyStrings validates that the string is not just whitespace characters (equal to [\r\n\t\f\v ]) +func NoEmptyStrings(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %q to be string", k)} + } + + if strings.TrimSpace(v) == "" { + return nil, []error{fmt.Errorf("%q must not be empty", k)} + } + + return nil, nil +} \ No newline at end of file diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 5a90f9e9ecd3..24441a2636d8 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -10,9 +10,8 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "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/internal/services/frontdoor/helper" - //"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -58,8 +57,9 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, "custom_block_response_status_code": { - Type: schema.TypeInt, - Optional: true, + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validate.CustomBlockResponseBody, }, "redirect_url": { @@ -331,19 +331,42 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta frontendEndpoints := d.Get("frontend_endpoint_ids").([]interface{}) tags := d.Get("tags").(map[string]interface{}) - frontdoorWebApplicationFirewallPolicyProperties := frontdoor.WebApplicationFirewallPolicyProperties{ - PolicySettings: &frontdoor.PolicySettings{ - EnabledState: helper.ConvertToPolicyEnabledStateFromBool(enabled), - Mode: helper.ConvertToPolicyModeFromString(mode), - RedirectURL: utils.String(redirectUrl), - CustomBlockResponseStatusCode: &customBlockResponseStatusCode, - CustomBlockResponseBody: utils.String(customBlockResponseBody), + frontdoorWebApplicationFirewallPolicy := frontdoor.WebApplicationFirewallPolicy{ + Name: utils.String(name), + Location: utils.String(location), + WebApplicationFirewallPolicyProperties: &frontdoor.WebApplicationFirewallPolicyProperties{ + PolicySettings: &frontdoor.PolicySettings{ + EnabledState: helper.ConvertToPolicyEnabledStateFromBool(enabled), + Mode: helper.ConvertToPolicyModeFromString(mode), + RedirectURL: utils.String(redirectUrl), + CustomBlockResponseStatusCode: &customBlockResponseStatusCode, + CustomBlockResponseBody: utils.String(customBlockResponseBody), + }, + customRules: expandArmFrontDoorFirewallCustomRules(customRules), + ManagedRules: expandArmFrontDoorFirewallManagedRules(managedRules), + FrontendEndpointLinks: expandArmFrontDoorFirewallManagedRules(frontendEndpoints), }, - Tags: expandTags(tags), } - return nil + future, err := client.CreateOrUpdate(ctx, resourceGroup, name, frontdoorWebApplicationFirewallPolicy) + if err != nil { + return fmt.Errorf("Error creating Front Door Firewall policy %q (Resource Group %q): %+v", name, resourceGroup, err) + } + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Error waiting for creation of Front Door Firewall %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + return fmt.Errorf("Error retrieving Front Door Firewall %q (Resource Group %q): %+v", name, resourceGroup, err) + } + if resp.ID == nil { + return fmt.Errorf("Cannot read Front Door Firewall %q (Resource Group %q) ID", name, resourceGroup) + } + d.SetId(*resp.ID) + + return resourceArmFrontDoorFirewallPolicyRead(d, meta) } func resourceArmFrontDoorFirewallPolicyRead(d *schema.ResourceData, meta interface{}) error { @@ -352,6 +375,94 @@ func resourceArmFrontDoorFirewallPolicyRead(d *schema.ResourceData, meta interfa } func resourceArmFrontDoorFirewallPolicyDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontdoor.FrontDoorsPolicyClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + name := id.Path["FrontDoorWebApplicationFirewallPolicies"] + + future, err := client.Delete(ctx, resourceGroup, name) + if err != nil { + if response.WasNotFound(future.Response()) { + return nil + } + return fmt.Errorf("Error deleting Front Door Firewall %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + if !response.WasNotFound(future.Response()) { + return fmt.Errorf("Error waiting for deleting Front Door Firewall %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } return nil } + +func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.CustomRuleList { + //Rules *[]CustomRule `json:"rules,omitempty"` + + if len(input) == 0 { + return nil + } + + output := make([]frontdoor.CustomRule, 0) + + for _, cr := range input { + customRule := cr.(map[string]interface{}) + + name := customRule["name"].(string) + priority := int32(customRule["priority"].(int)) + enabled := customRule["enabled"].(bool) + ruleType := customRule["rule_type"].(string) + rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) + rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) + matchConditions := expandArmFrontDoorFirewallMatchConditions(customRule["rate_limit_duration_in_minutes"].([]interface{})) + action := expandArmFrontDoorFirewallActionType(customRule["action_type"].(string)) + + + + + //Priority := utils.Int32(priority) + //EnabledState: expandArmFrontDoorFirewallCustomRuleEnabledState(enabled), + //RuleType: expandArmFrontDoorFirewallRuleType(ruleType) + } + + + + frontdoor.CustomRuleList { + Rules: *output, + } +} + +func expandArmFrontDoorFirewallCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { + if isEnabled { + return frontdoor.CustomRuleEnabledStateEnabled + } + + return frontdoor.CustomRuleEnabledStateDisabled +} + +func expandArmFrontDoorFirewallRuleType(ruleType string) frontdoor.RuleType { + if ruleType == string(frontdoor.MatchRule) { + return frontdoor.MatchRule + } + + return frontdoor.RateLimitRule +} + +func expandArmFrontDoorFirewallActionType(actionType string) frontdoor.ActionType { + switch actionType { + case string(frontdoor.Allow): + return frontdoor.Allow + case string(frontdoor.Block): + return frontdoor.Block + case string(frontdoor.Log): + return frontdoor.Log + case string(frontdoor.Redirect): + return frontdoor.Redirect + } +} \ No newline at end of file From 9bd74f1953a6e214daf2ba7bba19f12e979549a0 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 6 Sep 2019 16:10:41 -0700 Subject: [PATCH 56/74] [WIP] Progress --- .../services/frontdoor/helper/helper.go | 29 +++++++++++++ ...resource_arm_front_door_firewall_policy.go | 41 +++++++------------ 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper/helper.go b/azurerm/internal/services/frontdoor/helper/helper.go index 01044849d876..270ad8813eac 100644 --- a/azurerm/internal/services/frontdoor/helper/helper.go +++ b/azurerm/internal/services/frontdoor/helper/helper.go @@ -71,6 +71,14 @@ func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabled return frontdoor.PolicyEnabledStateDisabled } +func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { + if isEnabled { + return frontdoor.CustomRuleEnabledStateEnabled + } + + return frontdoor.CustomRuleEnabledStateDisabled +} + func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { if policyMode == "Detection" { return frontdoor.Detection @@ -79,6 +87,27 @@ func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { return frontdoor.Prevention } +func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { + if ruleType == string(frontdoor.MatchRule) { + return frontdoor.MatchRule + } + + return frontdoor.RateLimitRule +} + +func ConvertStringToActionType(actionType string) frontdoor.ActionType { + switch actionType { + case string(frontdoor.Allow): + return frontdoor.Allow + case string(frontdoor.Block): + return frontdoor.Block + case string(frontdoor.Log): + return frontdoor.Log + case string(frontdoor.Redirect): + return frontdoor.Redirect + } +} + func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { return "" diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 24441a2636d8..076e0e4d2173 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -420,15 +420,15 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo ruleType := customRule["rule_type"].(string) rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) - matchConditions := expandArmFrontDoorFirewallMatchConditions(customRule["rate_limit_duration_in_minutes"].([]interface{})) - action := expandArmFrontDoorFirewallActionType(customRule["action_type"].(string)) + matchConditions := expandArmFrontDoorFirewallMatchConditions(customRule["match_condition"].([]interface{})) + action := helper.ConvertStringToActionType(customRule["action_type"].(string)) - //Priority := utils.Int32(priority) - //EnabledState: expandArmFrontDoorFirewallCustomRuleEnabledState(enabled), - //RuleType: expandArmFrontDoorFirewallRuleType(ruleType) + //Priority : utils.Int32(priority), + //EnabledState: helper.ConvertBoolToCustomRuleEnabledState(enabled), + //RuleType: helper.ConvertStringToRuleType(ruleType), } @@ -438,31 +438,20 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo } } -func expandArmFrontDoorFirewallCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { - if isEnabled { - return frontdoor.CustomRuleEnabledStateEnabled +func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor.MatchCondition { + if len(input) == 0 { + return nil } - return frontdoor.CustomRuleEnabledStateDisabled -} + for _, mc := range input { + matchCondition := mc.(map[string]interface{}) -func expandArmFrontDoorFirewallRuleType(ruleType string) frontdoor.RuleType { - if ruleType == string(frontdoor.MatchRule) { - return frontdoor.MatchRule - } + matchVariable := matchCondition["match_variable"].(string) + selector := matchCondition["selector"].(string) + operator := matchCondition["operator"].(string) + negateCondition := helper.ConvertConditionToBool(matchCondition["condition"]) - return frontdoor.RateLimitRule -} -func expandArmFrontDoorFirewallActionType(actionType string) frontdoor.ActionType { - switch actionType { - case string(frontdoor.Allow): - return frontdoor.Allow - case string(frontdoor.Block): - return frontdoor.Block - case string(frontdoor.Log): - return frontdoor.Log - case string(frontdoor.Redirect): - return frontdoor.Redirect } + output := make([]frontdoor.MatchCondition, 0) } \ No newline at end of file From 953998fa43320aca7802ab8ccf82969a0cde4f43 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 9 Sep 2019 15:37:36 -0700 Subject: [PATCH 57/74] [WIP] Clean up from master merge --- azurerm/internal/services/frontdoor/helper.go | 53 +++++ .../services/frontdoor/helper/helper.go | 130 ------------ .../services/frontdoor/validate/validate.go | 194 ------------------ 3 files changed, 53 insertions(+), 324 deletions(-) delete mode 100644 azurerm/internal/services/frontdoor/helper/helper.go delete mode 100644 azurerm/internal/services/frontdoor/validate/validate.go diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 6d95177cb73c..31e5b15e386f 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -148,6 +148,59 @@ func VerifyLoadBalancingAndHealthProbeSettings(backendPools []interface{}, loadB return nil } +func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabledState { + if isEnabled { + return frontdoor.PolicyEnabledStateEnabled + } + + return frontdoor.PolicyEnabledStateDisabled +} + +func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { + if isEnabled { + return frontdoor.CustomRuleEnabledStateEnabled + } + + return frontdoor.CustomRuleEnabledStateDisabled +} + +func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { + if policyMode == "Detection" { + return frontdoor.Detection + } + + return frontdoor.Prevention +} + +func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { + if ruleType == string(frontdoor.MatchRule) { + return frontdoor.MatchRule + } + + return frontdoor.RateLimitRule +} + +func ConvertStringToActionType(actionType string) frontdoor.ActionType { + switch actionType { + case string(frontdoor.Allow): + return frontdoor.Allow + case string(frontdoor.Block): + return frontdoor.Block + case string(frontdoor.Log): + return frontdoor.Log + case string(frontdoor.Redirect): + return frontdoor.Redirect + } +} + +func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { + if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { + return "" + } + + return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName) +} + func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error { for _, configFrontendEndpoint := range configFrontendEndpoints { if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { diff --git a/azurerm/internal/services/frontdoor/helper/helper.go b/azurerm/internal/services/frontdoor/helper/helper.go deleted file mode 100644 index 270ad8813eac..000000000000 --- a/azurerm/internal/services/frontdoor/helper/helper.go +++ /dev/null @@ -1,130 +0,0 @@ -package helper - -import ( - "fmt" - "strings" - - "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" -) - -func DoesBackendPoolExists(backendPoolName string, backendPools []interface{}) error { - if backendPoolName == "" { - return fmt.Errorf(`"backend_pool_name" cannot be empty`) - } - - for _, bps := range backendPools { - backendPool := bps.(map[string]interface{}) - if backendPool["name"].(string) == backendPoolName { - return nil - } - } - - return fmt.Errorf(`unable to locate "backend_pool_name":%q in configuration file`, backendPoolName) -} - -func AzureKeyVaultCertificateHasValues(customHttpsConfiguration map[string]interface{}, MatchAllKeys bool) bool { - certificateSecretName := customHttpsConfiguration["azure_key_vault_certificate_secret_name"] - certificateSecretVersion := customHttpsConfiguration["azure_key_vault_certificate_secret_version"] - certificateVaultId := customHttpsConfiguration["azure_key_vault_certificate_vault_id"] - - if MatchAllKeys { - if strings.TrimSpace(certificateSecretName.(string)) != "" && strings.TrimSpace(certificateSecretVersion.(string)) != "" && strings.TrimSpace(certificateVaultId.(string)) != "" { - return true - } - } else { - if strings.TrimSpace(certificateSecretName.(string)) != "" || strings.TrimSpace(certificateSecretVersion.(string)) != "" || strings.TrimSpace(certificateVaultId.(string)) != "" { - return true - } - } - - return false -} - -func IsFrontDoorFrontendEndpointConfigurable(currentState frontdoor.CustomHTTPSProvisioningState, customHttpsProvisioningEnabled bool, frontendEndpointName string, resourceGroup string) error { - action := "disable" - if customHttpsProvisioningEnabled { - action = "enable" - } - - switch currentState { - case frontdoor.CustomHTTPSProvisioningStateDisabling, frontdoor.CustomHTTPSProvisioningStateEnabling, frontdoor.CustomHTTPSProvisioningStateFailed: - return fmt.Errorf("Unable to %s the Front Door Frontend Endpoint %q (Resource Group %q) Custom Domain HTTPS state because the Frontend Endpoint is currently in the %q state", action, frontendEndpointName, resourceGroup, currentState) - default: - return nil - } -} - -func NormalizeCustomHTTPSProvisioningStateToBool(provisioningState frontdoor.CustomHTTPSProvisioningState) bool { - isEnabled := false - if provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabled || provisioningState == frontdoor.CustomHTTPSProvisioningStateEnabling { - isEnabled = true - } - - return isEnabled -} - -func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabledState { - if isEnabled { - return frontdoor.PolicyEnabledStateEnabled - } - - return frontdoor.PolicyEnabledStateDisabled -} - -func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { - if isEnabled { - return frontdoor.CustomRuleEnabledStateEnabled - } - - return frontdoor.CustomRuleEnabledStateDisabled -} - -func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { - if policyMode == "Detection" { - return frontdoor.Detection - } - - return frontdoor.Prevention -} - -func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { - if ruleType == string(frontdoor.MatchRule) { - return frontdoor.MatchRule - } - - return frontdoor.RateLimitRule -} - -func ConvertStringToActionType(actionType string) frontdoor.ActionType { - switch actionType { - case string(frontdoor.Allow): - return frontdoor.Allow - case string(frontdoor.Block): - return frontdoor.Block - case string(frontdoor.Log): - return frontdoor.Log - case string(frontdoor.Redirect): - return frontdoor.Redirect - } -} - -func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { - if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { - return "" - } - - return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName) -} - -func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { - _, ok := i.(frontdoor.ForwardingConfiguration) - if !ok { - _, ok := i.(frontdoor.RedirectConfiguration) - if !ok { - return "" - } - return "RedirectConfiguration" - } else { - return "ForwardingConfiguration" - } -} diff --git a/azurerm/internal/services/frontdoor/validate/validate.go b/azurerm/internal/services/frontdoor/validate/validate.go deleted file mode 100644 index 08a37f03ce28..000000000000 --- a/azurerm/internal/services/frontdoor/validate/validate.go +++ /dev/null @@ -1,194 +0,0 @@ -package validate - -import ( - "fmt" - "strings" - - "github.com/Azure/azure-sdk-for-go/services/preview/frontdoor/mgmt/2019-04-01/frontdoor" - "github.com/hashicorp/terraform/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/helper" -) - -//Frontdoor name must begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens. -func FrontDoorName(i interface{}, k string) (_ []string, errors []error) { - if m, regexErrs := validate.RegExHelper(i, k, `(^[\da-zA-Z])([-\da-zA-Z]{3,61})([\da-zA-Z]$)`); !m { - errors = append(regexErrs, fmt.Errorf(`%q must be between 5 and 63 characters in length and begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) - } - - return nil, errors -} - -func BackendPoolRoutingRuleName(i interface{}, k string) (_ []string, errors []error) { - if m, regexErrs := validate.RegExHelper(i, k, `(^[\da-zA-Z])([-\da-zA-Z]{1,88})([\da-zA-Z]$)`); !m { - errors = append(regexErrs, fmt.Errorf(`%q must be between 1 and 90 characters in length and begin with a letter or number, end with a letter or number and may contain only letters, numbers or hyphens.`, k)) - } - - return nil, errors -} - -func CustomBlockResponseBody(i interface{}, k string) (_ []string, errors []error) { - if m, regexErrs := validate.RegExHelper(i, k, `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`); !m { - errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must be a valid base64 string.`, k)) - } - - return nil, errors -} -func FrontdoorSettings(d *schema.ResourceDiff) error { - routingRules := d.Get("routing_rule").([]interface{}) - configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) - backendPools := d.Get("backend_pool").([]interface{}) - loadBalancingSettings := d.Get("backend_pool_load_balancing").([]interface{}) - healthProbeSettings := d.Get("backend_pool_health_probe").([]interface{}) - - if len(configFrontendEndpoints) == 0 { - return fmt.Errorf(`"frontend_endpoint": must have at least one "frontend_endpoint" defined, found 0`) - } - - // Loop over all of the Routing Rules and validate that only one type of configuration is defined per Routing Rule - for _, rr := range routingRules { - routingRule := rr.(map[string]interface{}) - routingRuleName := routingRule["name"] - found := false - - redirectConfig := routingRule["redirect_configuration"].([]interface{}) - forwardConfig := routingRule["forwarding_configuration"].([]interface{}) - - // Check 0. validate that at least one routing configuration exists per routing rule - if len(redirectConfig) == 0 && len(forwardConfig) == 0 { - return fmt.Errorf(`"routing_rule":%q is invalid. you must have either a "redirect_configuration" or a "forwarding_configuration" defined for the "routing_rule":%q `, routingRuleName, routingRuleName) - } - - // Check 1. validate that only one configuration type is defined per routing rule - if len(redirectConfig) == 1 && len(forwardConfig) == 1 { - return fmt.Errorf(`"routing_rule":%q is invalid. "redirect_configuration" conflicts with "forwarding_configuration". You can only have one configuration type per each routing rule`, routingRuleName) - } - - // Check 2. routing rule is a forwarding_configuration type make sure the backend_pool_name exists in the configuration file - if len(forwardConfig) > 0 { - fc := forwardConfig[0].(map[string]interface{}) - if err := helper.DoesBackendPoolExists(fc["backend_pool_name"].(string), backendPools); err != nil { - return fmt.Errorf(`"routing_rule":%q is invalid. %+v`, routingRuleName, err) - } - } - - // Check 3. validate that each routing rule frontend_endpoints are actually defined in the resource schema - if routingRuleFrontends := routingRule["frontend_endpoints"].([]interface{}); len(routingRuleFrontends) > 0 { - - for _, routingRuleFrontend := range routingRuleFrontends { - // - //TODO: Refactor to helper function that returns an error - // - // Get the name of the frontend defined in the routing rule - routingRulefrontendName := routingRuleFrontend.(string) - found = false - - // Loop over all of the defined frontend endpoints in the config - // seeing if we find the routing rule frontend in the list - for _, configFrontendEndpoint := range configFrontendEndpoints { - configFrontend := configFrontendEndpoint.(map[string]interface{}) - configFrontendName := configFrontend["name"] - if routingRulefrontendName == configFrontendName { - found = true - break - } - } - - if !found { - return fmt.Errorf(`"routing_rule":%q "frontend_endpoints":%q was not found in the configuration file. verify you have the "frontend_endpoint":%q defined in the configuration file`, routingRuleName, routingRulefrontendName, routingRulefrontendName) - } - } - } else { - return fmt.Errorf(`"routing_rule": %q must have at least one "frontend_endpoints" defined`, routingRuleName) - } - } - - // Verify backend pool load balancing settings and health probe settings are defined in the resource schema - for _, bps := range backendPools { - backendPool := bps.(map[string]interface{}) - backendPoolName := backendPool["name"] - backendPoolLoadBalancingName := backendPool["load_balancing_name"] - backendPoolHealthProbeName := backendPool["health_probe_name"] - found := false - - // Verify backend pool load balancing settings name exists - if len(loadBalancingSettings) > 0 { - for _, lbs := range loadBalancingSettings { - loadBalancing := lbs.(map[string]interface{}) - loadBalancingName := loadBalancing["name"] - - if loadBalancingName == backendPoolLoadBalancingName { - found = true - break - } - } - - if !found { - return fmt.Errorf(`"backend_pool":%q "load_balancing_name":%q was not found in the configuration file. verify you have the "backend_pool_load_balancing":%q defined in the configuration file`, backendPoolName, backendPoolLoadBalancingName, backendPoolLoadBalancingName) - } - } - - found = false - - // Verify health probe settings name exists - if len(healthProbeSettings) > 0 { - for _, hps := range healthProbeSettings { - healthProbe := hps.(map[string]interface{}) - healthProbeName := healthProbe["name"] - - if healthProbeName == backendPoolHealthProbeName { - found = true - break - } - } - - if !found { - return fmt.Errorf(`"backend_pool":%q "health_probe_name":%q was not found in the configuration file. verify you have the "backend_pool_health_probe":%q defined in the configuration file`, backendPoolName, backendPoolHealthProbeName, backendPoolHealthProbeName) - } - } - } - - // Verify frontend endpoints custom https configuration is valid if defined - for _, configFrontendEndpoint := range configFrontendEndpoints { - if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { - FrontendName := configFrontend["name"] - customHttpsEnabled := configFrontend["custom_https_provisioning_enabled"].(bool) - - if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { - if !customHttpsEnabled { - return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid because "custom_https_provisioning_enabled" is set to "false". please remove the "custom_https_configuration" block from the configuration file`, FrontendName) - } - - customHttpsConfiguration := chc[0].(map[string]interface{}) - certificateSource := customHttpsConfiguration["certificate_source"] - if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { - if !helper.AzureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { - return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must have values in the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) - } - } else { - if helper.AzureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { - return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must be removed from the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) - } - } - } else if customHttpsEnabled { - return fmt.Errorf(`"frontend_endpoint":%q configuration is invalid because "custom_https_provisioning_enabled" is set to "true" and the "custom_https_configuration" block is undefined. please add the "custom_https_configuration" block to the configuration file`, FrontendName) - } - } - } - - return nil -} - -// NoEmptyStrings validates that the string is not just whitespace characters (equal to [\r\n\t\f\v ]) -func NoEmptyStrings(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %q to be string", k)} - } - - if strings.TrimSpace(v) == "" { - return nil, []error{fmt.Errorf("%q must not be empty", k)} - } - - return nil, nil -} \ No newline at end of file From 992cb9bc4586cf867fc23cb6f3b43ec4b5bd15ec Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 9 Sep 2019 15:41:49 -0700 Subject: [PATCH 58/74] [WIP] added EOF new line for client --- azurerm/internal/services/frontdoor/client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/internal/services/frontdoor/client.go b/azurerm/internal/services/frontdoor/client.go index ab5e48167ca7..60fee3730207 100644 --- a/azurerm/internal/services/frontdoor/client.go +++ b/azurerm/internal/services/frontdoor/client.go @@ -26,4 +26,4 @@ func BuildClient(o *common.ClientOptions) *Client { FrontDoorsFrontendClient: &frontDoorsFrontendClient, FrontDoorsPolicyClient: &frontDoorsPolicyClient, } -} \ No newline at end of file +} From 6648b22d93205a203aceb34bc208e0c12ea5e46a Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 9 Sep 2019 18:16:10 -0700 Subject: [PATCH 59/74] [WIP] More progress --- azurerm/internal/services/frontdoor/helper.go | 8 ++++ ...resource_arm_front_door_firewall_policy.go | 43 ++++++++++++++----- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 31e5b15e386f..8cde595ab5d1 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -193,6 +193,14 @@ func ConvertStringToActionType(actionType string) frontdoor.ActionType { } } +func ConvertConditionToBool(condition string) bool { + if strings.Contains(strings.ToLower(condition), "not") { + return true + } + + return false +} + func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { return "" diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 76caff885486..9386de9ca81c 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -10,8 +10,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/helper" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor/validate" + afd "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -31,7 +30,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.NoEmptyStrings, + ValidateFunc: validation.NoEmptyStrings, }, "location": { @@ -134,10 +133,10 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { MaxItems: 100, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - // Conflicts with Selector "match_variable": { Type: schema.TypeString, Optional: true, + ConflictsWith: []string{"selector"}, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Cookies), string(frontdoor.PostArgs), @@ -149,10 +148,10 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.RequestURI), }, false), }, - // Conflicts with match variable "selector": { Type: schema.TypeString, Optional: true, + ConflictsWith: []string{"match_variable"}, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Cookies), string(frontdoor.PostArgs), @@ -419,14 +418,14 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) matchConditions := expandArmFrontDoorFirewallMatchConditions(customRule["match_condition"].([]interface{})) - action := helper.ConvertStringToActionType(customRule["action_type"].(string)) + action := afd.ConvertStringToActionType(customRule["action_type"].(string)) //Priority : utils.Int32(priority), - //EnabledState: helper.ConvertBoolToCustomRuleEnabledState(enabled), - //RuleType: helper.ConvertStringToRuleType(ruleType), + //EnabledState: afd.ConvertBoolToCustomRuleEnabledState(enabled), + //RuleType: afd.ConvertStringToRuleType(ruleType), } @@ -441,15 +440,39 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor return nil } + output := make([]frontdoor.MatchCondition, 0) + for _, mc := range input { matchCondition := mc.(map[string]interface{}) matchVariable := matchCondition["match_variable"].(string) selector := matchCondition["selector"].(string) operator := matchCondition["operator"].(string) - negateCondition := helper.ConvertConditionToBool(matchCondition["condition"]) + negateCondition := afd.ConvertConditionToBool(matchCondition["condition"]) + mv := matchCondition["match_value"].([]interface{}) + matchValues := make([]string, 0) + for _, v := range mv { + matchValues = append(matchValues, v.(string)) + } + matchValue := &matchValues + ts := matchCondition["transforms"].([]interface{}) + transform := make([]string, 0) + for _, t := range ts { + transform = append(transform, t.(string)) + } + transforms := &transform + + fdpMatchCondition := frontdoor.MatchCondition { + Operator: operator, + NegateCondition: &negateCondition, + MatchValue: &matchValue, + Transforms: &transforms, + } + + if } - output := make([]frontdoor.MatchCondition, 0) + + return &output } \ No newline at end of file From 50571e9add8c42b7b32aea5ed92628839841497c Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 10 Sep 2019 18:26:52 -0700 Subject: [PATCH 60/74] [WIP] Progress --- azurerm/internal/services/frontdoor/helper.go | 58 ++++++++++----- ...resource_arm_front_door_firewall_policy.go | 72 ++++++++++++------- 2 files changed, 86 insertions(+), 44 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 8cde595ab5d1..6aeb4962ff88 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -148,48 +148,72 @@ func VerifyLoadBalancingAndHealthProbeSettings(backendPools []interface{}, loadB return nil } +func VerifyCustomRules(input []interface{}) error { + if len(input) == 0 { + return nil + } + + for _, cr := range input { + customRule := cr.(map[string]interface{}) + matchConditions := customRule["match_condition"].([]interface{}) + ruleName := customRule["name"] + + for _, mc := range matchConditions { + matchCondition := mc.(map[string]interface{}) + matchVariable := matchCondition["match_variable"].(string) + selector := matchCondition["selector"].(string) + + if matchvariable == "" && selector == "" { + return fmt.Errorf(`"custom_rule":%q is invalid, either "match_variable" or "selector" must be defined`, ruleName) + } + } + } + + return nil +} + func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabledState { if isEnabled { - return frontdoor.PolicyEnabledStateEnabled + return frontdoor.PolicyEnabledStateEnabled } - return frontdoor.PolicyEnabledStateDisabled + return frontdoor.PolicyEnabledStateDisabled } func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { if isEnabled { - return frontdoor.CustomRuleEnabledStateEnabled + return frontdoor.CustomRuleEnabledStateEnabled } - return frontdoor.CustomRuleEnabledStateDisabled + return frontdoor.CustomRuleEnabledStateDisabled } func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { if policyMode == "Detection" { - return frontdoor.Detection + return frontdoor.Detection } - return frontdoor.Prevention + return frontdoor.Prevention } -func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { +func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { if ruleType == string(frontdoor.MatchRule) { - return frontdoor.MatchRule + return frontdoor.MatchRule } - return frontdoor.RateLimitRule + return frontdoor.RateLimitRule } func ConvertStringToActionType(actionType string) frontdoor.ActionType { switch actionType { - case string(frontdoor.Allow): - return frontdoor.Allow - case string(frontdoor.Block): - return frontdoor.Block - case string(frontdoor.Log): - return frontdoor.Log - case string(frontdoor.Redirect): - return frontdoor.Redirect + case string(frontdoor.Allow): + return frontdoor.Allow + case string(frontdoor.Block): + return frontdoor.Block + case string(frontdoor.Log): + return frontdoor.Log + case string(frontdoor.Redirect): + return frontdoor.Redirect } } diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 9386de9ca81c..ce99ed718102 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -134,8 +134,8 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "match_variable": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, ConflictsWith: []string{"selector"}, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Cookies), @@ -149,8 +149,8 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, "selector": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, ConflictsWith: []string{"match_variable"}, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Cookies), @@ -311,7 +311,7 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta resp, err := client.Get(ctx, resourceGroup, name) if err != nil { if !utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Error checking for present of existing Front Door %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("Error checking for present of existing Front Door Firewall Policy %q (Resource Group %q): %+v", name, resourceGroup, err) } } if !utils.ResponseWasNotFound(resp.Response) { @@ -330,6 +330,10 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta frontendEndpoints := d.Get("frontend_endpoint_ids").([]interface{}) tags := d.Get("tags").(map[string]interface{}) + if err := afd.VerifyCustomRules(customRules); err != nil { + return fmt.Errorf(`Error validating "custom_rule" for Front Door Firewall Policy %q (Resource Group %q): %+v`, name, resourceGroup, err) + } + frontdoorWebApplicationFirewallPolicy := frontdoor.WebApplicationFirewallPolicy{ Name: utils.String(name), Location: utils.String(location), @@ -416,23 +420,28 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo enabled := customRule["enabled"].(bool) ruleType := customRule["rule_type"].(string) rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) - rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) + rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) matchConditions := expandArmFrontDoorFirewallMatchConditions(customRule["match_condition"].([]interface{})) - action := afd.ConvertStringToActionType(customRule["action_type"].(string)) - - - - - //Priority : utils.Int32(priority), - //EnabledState: afd.ConvertBoolToCustomRuleEnabledState(enabled), - //RuleType: afd.ConvertStringToRuleType(ruleType), + action := customRule["action_type"].(string) + + afpCustomRule = frontdoor.CustomRule{ + Name: utils.String(name), + Priority: utils.Int32(priority), + EnabledState: afd.ConvertBoolToCustomRuleEnabledState(enabled), + RuleType: afd.ConvertStringToRuleType(ruleType), + RateLimitDurationInMinutes: utils.Int32(rateLimitDurationInMinutes), + RateLimitThreshold: utils.Int32(rateLimitThreshold), + MatchConditions: expandArmFrontDoorFirewallMatchConditions(matchConditions), + Action: afd.ConvertStringToActionType(action), + } + output = append(output, afpCustomRule) } + result := frontdoor.CustomRuleList{ + Rules: &output, + } - - frontdoor.CustomRuleList { - Rules: *output, - } + return &result } func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor.MatchCondition { @@ -444,11 +453,10 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor for _, mc := range input { matchCondition := mc.(map[string]interface{}) - matchVariable := matchCondition["match_variable"].(string) selector := matchCondition["selector"].(string) operator := matchCondition["operator"].(string) - negateCondition := afd.ConvertConditionToBool(matchCondition["condition"]) + negateCondition := afd.ConvertConditionToBool(matchCondition["condition"]) mv := matchCondition["match_value"].([]interface{}) matchValues := make([]string, 0) @@ -464,15 +472,25 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor } transforms := &transform - fdpMatchCondition := frontdoor.MatchCondition { - Operator: operator, + fdpMatchCondition := &frontdoor.MatchCondition{ + Operator: operator, NegateCondition: &negateCondition, - MatchValue: &matchValue, - Transforms: &transforms, + MatchValue: &matchValue, + Transforms: &transforms, + } + + if matchvariable != "" { + fdpMatchCondition.MatchVariable = matchVariable + } else { + fdpMatchCondition.Selector = utils.String(selector) } - if + output = append(output, fdpMatchCondition) } - + return &output -} \ No newline at end of file +} + +func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.ManagedRuleSetList { + +} From 7b95660b19f935308055183169c4c4c186ad6870 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Tue, 10 Sep 2019 19:50:35 -0700 Subject: [PATCH 61/74] [WIP] Progress --- azurerm/internal/services/frontdoor/helper.go | 58 ++++++++++++++++++- .../internal/services/frontdoor/validate.go | 8 +++ ...resource_arm_front_door_firewall_policy.go | 45 +++++++------- 3 files changed, 90 insertions(+), 21 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 6aeb4962ff88..739865498222 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -163,7 +163,7 @@ func VerifyCustomRules(input []interface{}) error { matchVariable := matchCondition["match_variable"].(string) selector := matchCondition["selector"].(string) - if matchvariable == "" && selector == "" { + if matchVariable == "" && selector == "" { return fmt.Errorf(`"custom_rule":%q is invalid, either "match_variable" or "selector" must be defined`, ruleName) } } @@ -204,6 +204,60 @@ func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { return frontdoor.RateLimitRule } +func ConvertStringToMatchVariable(matchVariable string) frontdoor.MatchVariable { + switch matchVariable { + case "Cookies": + return frontdoor.Cookies + case "PostArgs": + return frontdoor.PostArgs + case "QueryString": + return frontdoor.QueryString + case "RemoteAddr": + return frontdoor.RemoteAddr + case "RequestBody": + return frontdoor.RequestBody + case "RequestHeader": + return frontdoor.RequestHeader + case "RequestMethod": + return frontdoor.RequestMethod + case "RequestUri": + return frontdoor.RequestURI + default: + return frontdoor.RequestHeader + } +} + +func ConvertStringToOperator(operator string) frontdoor.Operator { + switch operator { + case "Any": + return frontdoor.Any + case "BeginsWith": + return frontdoor.BeginsWith + case "Contains": + return frontdoor.Contains + case "EndsWith": + return frontdoor.EndsWith + case "Equal": + return frontdoor.Equal + case "GeoMatch": + return frontdoor.GeoMatch + case "GreaterThan": + return frontdoor.GreaterThan + case "GreaterThanOrEqual": + return frontdoor.GreaterThanOrEqual + case "IPMatch": + return frontdoor.IPMatch + case "LessThan": + return frontdoor.LessThan + case "LessThanOrEqual": + return frontdoor.LessThanOrEqual + case "RegEx": + return frontdoor.RegEx + default: + return frontdoor.Any + } +} + func ConvertStringToActionType(actionType string) frontdoor.ActionType { switch actionType { case string(frontdoor.Allow): @@ -214,6 +268,8 @@ func ConvertStringToActionType(actionType string) frontdoor.ActionType { return frontdoor.Log case string(frontdoor.Redirect): return frontdoor.Redirect + default: + return frontdoor.Block } } diff --git a/azurerm/internal/services/frontdoor/validate.go b/azurerm/internal/services/frontdoor/validate.go index 3f24097840f7..59ea4a779f45 100644 --- a/azurerm/internal/services/frontdoor/validate.go +++ b/azurerm/internal/services/frontdoor/validate.go @@ -23,6 +23,14 @@ func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, er return nil, errors } +func ValidateCustomBlockResponseBody(i interface{}, k string) (_ []string, errors []error) { + if m, regexErrs := validate.RegExHelper(i, k, `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`); !m { + errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must contain only alphanumeric and equals sign characters.`, k)) + } + + return nil, errors +} + func ValidateFrontdoorSettings(d *schema.ResourceDiff) error { routingRules := d.Get("routing_rule").([]interface{}) configFrontendEndpoints := d.Get("frontend_endpoint").([]interface{}) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index ce99ed718102..cceb162ca8c8 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -10,6 +10,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" afd "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -30,7 +31,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validation.NoEmptyStrings, + ValidateFunc: validate.NoEmptyStrings, }, "location": { @@ -55,22 +56,22 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, - "custom_block_response_status_code": { - Type: schema.TypeInt, - Optional: true, - ValidateFunc: validate.CustomBlockResponseBody, - }, - "redirect_url": { Type: schema.TypeString, Optional: true, ValidateFunc: validate.NoEmptyStrings, }, + "custom_block_response_status_code": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(100, 530), + }, + "custom_block_response_body": { Type: schema.TypeString, Optional: true, - ValidateFunc: validate.CustomBlockResponseBody, + ValidateFunc: afd.ValidateCustomBlockResponseBody, }, "custom_rule": { @@ -339,15 +340,15 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta Location: utils.String(location), WebApplicationFirewallPolicyProperties: &frontdoor.WebApplicationFirewallPolicyProperties{ PolicySettings: &frontdoor.PolicySettings{ - EnabledState: helper.ConvertToPolicyEnabledStateFromBool(enabled), - Mode: helper.ConvertToPolicyModeFromString(mode), + EnabledState: afd.ConvertToPolicyEnabledStateFromBool(enabled), + Mode: afd.ConvertToPolicyModeFromString(mode), RedirectURL: utils.String(redirectUrl), CustomBlockResponseStatusCode: &customBlockResponseStatusCode, CustomBlockResponseBody: utils.String(customBlockResponseBody), }, - customRules: expandArmFrontDoorFirewallCustomRules(customRules), + CustomRules: expandArmFrontDoorFirewallCustomRules(customRules), ManagedRules: expandArmFrontDoorFirewallManagedRules(managedRules), - FrontendEndpointLinks: expandArmFrontDoorFirewallManagedRules(frontendEndpoints), + FrontendEndpointLinks: expandArmFrontDoorFirewallFrontendEndpointLinks(frontendEndpoints), }, Tags: expandTags(tags), } @@ -421,10 +422,10 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo ruleType := customRule["rule_type"].(string) rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) - matchConditions := expandArmFrontDoorFirewallMatchConditions(customRule["match_condition"].([]interface{})) + matchConditions := customRule["match_condition"].([]interface{}) action := customRule["action_type"].(string) - afpCustomRule = frontdoor.CustomRule{ + afpCustomRule := frontdoor.CustomRule{ Name: utils.String(name), Priority: utils.Int32(priority), EnabledState: afd.ConvertBoolToCustomRuleEnabledState(enabled), @@ -455,8 +456,8 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor matchCondition := mc.(map[string]interface{}) matchVariable := matchCondition["match_variable"].(string) selector := matchCondition["selector"].(string) - operator := matchCondition["operator"].(string) - negateCondition := afd.ConvertConditionToBool(matchCondition["condition"]) + operator := afd.ConvertStringToOperator(matchCondition["operator"].(string)) + negateCondition := afd.ConvertConditionToBool(matchCondition["condition"].(string)) mv := matchCondition["match_value"].([]interface{}) matchValues := make([]string, 0) @@ -475,12 +476,12 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor fdpMatchCondition := &frontdoor.MatchCondition{ Operator: operator, NegateCondition: &negateCondition, - MatchValue: &matchValue, - Transforms: &transforms, + MatchValue: matchValue, + Transforms: transforms, } - if matchvariable != "" { - fdpMatchCondition.MatchVariable = matchVariable + if matchVariable != "" { + fdpMatchCondition.MatchVariable = afd.ConvertStringToMatchVariable(matchVariable) } else { fdpMatchCondition.Selector = utils.String(selector) } @@ -494,3 +495,7 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.ManagedRuleSetList { } + +func expandArmFrontDoorFirewallFrontendEndpointLinks(input []interface{}) *[]frontdoor.FrontendEnpointLink { + +} \ No newline at end of file From 4e57a4ed455fb6d37df26f5abddfeb6502a123de Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 11 Sep 2019 12:52:49 -0700 Subject: [PATCH 62/74] [WIP] Working prototype create only --- azurerm/internal/services/frontdoor/helper.go | 157 ++++-------------- ...resource_arm_front_door_firewall_policy.go | 20 ++- 2 files changed, 44 insertions(+), 133 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 739865498222..610a827fabd0 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -75,6 +75,7 @@ func GetFrontDoorBasicRouteConfigurationType(i interface{}) string { return "ForwardingConfiguration" } } + func VerifyRoutingRuleFrontendEndpoints(routingRuleFrontends []interface{}, configFrontendEndpoints []interface{}) error { for _, routingRuleFrontend := range routingRuleFrontends { // Get the name of the frontend defined in the routing rule @@ -148,6 +149,38 @@ func VerifyLoadBalancingAndHealthProbeSettings(backendPools []interface{}, loadB return nil } + +func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error { + for _, configFrontendEndpoint := range configFrontendEndpoints { + if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { + FrontendName := configFrontend["name"] + customHttpsEnabled := configFrontend["custom_https_provisioning_enabled"].(bool) + + if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { + if !customHttpsEnabled { + return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid because "custom_https_provisioning_enabled" is set to "false". please remove the "custom_https_configuration" block from the configuration file`, FrontendName) + } + + customHttpsConfiguration := chc[0].(map[string]interface{}) + certificateSource := customHttpsConfiguration["certificate_source"] + if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { + if !AzureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { + return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must have values in the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) + } + } else { + if AzureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { + return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must be removed from the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) + } + } + } else if customHttpsEnabled { + return fmt.Errorf(`"frontend_endpoint":%q configuration is invalid because "custom_https_provisioning_enabled" is set to "true" and the "custom_https_configuration" block is undefined. please add the "custom_https_configuration" block to the configuration file`, FrontendName) + } + } + } + + return nil +} + func VerifyCustomRules(input []interface{}) error { if len(input) == 0 { return nil @@ -188,91 +221,6 @@ func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEna return frontdoor.CustomRuleEnabledStateDisabled } -func ConvertToPolicyModeFromString(policyMode string) frontdoor.PolicyMode { - if policyMode == "Detection" { - return frontdoor.Detection - } - - return frontdoor.Prevention -} - -func ConvertStringToRuleType(ruleType string) frontdoor.RuleType { - if ruleType == string(frontdoor.MatchRule) { - return frontdoor.MatchRule - } - - return frontdoor.RateLimitRule -} - -func ConvertStringToMatchVariable(matchVariable string) frontdoor.MatchVariable { - switch matchVariable { - case "Cookies": - return frontdoor.Cookies - case "PostArgs": - return frontdoor.PostArgs - case "QueryString": - return frontdoor.QueryString - case "RemoteAddr": - return frontdoor.RemoteAddr - case "RequestBody": - return frontdoor.RequestBody - case "RequestHeader": - return frontdoor.RequestHeader - case "RequestMethod": - return frontdoor.RequestMethod - case "RequestUri": - return frontdoor.RequestURI - default: - return frontdoor.RequestHeader - } -} - -func ConvertStringToOperator(operator string) frontdoor.Operator { - switch operator { - case "Any": - return frontdoor.Any - case "BeginsWith": - return frontdoor.BeginsWith - case "Contains": - return frontdoor.Contains - case "EndsWith": - return frontdoor.EndsWith - case "Equal": - return frontdoor.Equal - case "GeoMatch": - return frontdoor.GeoMatch - case "GreaterThan": - return frontdoor.GreaterThan - case "GreaterThanOrEqual": - return frontdoor.GreaterThanOrEqual - case "IPMatch": - return frontdoor.IPMatch - case "LessThan": - return frontdoor.LessThan - case "LessThanOrEqual": - return frontdoor.LessThanOrEqual - case "RegEx": - return frontdoor.RegEx - default: - return frontdoor.Any - } -} - -func ConvertStringToActionType(actionType string) frontdoor.ActionType { - switch actionType { - case string(frontdoor.Allow): - return frontdoor.Allow - case string(frontdoor.Block): - return frontdoor.Block - case string(frontdoor.Log): - return frontdoor.Log - case string(frontdoor.Redirect): - return frontdoor.Redirect - default: - return frontdoor.Block - } -} - func ConvertConditionToBool(condition string) bool { if strings.Contains(strings.ToLower(condition), "not") { return true @@ -280,42 +228,3 @@ func ConvertConditionToBool(condition string) bool { return false } - -func GetFrontDoorSubResourceId(subscriptionId string, resourceGroup string, frontDoorName string, resourceType string, resourceName string) string { - if strings.TrimSpace(subscriptionId) == "" || strings.TrimSpace(resourceGroup) == "" || strings.TrimSpace(frontDoorName) == "" || strings.TrimSpace(resourceType) == "" || strings.TrimSpace(resourceName) == "" { - return "" - } - - return fmt.Sprintf("/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/Frontdoors/%s/%s/%s", subscriptionId, resourceGroup, frontDoorName, resourceType, resourceName) -} - -func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error { - for _, configFrontendEndpoint := range configFrontendEndpoints { - if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { - FrontendName := configFrontend["name"] - customHttpsEnabled := configFrontend["custom_https_provisioning_enabled"].(bool) - - if chc := configFrontend["custom_https_configuration"].([]interface{}); len(chc) > 0 { - if !customHttpsEnabled { - return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid because "custom_https_provisioning_enabled" is set to "false". please remove the "custom_https_configuration" block from the configuration file`, FrontendName) - } - - customHttpsConfiguration := chc[0].(map[string]interface{}) - certificateSource := customHttpsConfiguration["certificate_source"] - if certificateSource == string(frontdoor.CertificateSourceAzureKeyVault) { - if !AzureKeyVaultCertificateHasValues(customHttpsConfiguration, true) { - return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must have values in the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) - } - } else { - if AzureKeyVaultCertificateHasValues(customHttpsConfiguration, false) { - return fmt.Errorf(`"frontend_endpoint":%q "custom_https_configuration" is invalid, all of the following keys must be removed from the "custom_https_configuration" block: "azure_key_vault_certificate_secret_name", "azure_key_vault_certificate_secret_version", and "azure_key_vault_certificate_vault_id"`, FrontendName) - } - } - } else if customHttpsEnabled { - return fmt.Errorf(`"frontend_endpoint":%q configuration is invalid because "custom_https_provisioning_enabled" is set to "true" and the "custom_https_configuration" block is undefined. please add the "custom_https_configuration" block to the configuration file`, FrontendName) - } - } - } - - return nil -} diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index cceb162ca8c8..63bb8fc1f7a2 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -341,7 +341,7 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta WebApplicationFirewallPolicyProperties: &frontdoor.WebApplicationFirewallPolicyProperties{ PolicySettings: &frontdoor.PolicySettings{ EnabledState: afd.ConvertToPolicyEnabledStateFromBool(enabled), - Mode: afd.ConvertToPolicyModeFromString(mode), + Mode: frontdoor.PolicyMode(mode), RedirectURL: utils.String(redirectUrl), CustomBlockResponseStatusCode: &customBlockResponseStatusCode, CustomBlockResponseBody: utils.String(customBlockResponseBody), @@ -429,11 +429,11 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo Name: utils.String(name), Priority: utils.Int32(priority), EnabledState: afd.ConvertBoolToCustomRuleEnabledState(enabled), - RuleType: afd.ConvertStringToRuleType(ruleType), + RuleType: frontdoor.RuleType(ruleType), RateLimitDurationInMinutes: utils.Int32(rateLimitDurationInMinutes), RateLimitThreshold: utils.Int32(rateLimitThreshold), MatchConditions: expandArmFrontDoorFirewallMatchConditions(matchConditions), - Action: afd.ConvertStringToActionType(action), + Action: frontdoor.ActionType(action), } output = append(output, afpCustomRule) } @@ -456,7 +456,7 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor matchCondition := mc.(map[string]interface{}) matchVariable := matchCondition["match_variable"].(string) selector := matchCondition["selector"].(string) - operator := afd.ConvertStringToOperator(matchCondition["operator"].(string)) + operator := frontdoor.Operator(matchCondition["operator"].(string)) negateCondition := afd.ConvertConditionToBool(matchCondition["condition"].(string)) mv := matchCondition["match_value"].([]interface{}) @@ -467,13 +467,13 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor matchValue := &matchValues ts := matchCondition["transforms"].([]interface{}) - transform := make([]string, 0) + transform := make([]frontdoor.TransformType, 0) for _, t := range ts { - transform = append(transform, t.(string)) + transform = append(transform, frontdoor.TransformType(t.(string))) } transforms := &transform - fdpMatchCondition := &frontdoor.MatchCondition{ + fdpMatchCondition := frontdoor.MatchCondition{ Operator: operator, NegateCondition: &negateCondition, MatchValue: matchValue, @@ -481,7 +481,7 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor } if matchVariable != "" { - fdpMatchCondition.MatchVariable = afd.ConvertStringToMatchVariable(matchVariable) + fdpMatchCondition.MatchVariable = frontdoor.MatchVariable(matchVariable) } else { fdpMatchCondition.Selector = utils.String(selector) } @@ -494,8 +494,10 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.ManagedRuleSetList { + return nil } -func expandArmFrontDoorFirewallFrontendEndpointLinks(input []interface{}) *[]frontdoor.FrontendEnpointLink { +func expandArmFrontDoorFirewallFrontendEndpointLinks(input []interface{}) *[]frontdoor.FrontendEndpointLink { + return nil } \ No newline at end of file From 6b06026f7c0851f5e86fb330d1829961e5d8405d Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Wed, 11 Sep 2019 19:02:22 -0700 Subject: [PATCH 63/74] [WIP] Update for negation_condition --- azurerm/internal/services/frontdoor/helper.go | 33 +---- ...resource_arm_front_door_firewall_policy.go | 120 +++++++++++++----- 2 files changed, 95 insertions(+), 58 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 610a827fabd0..d161a7d82e04 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -149,7 +149,6 @@ func VerifyLoadBalancingAndHealthProbeSettings(backendPools []interface{}, loadB return nil } - func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error { for _, configFrontendEndpoint := range configFrontendEndpoints { if configFrontend := configFrontendEndpoint.(map[string]interface{}); len(configFrontend) > 0 { @@ -181,30 +180,6 @@ func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error return nil } -func VerifyCustomRules(input []interface{}) error { - if len(input) == 0 { - return nil - } - - for _, cr := range input { - customRule := cr.(map[string]interface{}) - matchConditions := customRule["match_condition"].([]interface{}) - ruleName := customRule["name"] - - for _, mc := range matchConditions { - matchCondition := mc.(map[string]interface{}) - matchVariable := matchCondition["match_variable"].(string) - selector := matchCondition["selector"].(string) - - if matchVariable == "" && selector == "" { - return fmt.Errorf(`"custom_rule":%q is invalid, either "match_variable" or "selector" must be defined`, ruleName) - } - } - } - - return nil -} - func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabledState { if isEnabled { return frontdoor.PolicyEnabledStateEnabled @@ -221,10 +196,10 @@ func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEna return frontdoor.CustomRuleEnabledStateDisabled } -func ConvertConditionToBool(condition string) bool { - if strings.Contains(strings.ToLower(condition), "not") { - return true +func ConvertBoolToManagedRuleEnabledState(isEnabled bool) frontdoor.ManagedRuleEnabledState { + if isEnabled { + return frontdoor.ManagedRuleEnabledStateEnabled } - return false + return frontdoor.ManagedRuleEnabledStateDisabled } diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 63bb8fc1f7a2..a6a1179a9239 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -135,9 +135,8 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "match_variable": { - Type: schema.TypeString, - Optional: true, - ConflictsWith: []string{"selector"}, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Cookies), string(frontdoor.PostArgs), @@ -150,15 +149,9 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, "selector": { - Type: schema.TypeString, - Optional: true, - ConflictsWith: []string{"match_variable"}, - ValidateFunc: validation.StringInSlice([]string{ - string(frontdoor.Cookies), - string(frontdoor.PostArgs), - string(frontdoor.QueryString), - string(frontdoor.RequestHeader), - }, false), + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, }, "operator": { Type: schema.TypeString, @@ -178,16 +171,10 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.RegEx), }, false), }, - "condition": { - Type: schema.TypeString, + "negation_condition": { + Type: schema.TypeBool, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - "Is", - "Is Not", - "Contains", - "Not Contains", - }, false), - Default: "Is", + Default: false, }, "match_value": { Type: schema.TypeList, @@ -323,8 +310,8 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta location := azure.NormalizeLocation("Global") enabled := d.Get("enabled").(bool) mode := d.Get("mode").(string) - redirectUrl := d.Get("redirect_url ").(string) - customBlockResponseStatusCode := d.Get("custom_block_response_status_code").(int32) + redirectUrl := d.Get("redirect_url").(string) + customBlockResponseStatusCode := d.Get("custom_block_response_status_code").(int) customBlockResponseBody := d.Get("custom_block_response_body").(string) customRules := d.Get("custom_rule").([]interface{}) managedRules := d.Get("managed_rule").([]interface{}) @@ -343,7 +330,7 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta EnabledState: afd.ConvertToPolicyEnabledStateFromBool(enabled), Mode: frontdoor.PolicyMode(mode), RedirectURL: utils.String(redirectUrl), - CustomBlockResponseStatusCode: &customBlockResponseStatusCode, + CustomBlockResponseStatusCode: utils.Int32(int32(customBlockResponseStatusCode)), CustomBlockResponseBody: utils.String(customBlockResponseBody), }, CustomRules: expandArmFrontDoorFirewallCustomRules(customRules), @@ -423,7 +410,7 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) matchConditions := customRule["match_condition"].([]interface{}) - action := customRule["action_type"].(string) + action := customRule["action"].(string) afpCustomRule := frontdoor.CustomRule{ Name: utils.String(name), @@ -457,7 +444,7 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor matchVariable := matchCondition["match_variable"].(string) selector := matchCondition["selector"].(string) operator := frontdoor.Operator(matchCondition["operator"].(string)) - negateCondition := afd.ConvertConditionToBool(matchCondition["condition"].(string)) + negateCondition := matchCondition["negation_condition"].(bool) mv := matchCondition["match_value"].([]interface{}) matchValues := make([]string, 0) @@ -493,11 +480,86 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor } func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.ManagedRuleSetList { + if len(input) == 0 { + return nil + } - return nil + managedRuleSetList := make([]frontdoor.ManagedRuleSet, 0) + + for _, mr := range input { + managedRule := mr.(map[string]interface{}) + + ruleType := managedRule["type"].(string) + version := managedRule["version"].(string) + overrides := managedRule["override"].([]interface{}) + + managedRuleSet := frontdoor.ManagedRuleSet{ + RuleSetType: utils.String(ruleType), + RuleSetVersion: utils.String(version), + //RuleGroupOverrides: *[]ManagedRuleGroupOverride + } + + if len(overrides) > 0 { + for _, o := range overrides { + override := o.(map[string]interface{}) + + ruleGroupName := override["rule_group_name"].(string) + rules := override["rule"].([]interface{}) + + managedRuleGroupOverride := frontdoor.ManagedRuleGroupOverride{ + RuleGroupName: utils.String(ruleGroupName), + //Rules: *[]ManagedRuleOverride + } + + if len(rules) > 0 { + managedRuleOverrides := make([]frontdoor.ManagedRuleOverride, 0) + + for _, r := range rules { + rule := r.(map[string]interface{}) + + ruleId := rule["rule_id"].(string) + enabled := rule["enabled"].(bool) + action := rule["action"].(string) + + managedRuleOverride := frontdoor.ManagedRuleOverride{ + RuleID: utils.String(ruleId), + EnabledState: afd.ConvertBoolToManagedRuleEnabledState(enabled), + Action: frontdoor.ActionType(action), + } + + managedRuleOverrides = append(managedRuleOverrides, managedRuleOverride) + } + + managedRuleGroupOverride.Rules = &managedRuleOverrides + } + } + + // Done processing overrides now add them to the managed rule set array + managedRuleSetList = append(managedRuleSetList, managedRuleSet) + } + } + + output := frontdoor.ManagedRuleSetList{ + ManagedRuleSets: &managedRuleSetList, + } + + return &output } func expandArmFrontDoorFirewallFrontendEndpointLinks(input []interface{}) *[]frontdoor.FrontendEndpointLink { + if len(input) == 0 { + return nil + } - return nil -} \ No newline at end of file + frontendEndpointLinks := make([]frontdoor.FrontendEndpointLink, 0) + + for _, frontendEndpointLink := range input { + fel := frontdoor.FrontendEndpointLink{ + ID: utils.String(frontendEndpointLink.(string)), + } + + frontendEndpointLinks = append(frontendEndpointLinks, fel) + } + + return &frontendEndpointLinks +} From 22fb9c572e513ae97ae36871d31f483cced9fca5 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 12 Sep 2019 14:45:23 -0700 Subject: [PATCH 64/74] [WIP] Fully functioning Create --- azurerm/resource_arm_front_door_firewall_policy.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index a6a1179a9239..e87c27670959 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -318,10 +318,6 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta frontendEndpoints := d.Get("frontend_endpoint_ids").([]interface{}) tags := d.Get("tags").(map[string]interface{}) - if err := afd.VerifyCustomRules(customRules); err != nil { - return fmt.Errorf(`Error validating "custom_rule" for Front Door Firewall Policy %q (Resource Group %q): %+v`, name, resourceGroup, err) - } - frontdoorWebApplicationFirewallPolicy := frontdoor.WebApplicationFirewallPolicy{ Name: utils.String(name), Location: utils.String(location), @@ -469,7 +465,8 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor if matchVariable != "" { fdpMatchCondition.MatchVariable = frontdoor.MatchVariable(matchVariable) - } else { + } + if selector != "" { fdpMatchCondition.Selector = utils.String(selector) } From d2b16e48526cb300cb8b03ddf4fd36956c273d71 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Thu, 12 Sep 2019 18:21:09 -0700 Subject: [PATCH 65/74] [WIP] Refactor --- azurerm/internal/services/frontdoor/helper.go | 23 --- ...resource_arm_front_door_firewall_policy.go | 185 ++++++++++-------- 2 files changed, 108 insertions(+), 100 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index d161a7d82e04..233c7a9f66b4 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -180,26 +180,3 @@ func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error return nil } -func ConvertToPolicyEnabledStateFromBool(isEnabled bool) frontdoor.PolicyEnabledState { - if isEnabled { - return frontdoor.PolicyEnabledStateEnabled - } - - return frontdoor.PolicyEnabledStateDisabled -} - -func ConvertBoolToCustomRuleEnabledState(isEnabled bool) frontdoor.CustomRuleEnabledState { - if isEnabled { - return frontdoor.CustomRuleEnabledStateEnabled - } - - return frontdoor.CustomRuleEnabledStateDisabled -} - -func ConvertBoolToManagedRuleEnabledState(isEnabled bool) frontdoor.ManagedRuleEnabledState { - if isEnabled { - return frontdoor.ManagedRuleEnabledStateEnabled - } - - return frontdoor.ManagedRuleEnabledStateDisabled -} diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index e87c27670959..ba6f82dd17fd 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -308,7 +308,10 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta } location := azure.NormalizeLocation("Global") - enabled := d.Get("enabled").(bool) + enabled := frontdoor.PolicyEnabledStateDisabled + if d.Get("enabled").(bool) { + enabled = frontdoor.PolicyEnabledStateEnabled + } mode := d.Get("mode").(string) redirectUrl := d.Get("redirect_url").(string) customBlockResponseStatusCode := d.Get("custom_block_response_status_code").(int) @@ -323,7 +326,7 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta Location: utils.String(location), WebApplicationFirewallPolicyProperties: &frontdoor.WebApplicationFirewallPolicyProperties{ PolicySettings: &frontdoor.PolicySettings{ - EnabledState: afd.ConvertToPolicyEnabledStateFromBool(enabled), + EnabledState: enabled, Mode: frontdoor.PolicyMode(mode), RedirectURL: utils.String(redirectUrl), CustomBlockResponseStatusCode: utils.Int32(int32(customBlockResponseStatusCode)), @@ -397,28 +400,31 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo output := make([]frontdoor.CustomRule, 0) for _, cr := range input { - customRule := cr.(map[string]interface{}) - - name := customRule["name"].(string) - priority := int32(customRule["priority"].(int)) - enabled := customRule["enabled"].(bool) - ruleType := customRule["rule_type"].(string) - rateLimitDurationInMinutes := int32(customRule["rate_limit_duration_in_minutes"].(int)) - rateLimitThreshold := int32(customRule["rate_limit_threshold"].(int)) - matchConditions := customRule["match_condition"].([]interface{}) - action := customRule["action"].(string) - - afpCustomRule := frontdoor.CustomRule{ + custom := cr.(map[string]interface{}) + + enabled := frontdoor.CustomRuleEnabledStateDisabled + if custom["enabled"].(bool) { + enabled = frontdoor.CustomRuleEnabledStateEnabled + } + name := custom["name"].(string) + priority := int32(custom["priority"].(int)) + ruleType := custom["rule_type"].(string) + rateLimitDurationInMinutes := int32(custom["rate_limit_duration_in_minutes"].(int)) + rateLimitThreshold := int32(custom["rate_limit_threshold"].(int)) + matchConditions := custom["match_condition"].([]interface{}) + action := custom["action"].(string) + + customRule := frontdoor.CustomRule{ Name: utils.String(name), Priority: utils.Int32(priority), - EnabledState: afd.ConvertBoolToCustomRuleEnabledState(enabled), + EnabledState: enabled, RuleType: frontdoor.RuleType(ruleType), RateLimitDurationInMinutes: utils.Int32(rateLimitDurationInMinutes), RateLimitThreshold: utils.Int32(rateLimitThreshold), MatchConditions: expandArmFrontDoorFirewallMatchConditions(matchConditions), Action: frontdoor.ActionType(action), } - output = append(output, afpCustomRule) + output = append(output, customRule) } result := frontdoor.CustomRuleList{ @@ -433,47 +439,50 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor return nil } - output := make([]frontdoor.MatchCondition, 0) + result := make([]frontdoor.MatchCondition, 0) - for _, mc := range input { - matchCondition := mc.(map[string]interface{}) - matchVariable := matchCondition["match_variable"].(string) - selector := matchCondition["selector"].(string) - operator := frontdoor.Operator(matchCondition["operator"].(string)) - negateCondition := matchCondition["negation_condition"].(bool) - - mv := matchCondition["match_value"].([]interface{}) - matchValues := make([]string, 0) - for _, v := range mv { - matchValues = append(matchValues, v.(string)) - } - matchValue := &matchValues + for _, v := range input { + match := v.(map[string]interface{}) - ts := matchCondition["transforms"].([]interface{}) - transform := make([]frontdoor.TransformType, 0) - for _, t := range ts { - transform = append(transform, frontdoor.TransformType(t.(string))) - } - transforms := &transform + matchVariable := match["match_variable"].(string) + selector := match["selector"].(string) + operator := match["operator"].(string) + negateCondition := match["negation_condition"].(bool) + matchValues := match["match_value"].([]interface{}) + transforms := match["transforms"].([]interface{}) - fdpMatchCondition := frontdoor.MatchCondition{ - Operator: operator, + matchCondition := frontdoor.MatchCondition{ + Operator: frontdoor.Operator(operator), NegateCondition: &negateCondition, - MatchValue: matchValue, - Transforms: transforms, + MatchValue: utils.ExpandStringSlice(matchValues), + Transforms: expandArmFrontDoorFirewallTransforms(transforms), } if matchVariable != "" { - fdpMatchCondition.MatchVariable = frontdoor.MatchVariable(matchVariable) + matchCondition.MatchVariable = frontdoor.MatchVariable(matchVariable) } if selector != "" { - fdpMatchCondition.Selector = utils.String(selector) + matchCondition.Selector = utils.String(selector) } - output = append(output, fdpMatchCondition) + result = append(result, matchCondition) + } + + return &result +} + +func expandArmFrontDoorFirewallTransforms(input []interface{}) *[]frontdoor.TransformType { + if len(input) == 0 { + return nil + } + + result := make([]frontdoor.TransformType, 0) + + for _, v := range input { + result = append(result, frontdoor.TransformType(v.(string))) } - return &output + return &result } func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.ManagedRuleSetList { @@ -481,7 +490,7 @@ func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.Mana return nil } - managedRuleSetList := make([]frontdoor.ManagedRuleSet, 0) + managedRules := make([]frontdoor.ManagedRuleSet, 0) for _, mr := range input { managedRule := mr.(map[string]interface{}) @@ -493,54 +502,76 @@ func expandArmFrontDoorFirewallManagedRules(input []interface{}) *frontdoor.Mana managedRuleSet := frontdoor.ManagedRuleSet{ RuleSetType: utils.String(ruleType), RuleSetVersion: utils.String(version), - //RuleGroupOverrides: *[]ManagedRuleGroupOverride } - if len(overrides) > 0 { - for _, o := range overrides { - override := o.(map[string]interface{}) + if ruleGroupOverrides := expandArmFrontDoorFirewallManagedRuleGroupOverride(overrides); ruleGroupOverrides != nil { + managedRuleSet.RuleGroupOverrides = ruleGroupOverrides + } - ruleGroupName := override["rule_group_name"].(string) - rules := override["rule"].([]interface{}) + managedRules = append(managedRules, managedRuleSet) + } - managedRuleGroupOverride := frontdoor.ManagedRuleGroupOverride{ - RuleGroupName: utils.String(ruleGroupName), - //Rules: *[]ManagedRuleOverride - } + result := frontdoor.ManagedRuleSetList{ + ManagedRuleSets: &managedRules, + } - if len(rules) > 0 { - managedRuleOverrides := make([]frontdoor.ManagedRuleOverride, 0) + return &result +} - for _, r := range rules { - rule := r.(map[string]interface{}) +func expandArmFrontDoorFirewallManagedRuleGroupOverride(input []interface{}) *[]frontdoor.ManagedRuleGroupOverride { + if len(input) == 0 { + return nil + } - ruleId := rule["rule_id"].(string) - enabled := rule["enabled"].(bool) - action := rule["action"].(string) + managedRuleGroupOverrides := make([]frontdoor.ManagedRuleGroupOverride, 0) - managedRuleOverride := frontdoor.ManagedRuleOverride{ - RuleID: utils.String(ruleId), - EnabledState: afd.ConvertBoolToManagedRuleEnabledState(enabled), - Action: frontdoor.ActionType(action), - } + for _, v := range input { + override := v.(map[string]interface{}) - managedRuleOverrides = append(managedRuleOverrides, managedRuleOverride) - } + ruleGroupName := override["rule_group_name"].(string) + rules := override["rule"].([]interface{}) - managedRuleGroupOverride.Rules = &managedRuleOverrides - } - } + managedRuleGroupOverride := frontdoor.ManagedRuleGroupOverride{ + RuleGroupName: utils.String(ruleGroupName), + } - // Done processing overrides now add them to the managed rule set array - managedRuleSetList = append(managedRuleSetList, managedRuleSet) + if managedRuleOverride := expandArmFrontDoorFirewallRuleOverride(rules); managedRuleOverride != nil { + managedRuleGroupOverride.Rules = managedRuleOverride } + + managedRuleGroupOverrides = append(managedRuleGroupOverrides, managedRuleGroupOverride) + } + + return &managedRuleGroupOverrides +} + +func expandArmFrontDoorFirewallRuleOverride(input []interface{}) *[]frontdoor.ManagedRuleOverride { + if len(input) == 0 { + return nil } - output := frontdoor.ManagedRuleSetList{ - ManagedRuleSets: &managedRuleSetList, + managedRuleOverrides := make([]frontdoor.ManagedRuleOverride, 0) + + for _, v := range input { + rule := v.(map[string]interface{}) + + enabled := frontdoor.ManagedRuleEnabledStateDisabled + if rule["enabled"].(bool) { + enabled = frontdoor.ManagedRuleEnabledStateEnabled + } + ruleId := rule["rule_id"].(string) + action := rule["action"].(string) + + managedRuleOverride := frontdoor.ManagedRuleOverride{ + RuleID: utils.String(ruleId), + EnabledState: enabled, + Action: frontdoor.ActionType(action), + } + + managedRuleOverrides = append(managedRuleOverrides, managedRuleOverride) } - return &output + return &managedRuleOverrides } func expandArmFrontDoorFirewallFrontendEndpointLinks(input []interface{}) *[]frontdoor.FrontendEndpointLink { From fca8221000da4aa53cc2b948a836dc6687beb08a Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Fri, 13 Sep 2019 18:48:57 -0700 Subject: [PATCH 66/74] [WIP] Progress --- ...resource_arm_front_door_firewall_policy.go | 93 +++++++++++++++---- 1 file changed, 76 insertions(+), 17 deletions(-) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index ba6f82dd17fd..7727d2ea62b2 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -273,7 +273,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "frontend_endpoint_ids": { Type: schema.TypeList, - Required: true, + Computed: true, MaxItems: 1000, Elem: &schema.Schema{ Type: schema.TypeString, @@ -318,7 +318,6 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta customBlockResponseBody := d.Get("custom_block_response_body").(string) customRules := d.Get("custom_rule").([]interface{}) managedRules := d.Get("managed_rule").([]interface{}) - frontendEndpoints := d.Get("frontend_endpoint_ids").([]interface{}) tags := d.Get("tags").(map[string]interface{}) frontdoorWebApplicationFirewallPolicy := frontdoor.WebApplicationFirewallPolicy{ @@ -334,7 +333,6 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta }, CustomRules: expandArmFrontDoorFirewallCustomRules(customRules), ManagedRules: expandArmFrontDoorFirewallManagedRules(managedRules), - FrontendEndpointLinks: expandArmFrontDoorFirewallFrontendEndpointLinks(frontendEndpoints), }, Tags: expandTags(tags), } @@ -358,8 +356,76 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta return resourceArmFrontDoorFirewallPolicyRead(d, meta) } - +// ********************************************************************************************* +// ********************************************************************************************* +// ********************************************************************************************* +// ********************************************************************************************* +// ********************************************************************************************* +// ********************************************************************************************* +// ********************************************************************************************* func resourceArmFrontDoorFirewallPolicyRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).frontdoor.FrontDoorsPolicyClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + name := id.Path["frontdoorwebapplicationfirewallpolicies"] + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] Front Door Firewall Policy %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("Error reading Front Door Firewall Policy %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resourceGroup) + + if location := resp.Location; location != nil { + d.Set("location", azure.NormalizeLocation(*location)) + } + + if properties := resp.WebApplicationFirewallPolicyProperties; properties != nil { + if properties.PolicySettings != nil { + + if err := d.Set("enabled", properties.PolicySettings.EnabledState == frontdoor.PolicyEnabledStateEnabled); err != nil { + return fmt.Errorf("Error setting `enabled`: %+v", err) + } + + if err := d.Set("mode", string(properties.PolicySettings.Mode)); err != nil { + return fmt.Errorf("Error setting `mode`: %+v", err) + } + + if err := d.Set("redirect_url", properties.PolicySettings.RedirectURL); err != nil { + return fmt.Errorf("Error setting `redirect_url`: %+v", err) + } + + if err := d.Set("custom_block_response_status_code", properties.PolicySettings.CustomBlockResponseStatusCode); err != nil { + return fmt.Errorf("Error setting `custom_block_response_status_code`: %+v", err) + } + + if err := d.Set("custom_block_response_body", properties.PolicySettings.CustomBlockResponseBody); err != nil { + return fmt.Errorf("Error setting `custom_block_response_body`: %+v", err) + } + } + + if err := d.Set("custom_rule", flattenArmFrontDoorFirewallCustomRules(properties.CustomRules)); err != nil { + return fmt.Errorf("Error flattening `custom_rule`: %+v", err) + } + } + + + + + + + return nil } @@ -574,20 +640,13 @@ func expandArmFrontDoorFirewallRuleOverride(input []interface{}) *[]frontdoor.Ma return &managedRuleOverrides } -func expandArmFrontDoorFirewallFrontendEndpointLinks(input []interface{}) *[]frontdoor.FrontendEndpointLink { - if len(input) == 0 { - return nil +func flattenArmFrontDoorFirewallCustomRules(input *frontdoor.CustomRuleList) []interface{} { + if input == nil { + return make([]interface{}, 0) } - frontendEndpointLinks := make([]frontdoor.FrontendEndpointLink, 0) - - for _, frontendEndpointLink := range input { - fel := frontdoor.FrontendEndpointLink{ - ID: utils.String(frontendEndpointLink.(string)), - } + result := make([]interface{}, 0) - frontendEndpointLinks = append(frontendEndpointLinks, fel) - } + //for _, item := input. - return &frontendEndpointLinks -} +} \ No newline at end of file From 4a97e5eaf8991e2439a0d871e87fb45889bb68e9 Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 16 Sep 2019 17:06:36 -0700 Subject: [PATCH 67/74] [WIP] Fully function WAF resource --- azurerm/internal/services/frontdoor/helper.go | 21 +++ ...resource_arm_front_door_firewall_policy.go | 155 ++++++++++++++---- 2 files changed, 146 insertions(+), 30 deletions(-) diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index 233c7a9f66b4..adcebc48f0fc 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -180,3 +180,24 @@ func VerifyCustomHttpsConfiguration(configFrontendEndpoints []interface{}) error return nil } +func FlattenTransformSlice(input *[]frontdoor.TransformType) []interface{} { + result := make([]interface{}, 0) + + if input != nil { + for _, item := range *input { + result = append(result, string(item)) + } + } + return result +} + +func FlattenFrontendEndpointLinkSlice(input *[]frontdoor.FrontendEndpointLink) []interface{} { + result := make([]interface{}, 0) + + if input != nil { + for _, item := range *input { + result = append(result, string(*item.ID)) + } + } + return result +} diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 7727d2ea62b2..6300e37ccfb9 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -12,6 +12,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" afd "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -123,11 +124,6 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.Redirect), }, false), }, - "custom_block_response_body": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.NoEmptyStrings, - }, "match_condition": { Type: schema.TypeList, Optional: true, @@ -149,8 +145,8 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, false), }, "selector": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, ValidateFunc: validate.NoEmptyStrings, }, "operator": { @@ -174,7 +170,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "negation_condition": { Type: schema.TypeBool, Optional: true, - Default: false, + Default: false, }, "match_value": { Type: schema.TypeList, @@ -274,14 +270,12 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "frontend_endpoint_ids": { Type: schema.TypeList, Computed: true, - MaxItems: 1000, Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validate.NoEmptyStrings, + Type: schema.TypeString, }, }, - "tags": tagsSchema(), + "tags": tags.Schema(), }, } } @@ -331,8 +325,8 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta CustomBlockResponseStatusCode: utils.Int32(int32(customBlockResponseStatusCode)), CustomBlockResponseBody: utils.String(customBlockResponseBody), }, - CustomRules: expandArmFrontDoorFirewallCustomRules(customRules), - ManagedRules: expandArmFrontDoorFirewallManagedRules(managedRules), + CustomRules: expandArmFrontDoorFirewallCustomRules(customRules), + ManagedRules: expandArmFrontDoorFirewallManagedRules(managedRules), }, Tags: expandTags(tags), } @@ -356,13 +350,7 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta return resourceArmFrontDoorFirewallPolicyRead(d, meta) } -// ********************************************************************************************* -// ********************************************************************************************* -// ********************************************************************************************* -// ********************************************************************************************* -// ********************************************************************************************* -// ********************************************************************************************* -// ********************************************************************************************* + func resourceArmFrontDoorFirewallPolicyRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient).frontdoor.FrontDoorsPolicyClient ctx := meta.(*ArmClient).StopContext @@ -418,14 +406,17 @@ func resourceArmFrontDoorFirewallPolicyRead(d *schema.ResourceData, meta interfa if err := d.Set("custom_rule", flattenArmFrontDoorFirewallCustomRules(properties.CustomRules)); err != nil { return fmt.Errorf("Error flattening `custom_rule`: %+v", err) } - } - - - - + if err := d.Set("managed_rule", flattenArmFrontDoorFirewallManagedRules(properties.ManagedRules)); err != nil { + return fmt.Errorf("Error flattening `managed_rule`: %+v", err) + } + if err := d.Set("frontend_endpoint_ids", afd.FlattenFrontendEndpointLinkSlice(properties.FrontendEndpointLinks)); err != nil { + return fmt.Errorf("Error flattening `frontend_endpoint_ids`: %+v", err) + } + } + flattenAndSetTags(d, resp.Tags) return nil } @@ -642,11 +633,115 @@ func expandArmFrontDoorFirewallRuleOverride(input []interface{}) *[]frontdoor.Ma func flattenArmFrontDoorFirewallCustomRules(input *frontdoor.CustomRuleList) []interface{} { if input == nil { - return make([]interface{}, 0) + return make([]interface{}, 0) } - result := make([]interface{}, 0) + results := make([]interface{}, 0) - //for _, item := input. + for _, v := range *input.Rules { + output := make(map[string]interface{}) -} \ No newline at end of file + output["name"] = v.Name + output["priority"] = int(*v.Priority) + output["enabled"] = v.EnabledState == frontdoor.CustomRuleEnabledStateEnabled + output["rule_type"] = string(v.RuleType) + output["rate_limit_duration_in_minutes"] = int(*v.RateLimitDurationInMinutes) + output["rate_limit_threshold"] = int(*v.RateLimitThreshold) + output["match_condition"] = flattenArmFrontDoorFirewallMatchConditions(v.MatchConditions) + output["action"] = string(v.Action) + + results = append(results, output) + } + + return results +} + +func flattenArmFrontDoorFirewallMatchConditions(input *[]frontdoor.MatchCondition) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + results := make([]interface{}, 0) + + for _, v := range *input { + output := make(map[string]interface{}) + + output["match_variable"] = string(v.MatchVariable) + if selector := v.Selector; selector != nil { + output["selector"] = string(*v.Selector) + } + output["operator"] = string(v.Operator) + if negateCondition := v.NegateCondition; negateCondition != nil { + output["negation_condition"] = *v.NegateCondition + } + output["match_value"] = utils.FlattenStringSlice(v.MatchValue) + output["transforms"] = afd.FlattenTransformSlice(v.Transforms) + + results = append(results, output) + } + + return results +} + +func flattenArmFrontDoorFirewallManagedRules(input *frontdoor.ManagedRuleSetList) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + results := make([]interface{}, 0) + + for _, v := range *input.ManagedRuleSets { + output := make(map[string]interface{}) + + output["type"] = string(*v.RuleSetType) + output["version"] = string(*v.RuleSetVersion) + if overrides := v.RuleGroupOverrides; overrides != nil { + output["override"] = flattenArmFrontDoorFirewallOverrides(overrides) + } + + results = append(results, output) + } + + return results +} + +func flattenArmFrontDoorFirewallOverrides(input *[]frontdoor.ManagedRuleGroupOverride) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + results := make([]interface{}, 0) + + for _, v := range *input { + output := make(map[string]interface{}) + + output["rule_group_name"] = string(*v.RuleGroupName) + if rules := v.Rules; rules != nil { + output["rule"] = flattenArmFrontdoorFirewallRules(rules) + } + + results = append(results, output) + } + + return results +} + +func flattenArmFrontdoorFirewallRules(input *[]frontdoor.ManagedRuleOverride) []interface{} { + if input == nil { + return make([]interface{}, 0) + } + + results := make([]interface{}, 0) + + for _, v := range *input { + output := make(map[string]interface{}) + + output["rule_id"] = string(*v.RuleID) + output["enabled"] = v.EnabledState == frontdoor.ManagedRuleEnabledStateEnabled + output["action"] = string(v.Action) + + results = append(results, output) + } + + return results +} From ff040bb7ed1f9d66b9d4e46d8631eb036bb0228c Mon Sep 17 00:00:00 2001 From: Jeffrey Cline Date: Mon, 16 Sep 2019 20:18:12 -0700 Subject: [PATCH 68/74] Fix lint error add test case --- azurerm/internal/services/frontdoor/helper.go | 2 +- .../internal/services/frontdoor/validate.go | 2 +- ...resource_arm_front_door_firewall_policy.go | 56 +++-- ...rce_arm_front_door_firewall_policy_test.go | 102 +++++++++ .../front_door_firewall_policy.html.markdown | 194 ++++++++++++++++++ 5 files changed, 333 insertions(+), 23 deletions(-) create mode 100644 azurerm/resource_arm_front_door_firewall_policy_test.go create mode 100644 website/docs/r/front_door_firewall_policy.html.markdown diff --git a/azurerm/internal/services/frontdoor/helper.go b/azurerm/internal/services/frontdoor/helper.go index adcebc48f0fc..006e03a08228 100644 --- a/azurerm/internal/services/frontdoor/helper.go +++ b/azurerm/internal/services/frontdoor/helper.go @@ -196,7 +196,7 @@ func FlattenFrontendEndpointLinkSlice(input *[]frontdoor.FrontendEndpointLink) [ if input != nil { for _, item := range *input { - result = append(result, string(*item.ID)) + result = append(result, *item.ID) } } return result diff --git a/azurerm/internal/services/frontdoor/validate.go b/azurerm/internal/services/frontdoor/validate.go index 59ea4a779f45..67e2e5a57880 100644 --- a/azurerm/internal/services/frontdoor/validate.go +++ b/azurerm/internal/services/frontdoor/validate.go @@ -25,7 +25,7 @@ func ValidateBackendPoolRoutingRuleName(i interface{}, k string) (_ []string, er func ValidateCustomBlockResponseBody(i interface{}, k string) (_ []string, errors []error) { if m, regexErrs := validate.RegExHelper(i, k, `^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$`); !m { - errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must contain only alphanumeric and equals sign characters.`, k)) + errors = append(regexErrs, fmt.Errorf(`%q contains invalid characters, %q must contain only alphanumeric and equals sign characters.`, k, k)) } return nil, errors diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index 6300e37ccfb9..a6b477e6234f 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -50,11 +50,12 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "mode": { Type: schema.TypeString, - Required: true, + Optional: true, ValidateFunc: validation.StringInSlice([]string{ string(frontdoor.Detection), string(frontdoor.Prevention), }, false), + Default: string(frontdoor.Prevention), }, "redirect_url": { @@ -64,9 +65,15 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { }, "custom_block_response_status_code": { - Type: schema.TypeInt, - Optional: true, - ValidateFunc: validation.IntBetween(100, 530), + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validate.IntInSlice([]int{ + 200, + 403, + 405, + 406, + 429, + }), }, "custom_block_response_body": { @@ -78,12 +85,12 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "custom_rule": { Type: schema.TypeList, MaxItems: 100, - Required: true, + Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validate.NoEmptyStrings, }, "priority": { @@ -207,17 +214,17 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "managed_rule": { Type: schema.TypeList, MaxItems: 100, - Required: true, + Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "type": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validate.NoEmptyStrings, }, "version": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validate.NoEmptyStrings, }, "override": { @@ -228,7 +235,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Schema: map[string]*schema.Schema{ "rule_group_name": { Type: schema.TypeString, - Optional: true, + Required: true, ValidateFunc: validate.NoEmptyStrings, }, "rule": { @@ -319,11 +326,8 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta Location: utils.String(location), WebApplicationFirewallPolicyProperties: &frontdoor.WebApplicationFirewallPolicyProperties{ PolicySettings: &frontdoor.PolicySettings{ - EnabledState: enabled, - Mode: frontdoor.PolicyMode(mode), - RedirectURL: utils.String(redirectUrl), - CustomBlockResponseStatusCode: utils.Int32(int32(customBlockResponseStatusCode)), - CustomBlockResponseBody: utils.String(customBlockResponseBody), + EnabledState: enabled, + Mode: frontdoor.PolicyMode(mode), }, CustomRules: expandArmFrontDoorFirewallCustomRules(customRules), ManagedRules: expandArmFrontDoorFirewallManagedRules(managedRules), @@ -331,6 +335,16 @@ func resourceArmFrontDoorFirewallPolicyCreateUpdate(d *schema.ResourceData, meta Tags: expandTags(tags), } + if redirectUrl != "" { + frontdoorWebApplicationFirewallPolicy.WebApplicationFirewallPolicyProperties.PolicySettings.RedirectURL = utils.String(redirectUrl) + } + if customBlockResponseBody != "" { + frontdoorWebApplicationFirewallPolicy.WebApplicationFirewallPolicyProperties.PolicySettings.CustomBlockResponseBody = utils.String(customBlockResponseBody) + } + if customBlockResponseStatusCode > 0 { + frontdoorWebApplicationFirewallPolicy.WebApplicationFirewallPolicyProperties.PolicySettings.CustomBlockResponseStatusCode = utils.Int32(int32(customBlockResponseStatusCode)) + } + future, err := client.CreateOrUpdate(ctx, resourceGroup, name, frontdoorWebApplicationFirewallPolicy) if err != nil { return fmt.Errorf("Error creating Front Door Firewall policy %q (Resource Group %q): %+v", name, resourceGroup, err) @@ -430,7 +444,7 @@ func resourceArmFrontDoorFirewallPolicyDelete(d *schema.ResourceData, meta inter return err } resourceGroup := id.ResourceGroup - name := id.Path["FrontDoorWebApplicationFirewallPolicies"] + name := id.Path["frontdoorwebapplicationfirewallpolicies"] future, err := client.Delete(ctx, resourceGroup, name) if err != nil { @@ -668,7 +682,7 @@ func flattenArmFrontDoorFirewallMatchConditions(input *[]frontdoor.MatchConditio output["match_variable"] = string(v.MatchVariable) if selector := v.Selector; selector != nil { - output["selector"] = string(*v.Selector) + output["selector"] = *v.Selector } output["operator"] = string(v.Operator) if negateCondition := v.NegateCondition; negateCondition != nil { @@ -693,8 +707,8 @@ func flattenArmFrontDoorFirewallManagedRules(input *frontdoor.ManagedRuleSetList for _, v := range *input.ManagedRuleSets { output := make(map[string]interface{}) - output["type"] = string(*v.RuleSetType) - output["version"] = string(*v.RuleSetVersion) + output["type"] = *v.RuleSetType + output["version"] = *v.RuleSetVersion if overrides := v.RuleGroupOverrides; overrides != nil { output["override"] = flattenArmFrontDoorFirewallOverrides(overrides) } @@ -715,7 +729,7 @@ func flattenArmFrontDoorFirewallOverrides(input *[]frontdoor.ManagedRuleGroupOve for _, v := range *input { output := make(map[string]interface{}) - output["rule_group_name"] = string(*v.RuleGroupName) + output["rule_group_name"] = *v.RuleGroupName if rules := v.Rules; rules != nil { output["rule"] = flattenArmFrontdoorFirewallRules(rules) } @@ -736,7 +750,7 @@ func flattenArmFrontdoorFirewallRules(input *[]frontdoor.ManagedRuleOverride) [] for _, v := range *input { output := make(map[string]interface{}) - output["rule_id"] = string(*v.RuleID) + output["rule_id"] = *v.RuleID output["enabled"] = v.EnabledState == frontdoor.ManagedRuleEnabledStateEnabled output["action"] = string(v.Action) diff --git a/azurerm/resource_arm_front_door_firewall_policy_test.go b/azurerm/resource_arm_front_door_firewall_policy_test.go new file mode 100644 index 000000000000..7a4fe51450c8 --- /dev/null +++ b/azurerm/resource_arm_front_door_firewall_policy_test.go @@ -0,0 +1,102 @@ +package azurerm + +import ( + "fmt" + //"strings" + "testing" + + //"github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMFrontDoorFirewallPolicy_basic(t *testing.T) { + resourceName := "azurerm_frontdoor_firewall_policy.test" + ri := tf.AccRandTimeInt() + config := testAccAzureRMFrontDoorFirewallPolicy_basic(ri, testLocation()) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMFrontDoorFirewallPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMFrontDoorFirewallPolicyExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("testAccFrontDoorWAF%d", ri)), + resource.TestCheckResourceAttr(resourceName, "mode", "Prevention"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testCheckAzureRMFrontDoorFirewallPolicyExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Front Door Firewall Policy not found: %s", resourceName) + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + client := testAccProvider.Meta().(*ArmClient).frontdoor.FrontDoorsPolicyClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Front Door Firewall Policy %q (Resource Group %q) does not exist", name, resourceGroup) + } + return fmt.Errorf("Bad: Get on FrontDoorsPolicyClient: %+v", err) + } + + return nil + } +} + +func testCheckAzureRMFrontDoorFirewallPolicyDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*ArmClient).frontdoor.FrontDoorsPolicyClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_frontdoor_firewall_policy" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + if resp, err := client.Get(ctx, resourceGroup, name); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Get on FrontDoorsPolicyClient: %+v", err) + } + } + + return nil + } + + return nil +} + +func testAccAzureRMFrontDoorFirewallPolicy_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testAccRG-%[1]d" + location = "%[2]s" +} + +resource "azurerm_frontdoor_firewall_policy" "test" { + name = "testAccFrontDoorWAF%[1]d" + resource_group_name = azurerm_resource_group.test.name +} +`, rInt, location) +} diff --git a/website/docs/r/front_door_firewall_policy.html.markdown b/website/docs/r/front_door_firewall_policy.html.markdown new file mode 100644 index 000000000000..7561f69d2bb1 --- /dev/null +++ b/website/docs/r/front_door_firewall_policy.html.markdown @@ -0,0 +1,194 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_frontdoor_firewall_policy" +sidebar_current: "docs-azurerm-resource-front-door-firewall-policy" +description: |- + Manages an Azure Front Door Web Application Firewall Policy instance. +--- + +# azurerm_web_application_firewall_policy + +Manages an Azure Front Door Web Application Firewall Policy instance. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-rg" + location = "West US 2" +} + +resource "azurerm_frontdoor_firewall_policy" "example" { + name = "example-fdwafpolicy" + resource_group_name = "${azurerm_resource_group.example.name}" + enabled = true + mode = "Prevention" + redirect_url = "https://www.contoso.com" + custom_block_response_status_code = 403 + custom_block_response_body = "PGh0bWw+CjxoZWFkZXI+PHRpdGxlPkhlbGxvPC90aXRsZT48L2hlYWRlcj4KPGJvZHk+CkhlbGxvIHdvcmxkCjwvYm9keT4KPC9odG1sPg==" + + custom_rule { + name = "Rule1" + enabled = true + priority = 1 + rate_limit_duration_in_minutes = 1 + rate_limit_threshold = 10 + rule_type = "MatchRule" + action = "Block" + + match_condition { + match_variable = "RemoteAddr" + operator = "IPMatch" + negation_condition = false + match_value = ["192.168.1.0/24", "10.0.0.0/24"] + transforms = ["Lowercase", "Trim"] + } + } + + custom_rules { + name = "Rule2" + enabled = true + priority = 2 + rate_limit_duration_in_minutes = 1 + rate_limit_threshold = 10 + rule_type = "MatchRule" + action = "Block" + + match_condition { + match_variable = "RemoteAddr" + operator = "IPMatch" + negation_condition = false + match_value = ["192.168.1.0/24"] + } + + match_condition { + variable_name = "RequestHeaders" + selector = "UserAgent" + operator = "Contains" + negation_condition = false + match_value = ["windows"] + transforms = ["Lowercase", "Trim"] + } + } + + managed_rule { + type = "DefaultRuleSet" + version = "preview-0.1" + + override { + rule_group_name = "PHP" + + rule { + rule_id = "933111" + enable = false + action = "Block" + } + } + } + + managed_rule { + type = "BotProtection" + version = "preview-0.1" + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the policy. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group. Changing this forces a new resource to be created. + +* `enabled` - (Optional) Describes if the policy is in enabled state or disabled state Defaults to `Enabled`. + +* `mode` - (Optional) Describes if it is in detection mode or prevention mode at the policy level Defaults to `Prevention`. + +* `redirect_url` - (Optional) If action type is redirect, this field represents redirect URL for the client. + +* `custom_block_response_status_code` - (Optional) If the `action` type is block, customer can override the response status code. Valid values for the `custom_block_response_status_code` are `200`, `403`, `405`, `406`, or `429`. + +* `custom_block_response_body` - (Optional) If the `action` type is block, customer can override the response body. The body must be specified in base64 encoding. + +* `custom_rule` - (Optional) One or more `custom_rule` blocks as defined below. + +* `managed_rule` - (Optional) One or more `managed_rule` blocks as defined below. + +* `tags` - (Optional) A mapping of tags to assign to the Web Application Firewall Policy. + +--- + +The `custom_rule` block supports the following: + +* `name` - (Required) Gets name of the resource that is unique within a policy. This name can be used to access the resource. + +* `priority` - (Required) Describes priority of the rule. Rules with a lower value will be evaluated before rules with a higher value + +* `rule_type` - (Required) Describes the type of rule + +* `match_condition` - (Required) One or more `match_condition` block defined below. + +* `action` - (Required) Type of Actions + +--- + +The `managed_rule` block supports the following: + +* `type` - (Required) The name of the managed rule to use with this resource. + +* `version` - (Required) The version on the managed rule to use with this resource. + +* `override` - (Optional) One or more `override` blocks as defined below. + +--- + +The `match_condition` block supports the following: + +* `variable_name` - (Required) The name of the Match Variable + +* `selector` - (Optional) Match against a specific key from the `QueryString`, `PostArgs`, `RequestHeader` or `Cookies` variables. + +* `match_variable` - (Required) The request variable to compare with. + +* `operator` - (Required) Comparison type to use for matching with the variable value. + +* `negation_condition` - (Optional) Describes if the result of this condition should be negated. + +* `match_values` - (Required) A list of possible values to match. + +--- + +The `override` block supports the following: + +* `rule_group_name` - (Required) Describes the managed rule group to override. + +* `rule` - (Optional) One or more `rule` blocks as defined below. If none are specified, all of the rules in the group will be disabled. + +--- + +The `rule` block supports the following: + +* `rule_id` - (Required) Identifier for the managed rule. + +* `action` - (Required) Describes the override action to be applied when the rule matches. + +* `enabled` - (Optional) Describes if the managed rule is in enabled or disabled state. Defaults to Disabled if not specified. + +## Attributes Reference + +The following attributes are exported: + +* `id` - Resource ID. + +* `location` - Resource location. + +* `frontend_endpoint_ids` - Describes Frontend Endpoints associated with this Front Door Web Application Firewall policy. + +## Import + +Front Door Web Application Firewall Policy can be imported using the `resource id`, e.g. + +```shell +$ terraform import azurerm_frontdoor_firewall_policy.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Network/frontdoorwebapplicationfirewallpolicies/example-fdwafpolicy +``` From 31bc27a95f8ec7ae526675e8a4009416e433f0e4 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 17 Sep 2019 14:01:26 -0700 Subject: [PATCH 69/74] Fix documentation & add to side bar --- ...resource_arm_front_door_firewall_policy.go | 70 +++++++++++-------- website/azurerm.erb | 12 ++++ .../front_door_firewall_policy.html.markdown | 56 ++++++++------- 3 files changed, 85 insertions(+), 53 deletions(-) diff --git a/azurerm/resource_arm_front_door_firewall_policy.go b/azurerm/resource_arm_front_door_firewall_policy.go index a6b477e6234f..40f5a07becd7 100644 --- a/azurerm/resource_arm_front_door_firewall_policy.go +++ b/azurerm/resource_arm_front_door_firewall_policy.go @@ -35,10 +35,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { ValidateFunc: validate.NoEmptyStrings, }, - "location": { - Type: schema.TypeString, - Computed: true, - }, + "location": azure.SchemaLocationForDataSource(), "resource_group_name": azure.SchemaResourceGroupName(), @@ -61,7 +58,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { "redirect_url": { Type: schema.TypeString, Optional: true, - ValidateFunc: validate.NoEmptyStrings, + ValidateFunc: validate.URLIsHTTPOrHTTPS, }, "custom_block_response_status_code": { @@ -93,17 +90,20 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, ValidateFunc: validate.NoEmptyStrings, }, - "priority": { - Type: schema.TypeInt, - Optional: true, - Default: 1, - }, + "enabled": { Type: schema.TypeBool, Optional: true, Default: true, }, - "rule_type": { + + "priority": { + Type: schema.TypeInt, + Optional: true, + Default: 1, + }, + + "type": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ @@ -111,16 +111,19 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.RateLimitRule), }, false), }, + "rate_limit_duration_in_minutes": { Type: schema.TypeInt, Optional: true, Default: 1, }, + "rate_limit_threshold": { Type: schema.TypeInt, Optional: true, Default: 10, }, + "action": { Type: schema.TypeString, Required: true, @@ -131,6 +134,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.Redirect), }, false), }, + "match_condition": { Type: schema.TypeList, Optional: true, @@ -151,11 +155,17 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.RequestURI), }, false), }, - "selector": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validate.NoEmptyStrings, + + "match_values": { + Type: schema.TypeList, + Required: true, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validate.NoEmptyStrings, + }, }, + "operator": { Type: schema.TypeString, Required: true, @@ -174,20 +184,19 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { string(frontdoor.RegEx), }, false), }, + + "selector": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.NoEmptyStrings, + }, + "negation_condition": { Type: schema.TypeBool, Optional: true, Default: false, }, - "match_value": { - Type: schema.TypeList, - Required: true, - MaxItems: 100, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validate.NoEmptyStrings, - }, - }, + "transforms": { Type: schema.TypeList, Optional: true, @@ -222,11 +231,13 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, ValidateFunc: validate.NoEmptyStrings, }, + "version": { Type: schema.TypeString, Required: true, ValidateFunc: validate.NoEmptyStrings, }, + "override": { Type: schema.TypeList, MaxItems: 100, @@ -238,6 +249,7 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, ValidateFunc: validate.NoEmptyStrings, }, + "rule": { Type: schema.TypeList, MaxItems: 1000, @@ -249,11 +261,13 @@ func resourceArmFrontDoorFirewallPolicy() *schema.Resource { Required: true, ValidateFunc: validate.NoEmptyStrings, }, + "enabled": { Type: schema.TypeBool, Optional: true, Default: false, }, + "action": { Type: schema.TypeString, Required: true, @@ -479,7 +493,7 @@ func expandArmFrontDoorFirewallCustomRules(input []interface{}) *frontdoor.Custo } name := custom["name"].(string) priority := int32(custom["priority"].(int)) - ruleType := custom["rule_type"].(string) + ruleType := custom["type"].(string) rateLimitDurationInMinutes := int32(custom["rate_limit_duration_in_minutes"].(int)) rateLimitThreshold := int32(custom["rate_limit_threshold"].(int)) matchConditions := custom["match_condition"].([]interface{}) @@ -519,7 +533,7 @@ func expandArmFrontDoorFirewallMatchConditions(input []interface{}) *[]frontdoor selector := match["selector"].(string) operator := match["operator"].(string) negateCondition := match["negation_condition"].(bool) - matchValues := match["match_value"].([]interface{}) + matchValues := match["match_values"].([]interface{}) transforms := match["transforms"].([]interface{}) matchCondition := frontdoor.MatchCondition{ @@ -658,7 +672,7 @@ func flattenArmFrontDoorFirewallCustomRules(input *frontdoor.CustomRuleList) []i output["name"] = v.Name output["priority"] = int(*v.Priority) output["enabled"] = v.EnabledState == frontdoor.CustomRuleEnabledStateEnabled - output["rule_type"] = string(v.RuleType) + output["type"] = string(v.RuleType) output["rate_limit_duration_in_minutes"] = int(*v.RateLimitDurationInMinutes) output["rate_limit_threshold"] = int(*v.RateLimitThreshold) output["match_condition"] = flattenArmFrontDoorFirewallMatchConditions(v.MatchConditions) @@ -688,7 +702,7 @@ func flattenArmFrontDoorFirewallMatchConditions(input *[]frontdoor.MatchConditio if negateCondition := v.NegateCondition; negateCondition != nil { output["negation_condition"] = *v.NegateCondition } - output["match_value"] = utils.FlattenStringSlice(v.MatchValue) + output["match_values"] = utils.FlattenStringSlice(v.MatchValue) output["transforms"] = afd.FlattenTransformSlice(v.Transforms) results = append(results, output) diff --git a/website/azurerm.erb b/website/azurerm.erb index 0cda4aee99b8..4b3e11a9fd77 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -1017,6 +1017,18 @@ +
  • + Front Door Resources + +
  • +
  • HDInsight Resources