From 09858c4d481d59f164732ac879f8e9669287b66a Mon Sep 17 00:00:00 2001 From: magodo Date: Thu, 30 Apr 2020 15:52:00 +0800 Subject: [PATCH 001/104] app_service_environment: explicit resource group --- azurerm/helpers/azure/resource_group.go | 10 +++++ .../web/app_service_environment_resource.go | 23 ++++++++---- .../app_service_environment_resource_test.go | 37 +++++++++++++++++++ .../r/app_service_environment.html.markdown | 6 ++- 4 files changed, 66 insertions(+), 10 deletions(-) diff --git a/azurerm/helpers/azure/resource_group.go b/azurerm/helpers/azure/resource_group.go index a1dc5dc522ca9..aba7f5909a727 100644 --- a/azurerm/helpers/azure/resource_group.go +++ b/azurerm/helpers/azure/resource_group.go @@ -35,6 +35,16 @@ func SchemaResourceGroupNameForDataSource() *schema.Schema { } } +func SchemaResourceGroupNameOC() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeString, + ForceNew: true, + Optional: true, + Computed: true, + ValidateFunc: validateResourceGroupName, + } +} + func validateResourceGroupName(v interface{}, k string) (warnings []string, errors []error) { value := v.(string) diff --git a/azurerm/internal/services/web/app_service_environment_resource.go b/azurerm/internal/services/web/app_service_environment_resource.go index 3632b0946cdce..20205c54eef67 100644 --- a/azurerm/internal/services/web/app_service_environment_resource.go +++ b/azurerm/internal/services/web/app_service_environment_resource.go @@ -86,6 +86,9 @@ func resourceArmAppServiceEnvironment() *schema.Resource { }, false), }, + // TODO: Make it "Required" in next major release + "resource_group_name": azure.SchemaResourceGroupNameOC(), + "tags": tags.ForceNewSchema(), // Computed @@ -93,11 +96,6 @@ func resourceArmAppServiceEnvironment() *schema.Resource { Type: schema.TypeString, Computed: true, }, - - "resource_group_name": { - Type: schema.TypeString, - Computed: true, - }, }, } } @@ -118,10 +116,19 @@ func resourceArmAppServiceEnvironmentCreate(d *schema.ResourceData, meta interfa return err } + // TODO: Remove the implicit behavior in new major version. + // Discrepancy of resource group between ASE and Subnet is allowed. While for the sake of + // compatibility, we still allow user to use the resource group of Subnet to be the one for + // ASE implicitly. While allow user to explicitly specify the resource group, which takes higher + // precedence. resourceGroup := subnet.ResourceGroup - vnet, err := networksClient.Get(ctx, resourceGroup, subnet.VirtualNetworkName, "") + if v, ok := d.GetOk("resource_group_name"); ok { + resourceGroup = v.(string) + } + + vnet, err := networksClient.Get(ctx, subnet.ResourceGroup, subnet.VirtualNetworkName, "") if err != nil { - return fmt.Errorf("Error retrieving Virtual Network %q (Resource Group %q): %+v", subnet.VirtualNetworkName, resourceGroup, err) + return fmt.Errorf("Error retrieving Virtual Network %q (Resource Group %q): %+v", subnet.VirtualNetworkName, subnet.ResourceGroup, err) } // the App Service Environment has to be in the same location as the Virtual Network @@ -129,7 +136,7 @@ func resourceArmAppServiceEnvironmentCreate(d *schema.ResourceData, meta interfa if loc := vnet.Location; loc != nil { location = azure.NormalizeLocation(*loc) } else { - return fmt.Errorf("Error determining Location from Virtual Network %q (Resource Group %q): `location` was nil", subnet.VirtualNetworkName, resourceGroup) + return fmt.Errorf("Error determining Location from Virtual Network %q (Resource Group %q): `location` was nil", subnet.VirtualNetworkName, subnet.ResourceGroup) } existing, err := client.Get(ctx, resourceGroup, name) diff --git a/azurerm/internal/services/web/tests/app_service_environment_resource_test.go b/azurerm/internal/services/web/tests/app_service_environment_resource_test.go index e338f201084f7..71769ef80e8e2 100644 --- a/azurerm/internal/services/web/tests/app_service_environment_resource_test.go +++ b/azurerm/internal/services/web/tests/app_service_environment_resource_test.go @@ -120,6 +120,25 @@ func TestAccAzureRMAppServiceEnvironment_withAppServicePlan(t *testing.T) { }) } +func TestAccAzureRMAppServiceEnvironment_dedicatedResourceGroup(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_app_service_environment", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMAppServiceEnvironmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMAppServiceEnvironment_dedicatedResourceGroup(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMAppServiceEnvironmentExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + func testCheckAzureRMAppServiceEnvironmentExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).Web.AppServiceEnvironmentsClient @@ -234,6 +253,24 @@ resource "azurerm_app_service_plan" "test" { `, template, data.RandomInteger) } +func testAccAzureRMAppServiceEnvironment_dedicatedResourceGroup(data acceptance.TestData) string { + template := testAccAzureRMAppServiceEnvironment_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_resource_group" "test2" { + name = "acctestRG2-%[2]d" + location = "%s" +} + +resource "azurerm_app_service_environment" "test" { + name = "acctest-ase-%[2]d" + resource_group_name = azurerm_resource_group.test2.name + subnet_id = azurerm_subnet.ase.id +} +`, template, data.RandomInteger, data.Locations.Secondary) +} + func testAccAzureRMAppServiceEnvironment_template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/website/docs/r/app_service_environment.html.markdown b/website/docs/r/app_service_environment.html.markdown index a0518caac047b..ed0cea611f3c2 100644 --- a/website/docs/r/app_service_environment.html.markdown +++ b/website/docs/r/app_service_environment.html.markdown @@ -61,12 +61,14 @@ resource "azurerm_app_service_environment" "example" { * `front_end_scale_factor` - (Optional) Scale factor for front end instances. Possible values are between `5` and `15`. Defaults to `15`. +* `resource_group_name` - (Optional) The name of the Resource Group where the App Service Environment exists. Defaults to the Resource Group of the Subnet (specified by `subnet_id`). + +* `tags` - (Optional) A mapping of tags to assign to the resource. Changing this forces a new resource to be created. + ## Attribute Reference * `id` - The ID of the App Service Environment. -* `resource_group_name` - The name of the Resource Group where the App Service Environment exists. - * `location` - The location where the App Service Environment exists. ## Timeouts From 893307fb8b8e49eb1f8835f35a09d63bc4a81f4b Mon Sep 17 00:00:00 2001 From: Arcturus Date: Fri, 8 May 2020 06:13:27 +0800 Subject: [PATCH 002/104] update `azurerm_policy_assignment` - allow scopes of policy set definition without `subscription/` (#6792) Fixes #6671 --- .../services/policy/parse/set_definition.go | 12 ++++- .../tests/policy_assignment_resource_test.go | 47 +++++++++++++++++++ .../policy_set_definition_data_source_test.go | 46 +++++++++++++++--- 3 files changed, 97 insertions(+), 8 deletions(-) diff --git a/azurerm/internal/services/policy/parse/set_definition.go b/azurerm/internal/services/policy/parse/set_definition.go index 2a01d4946b54e..c2fcbb05482be 100644 --- a/azurerm/internal/services/policy/parse/set_definition.go +++ b/azurerm/internal/services/policy/parse/set_definition.go @@ -12,8 +12,10 @@ type PolicySetDefinitionId struct { // TODO: This parsing function is currently suppressing case difference due to github issue: https://github.com/Azure/azure-rest-api-specs/issues/8353 func PolicySetDefinitionID(input string) (*PolicySetDefinitionId, error) { - // in general, the id of a set definition should be: - // {scope}/providers/Microsoft.Authorization/policySetDefinitions/set1 + // in general, the id of a set definition should be (for custom policy set definition): + // {scope}/providers/Microsoft.Authorization/policySetDefinitions/{name} + // and for built-in policy-set-definition + // /providers/Microsoft.Authorization/policySetDefinitions/{name} regex := regexp.MustCompile(`/providers/[Mm]icrosoft\.[Aa]uthorization/policy[Ss]et[Dd]efinitions/`) if !regex.MatchString(input) { return nil, fmt.Errorf("unable to parse Policy Set Definition ID %q", input) @@ -31,6 +33,12 @@ func PolicySetDefinitionID(input string) (*PolicySetDefinitionId, error) { return nil, fmt.Errorf("unable to parse Policy Set Definition ID %q: set definition name is empty", input) } + if scope == "" { + return &PolicySetDefinitionId{ + Name: name, + }, nil + } + scopeId, err := PolicyScopeID(scope) if err != nil { return nil, fmt.Errorf("unable to parse Policy Set Definition ID %q: %+v", input, err) diff --git a/azurerm/internal/services/policy/tests/policy_assignment_resource_test.go b/azurerm/internal/services/policy/tests/policy_assignment_resource_test.go index 0872f410d112e..d00e4568b3663 100644 --- a/azurerm/internal/services/policy/tests/policy_assignment_resource_test.go +++ b/azurerm/internal/services/policy/tests/policy_assignment_resource_test.go @@ -47,6 +47,25 @@ func TestAccAzureRMPolicyAssignment_basicBuiltin(t *testing.T) { }) } +func TestAccAzureRMPolicyAssignment_basicBuiltInSet(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_policy_assignment", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMPolicyAssignmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAzureRMPolicyAssignment_basicBuiltInSet(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPolicyAssignmentExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + func TestAccAzureRMPolicyAssignment_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_policy_assignment", "test") resource.ParallelTest(t, resource.TestCase{ @@ -208,6 +227,34 @@ resource "azurerm_policy_assignment" "test" { `, data.RandomInteger, data.Locations.Primary) } +func testAzureRMPolicyAssignment_basicBuiltInSet(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +data "azurerm_policy_set_definition" "test" { + display_name = "Audit Windows VMs with a pending reboot" +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%[2]s" +} + +resource "azurerm_policy_assignment" "test" { + name = "acctestpa-%[1]d" + location = azurerm_resource_group.test.location + scope = azurerm_resource_group.test.id + policy_definition_id = data.azurerm_policy_set_definition.test.id + + identity { + type = "SystemAssigned" + } +} +`, data.RandomInteger, data.Locations.Primary) +} + func testAzureRMPolicyAssignment_basicBuiltin(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/azurerm/internal/services/policy/tests/policy_set_definition_data_source_test.go b/azurerm/internal/services/policy/tests/policy_set_definition_data_source_test.go index 643b3d85c544b..21ea87750f4a1 100644 --- a/azurerm/internal/services/policy/tests/policy_set_definition_data_source_test.go +++ b/azurerm/internal/services/policy/tests/policy_set_definition_data_source_test.go @@ -8,7 +8,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" ) -func TestAccDataSourceAzureRMPolicySetDefinition_byName(t *testing.T) { +func TestAccDataSourceAzureRMPolicySetDefinition_builtIn(t *testing.T) { data := acceptance.BuildTestData(t, "data.azurerm_policy_set_definition", "test") resource.ParallelTest(t, resource.TestCase{ @@ -17,7 +17,29 @@ func TestAccDataSourceAzureRMPolicySetDefinition_byName(t *testing.T) { CheckDestroy: testCheckAzureRMPolicySetDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccDataSourceAzureRMPolicySetDefinition_byName(data), + Config: testAccDataSourceAzureRMPolicySetDefinition_builtIn("Audit Windows VMs with a pending reboot"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(data.ResourceName, "name", "c96b2a9c-6fab-4ac2-ae21-502143491cd4"), + resource.TestCheckResourceAttr(data.ResourceName, "displayName", "Audit Windows VMs with a pending reboot"), + resource.TestCheckResourceAttr(data.ResourceName, "policy_type", "BuiltIn"), + resource.TestCheckResourceAttrSet(data.ResourceName, "parameters"), + resource.TestCheckResourceAttrSet(data.ResourceName, "policy_definitions"), + ), + }, + }, + }) +} + +func TestAccDataSourceAzureRMPolicySetDefinition_customByName(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_policy_set_definition", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMPolicySetDefinitionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAzureRMPolicySetDefinition_customByName(data), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(data.ResourceName, "name", fmt.Sprintf("acctestPolSet-%d", data.RandomInteger)), resource.TestCheckResourceAttr(data.ResourceName, "display_name", fmt.Sprintf("acctestPolSet-display-%d", data.RandomInteger)), @@ -30,7 +52,7 @@ func TestAccDataSourceAzureRMPolicySetDefinition_byName(t *testing.T) { }) } -func TestAccDataSourceAzureRMPolicySetDefinition_byDisplayName(t *testing.T) { +func TestAccDataSourceAzureRMPolicySetDefinition_customByDisplayName(t *testing.T) { data := acceptance.BuildTestData(t, "data.azurerm_policy_set_definition", "test") resource.ParallelTest(t, resource.TestCase{ @@ -39,7 +61,7 @@ func TestAccDataSourceAzureRMPolicySetDefinition_byDisplayName(t *testing.T) { CheckDestroy: testCheckAzureRMPolicySetDefinitionDestroy, Steps: []resource.TestStep{ { - Config: testAccDataSourceAzureRMPolicySetDefinition_byDisplayName(data), + Config: testAccDataSourceAzureRMPolicySetDefinition_customByDisplayName(data), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(data.ResourceName, "name", fmt.Sprintf("acctestPolSet-%d", data.RandomInteger)), resource.TestCheckResourceAttr(data.ResourceName, "display_name", fmt.Sprintf("acctestPolSet-display-%d", data.RandomInteger)), @@ -52,7 +74,19 @@ func TestAccDataSourceAzureRMPolicySetDefinition_byDisplayName(t *testing.T) { }) } -func testAccDataSourceAzureRMPolicySetDefinition_byName(data acceptance.TestData) string { +func testAccDataSourceAzureRMPolicySetDefinition_builtIn(name string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +data "azurerm_policy_set_definition" "test" { + display_name = "%s" +} +`, name) +} + +func testAccDataSourceAzureRMPolicySetDefinition_customByName(data acceptance.TestData) string { template := testAzureRMPolicySetDefinition_custom(data) return fmt.Sprintf(` %s @@ -63,7 +97,7 @@ data "azurerm_policy_set_definition" "test" { `, template) } -func testAccDataSourceAzureRMPolicySetDefinition_byDisplayName(data acceptance.TestData) string { +func testAccDataSourceAzureRMPolicySetDefinition_customByDisplayName(data acceptance.TestData) string { template := testAzureRMPolicySetDefinition_custom(data) return fmt.Sprintf(` %s From cae117e30194d44d3b4e978cb512c246896c8c84 Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 7 May 2020 15:14:55 -0700 Subject: [PATCH 003/104] update CHANGELOG.md to include #6792 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecf5f77f3a069..e22f67ad1b9c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ BUG FIXES: * `azurerm_analysis_services_server` - ip restriction name field no longer case sensitive [GH-6774] * `azurerm_eventhub_namespace_authorization_rule` - lock to prevent multiple resources won't clash [GH-6701] * `azurerm_network_interface` - changes to dns servers no longer use incremental update [GH-6624] +* `azurerm_policy_assignment` - allow polices with scopes without `subscription/` (built-in policies) [GH-6792] * `azurerm_policy_definition` - changes to the dynamic fields (`createdBy`, `createdOn`, `updatedBy`, `updatedOn`) keys in the `metadata` field are excluded from diff's [GH-6734] * `azurerm_site_recovery_network_mapping` - handling an API Error when checking for the presence of an existing Network Mapping [GH-6747] From 090deae255362612360707fd45bb3eed61e91bd7 Mon Sep 17 00:00:00 2001 From: njucz Date: Fri, 8 May 2020 06:55:27 +0800 Subject: [PATCH 004/104] `azurerm_automation_runbook` - add support for create runbook as draft and then publish (#6813) fixes #6588 fixes #4403 fixes #3086 --- .../automation/automation_runbook_resource.go | 45 +++++++++++-------- .../tests/automation_runbook_resource_test.go | 19 ++++---- .../docs/r/automation_runbook.html.markdown | 8 +--- 3 files changed, 38 insertions(+), 34 deletions(-) diff --git a/azurerm/internal/services/automation/automation_runbook_resource.go b/azurerm/internal/services/automation/automation_runbook_resource.go index b7a850fc74830..78bce62e8dea0 100644 --- a/azurerm/internal/services/automation/automation_runbook_resource.go +++ b/azurerm/internal/services/automation/automation_runbook_resource.go @@ -87,15 +87,18 @@ func resourceArmAutomationRunbook() *schema.Resource { }, "content": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + AtLeastOneOf: []string{"content", "publish_content_link"}, + ValidateFunc: validation.StringIsNotEmpty, }, "publish_content_link": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + AtLeastOneOf: []string{"content", "publish_content_link"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "uri": { @@ -166,21 +169,25 @@ func resourceArmAutomationRunbookCreateUpdate(d *schema.ResourceData, meta inter logVerbose := d.Get("log_verbose").(bool) description := d.Get("description").(string) - contentLink := expandContentLink(d) - parameters := automation.RunbookCreateOrUpdateParameters{ RunbookCreateOrUpdateProperties: &automation.RunbookCreateOrUpdateProperties{ - LogVerbose: &logVerbose, - LogProgress: &logProgress, - RunbookType: runbookType, - Description: &description, - PublishContentLink: &contentLink, + LogVerbose: &logVerbose, + LogProgress: &logProgress, + RunbookType: runbookType, + Description: &description, }, Location: &location, Tags: tags.Expand(t), } + contentLink := expandContentLink(d.Get("publish_content_link").([]interface{})) + if contentLink != nil { + parameters.RunbookCreateOrUpdateProperties.PublishContentLink = contentLink + } else { + parameters.RunbookCreateOrUpdateProperties.Draft = &automation.RunbookDraft{} + } + if _, err := client.CreateOrUpdate(ctx, resGroup, accName, name, parameters); err != nil { return fmt.Errorf("Error creating/updating Automation Runbook %q (Account %q / Resource Group %q): %+v", name, accName, resGroup, err) } @@ -298,12 +305,14 @@ func resourceArmAutomationRunbookDelete(d *schema.ResourceData, meta interface{} return nil } -func expandContentLink(d *schema.ResourceData) automation.ContentLink { - inputs := d.Get("publish_content_link").([]interface{}) +func expandContentLink(inputs []interface{}) *automation.ContentLink { + if len(inputs) == 0 || inputs[0] == nil { + return nil + } + input := inputs[0].(map[string]interface{}) uri := input["uri"].(string) version := input["version"].(string) - hashes := input["hash"].([]interface{}) if len(hashes) > 0 { @@ -311,7 +320,7 @@ func expandContentLink(d *schema.ResourceData) automation.ContentLink { hashValue := hash["value"].(string) hashAlgorithm := hash["algorithm"].(string) - return automation.ContentLink{ + return &automation.ContentLink{ URI: &uri, Version: &version, ContentHash: &automation.ContentHash{ @@ -321,7 +330,7 @@ func expandContentLink(d *schema.ResourceData) automation.ContentLink { } } - return automation.ContentLink{ + return &automation.ContentLink{ URI: &uri, Version: &version, } diff --git a/azurerm/internal/services/automation/tests/automation_runbook_resource_test.go b/azurerm/internal/services/automation/tests/automation_runbook_resource_test.go index a52c0c863c000..c7facc8545738 100644 --- a/azurerm/internal/services/automation/tests/automation_runbook_resource_test.go +++ b/azurerm/internal/services/automation/tests/automation_runbook_resource_test.go @@ -23,7 +23,6 @@ func TestAccAzureRMAutomationRunbook_PSWorkflow(t *testing.T) { Config: testAccAzureRMAutomationRunbook_PSWorkflow(data), Check: resource.ComposeTestCheckFunc( testCheckAzureRMAutomationRunbookExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "runbook_type", "PowerShellWorkflow"), ), }, data.ImportStep("publish_content_link"), @@ -184,11 +183,12 @@ resource "azurerm_automation_runbook" "test" { log_verbose = "true" log_progress = "true" description = "This is a test runbook for terraform acceptance test" - runbook_type = "PowerShellWorkflow" + runbook_type = "PowerShell" - publish_content_link { - uri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/c4935ffb69246a6058eb24f54640f53f69d3ac9f/101-automation-runbook-getvms/Runbooks/Get-AzureVMTutorial.ps1" - } + content = < **NOTE** The Azure API requires a `publish_content_link` to be supplied even when specifying your own `content`. -~> **NOTE** Setting `content` to an empty string will revert the runbook to the `publish_content_link`. - * `tags` - (Optional) A mapping of tags to assign to the resource. `publish_content_link` supports the following: From 44bb6ad307976ff92c6d6dfef24f150d0d6e404b Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 7 May 2020 15:57:03 -0700 Subject: [PATCH 005/104] update CHANGELOG.md to include #6813 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e22f67ad1b9c1..c5ba5bf1bb7c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ BUG FIXES: * provider: raising an error when the environment is set to `AZURESTACKCLOUD` [GH-6817] * `azurerm_analysis_services_server` - ip restriction name field no longer case sensitive [GH-6774] +* `azurerm_automation_runbook` - the `publish_content_link` property is now optional [GH-6813] * `azurerm_eventhub_namespace_authorization_rule` - lock to prevent multiple resources won't clash [GH-6701] * `azurerm_network_interface` - changes to dns servers no longer use incremental update [GH-6624] * `azurerm_policy_assignment` - allow polices with scopes without `subscription/` (built-in policies) [GH-6792] From 4b4a54e02b7323e329eebf8152372514ec4be241 Mon Sep 17 00:00:00 2001 From: Clara McKenzie Date: Thu, 7 May 2020 16:15:31 -0700 Subject: [PATCH 006/104] [BUG] azurerm_redis_cache backup requires connection string (#6819) --- azurerm/internal/services/redis/resource_arm_redis_cache.go | 5 +++++ website/docs/r/redis_cache.html.markdown | 3 +++ 2 files changed, 8 insertions(+) diff --git a/azurerm/internal/services/redis/resource_arm_redis_cache.go b/azurerm/internal/services/redis/resource_arm_redis_cache.go index 52935aebc0233..0738a86250c92 100644 --- a/azurerm/internal/services/redis/resource_arm_redis_cache.go +++ b/azurerm/internal/services/redis/resource_arm_redis_cache.go @@ -672,6 +672,11 @@ func expandRedisConfiguration(d *schema.ResourceData) (map[string]*string, error // RDB Backup if v, ok := d.GetOk("redis_configuration.0.rdb_backup_enabled"); ok { + if v.(bool) { + if connStr, connOk := d.GetOk("redis_configuration.0.rdb_storage_connection_string"); !connOk || connStr.(string) == "" { + return nil, fmt.Errorf("The rdb_storage_connection_string property must be set when rdb_backup_enabled is true") + } + } delta := strconv.FormatBool(v.(bool)) output["rdb-backup-enabled"] = utils.String(delta) } diff --git a/website/docs/r/redis_cache.html.markdown b/website/docs/r/redis_cache.html.markdown index d233a54a10d0f..9739e59971ffe 100644 --- a/website/docs/r/redis_cache.html.markdown +++ b/website/docs/r/redis_cache.html.markdown @@ -92,6 +92,9 @@ A `redis_configuration` block supports the following: * `maxfragmentationmemory_reserved` - (Optional) Value in megabytes reserved to accommodate for memory fragmentation. Defaults are shown below. * `rdb_backup_enabled` - (Optional) Is Backup Enabled? Only supported on Premium SKU's. + +-> **NOTE:** If `rdb_backup_enabled` set to `true`, `rdb_storage_connection_string` must also be set. + * `rdb_backup_frequency` - (Optional) The Backup Frequency in Minutes. Only supported on Premium SKU's. Possible values are: `15`, `30`, `60`, `360`, `720` and `1440`. * `rdb_backup_max_snapshot_count` - (Optional) The maximum number of snapshots to create as a backup. Only supported for Premium SKU's. * `rdb_storage_connection_string` - (Optional) The Connection String to the Storage Account. Only supported for Premium SKU's. In the format: `DefaultEndpointsProtocol=https;BlobEndpoint=${azurerm_storage_account.example.primary_blob_endpoint};AccountName=${azurerm_storage_account.example.name};AccountKey=${azurerm_storage_account.example.primary_access_key}`. From e78759033d6c00ca0a128927ae023c1b771c7f48 Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 7 May 2020 16:16:57 -0700 Subject: [PATCH 007/104] update CHANGELOG.md to include #6819 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5ba5bf1bb7c3..5689d975b3674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ BUG FIXES: * `azurerm_network_interface` - changes to dns servers no longer use incremental update [GH-6624] * `azurerm_policy_assignment` - allow polices with scopes without `subscription/` (built-in policies) [GH-6792] * `azurerm_policy_definition` - changes to the dynamic fields (`createdBy`, `createdOn`, `updatedBy`, `updatedOn`) keys in the `metadata` field are excluded from diff's [GH-6734] +* `azurerm_redis_cache` - ensure `rdb_storage_connection_string` is set when `rdb_backup_enabled` is enabled [GH-6819] * `azurerm_site_recovery_network_mapping` - handling an API Error when checking for the presence of an existing Network Mapping [GH-6747] ## 2.8.0 (April 30, 2020) From d4da9b2012c386c5c5e181aca03e19b88171a2e7 Mon Sep 17 00:00:00 2001 From: tf-release-bot Date: Fri, 8 May 2020 00:02:50 +0000 Subject: [PATCH 008/104] v2.9.0 --- CHANGELOG.md | 62 ++++++++++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5689d975b3674..b523df8559f64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,43 +1,43 @@ -## 2.9.0 (Unreleased) +## 2.9.0 (May 07, 2020) FEATURES: -* **New Data Source:** `azurerm_data_share_account` [GH-6575] -* **New Resource:** `azurerm_data_share_account` [GH-6575] -* **New Resource:** `azurerm_function_app_slot` [GH-6435] -* **New Resource:** `azurerm_sentinel_alert_rule_scheduled` [GH-6650] +* **New Data Source:** `azurerm_data_share_account` ([#6575](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6575)) +* **New Resource:** `azurerm_data_share_account` ([#6575](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6575)) +* **New Resource:** `azurerm_function_app_slot` ([#6435](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6435)) +* **New Resource:** `azurerm_sentinel_alert_rule_scheduled` ([#6650](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6650)) IMPROVEMENTS: -* Data Source: `azurerm_eventhub_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties [GH-6708] -* Data Source: `azurerm_eventhub_namespace_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties [GH-6708] -* Data Source: `azurerm_eventhub_namespace` - support for the `default_primary_connection_string_alias` an `_defaultsecondary_connection_string_alias` propeties [GH-6708] -* `azurerm_analysis_services_server` - support updating when the Server is paused [GH-6786] -* `azurerm_app_service` - support for health_check_path preview feature added [GH-6661] -* `azurerm_app_service` - support for `name` and `priority` on `ip_restrictions` [GH-6705] -* `azurerm_application_gateway` - support for SSL Certificates without passwords [GH-6742] -* `azurerm_eventhub_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties [GH-6708] -* `azurerm_eventhub_namespace_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties [GH-6708] -* `azurerm_eventhub_namespace` - support for the `default_primary_connection_string_alias` an `_defaultsecondary_connection_string_alias` propeties [GH-6708] -* `azurerm_hdinsight_hadoop_cluster` - support for metastores on cluster creation [GH-6145] -* `azurerm_key_vault_certificate` - support for recovering a soft-deleted certificate if the `features` flag `recover_soft_deleted_key_vaults` is set to `true` [GH-6716] -* `azurerm_key_vault_key` - support for recovering a soft-deleted key if the `features` flag `recover_soft_deleted_key_vaults` is set to `true` [GH-6716] -* `azurerm_key_vault_secret` - support for recovering a soft-deleted secret if the `features` flag `recover_soft_deleted_key_vaults` is set to `true` [GH-6716] -* `azurerm_linux_virtual_machine_scale_set` - support for configuring `create_mode` for data disks [GH-6744] -* `azurerm_monitor_diagnostic_setting` - `log_analytics_destination_type` supports `AzureDiagnostics` [GH-6769] -* `azurerm_windows_virtual_machine_scale_set` - support for configuring `create_mode` for data disks [GH-6744] +* Data Source: `azurerm_eventhub_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties ([#6708](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6708)) +* Data Source: `azurerm_eventhub_namespace_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties ([#6708](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6708)) +* Data Source: `azurerm_eventhub_namespace` - support for the `default_primary_connection_string_alias` an `_defaultsecondary_connection_string_alias` propeties ([#6708](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6708)) +* `azurerm_analysis_services_server` - support updating when the Server is paused ([#6786](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6786)) +* `azurerm_app_service` - support for health_check_path preview feature added ([#6661](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6661)) +* `azurerm_app_service` - support for `name` and `priority` on `ip_restrictions` ([#6705](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6705)) +* `azurerm_application_gateway` - support for SSL Certificates without passwords ([#6742](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6742)) +* `azurerm_eventhub_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties ([#6708](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6708)) +* `azurerm_eventhub_namespace_authorization_rule` - support for the `primary_connection_string_alias` an `secondary_connection_string_alias` propeties ([#6708](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6708)) +* `azurerm_eventhub_namespace` - support for the `default_primary_connection_string_alias` an `_defaultsecondary_connection_string_alias` propeties ([#6708](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6708)) +* `azurerm_hdinsight_hadoop_cluster` - support for metastores on cluster creation ([#6145](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6145)) +* `azurerm_key_vault_certificate` - support for recovering a soft-deleted certificate if the `features` flag `recover_soft_deleted_key_vaults` is set to `true` ([#6716](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6716)) +* `azurerm_key_vault_key` - support for recovering a soft-deleted key if the `features` flag `recover_soft_deleted_key_vaults` is set to `true` ([#6716](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6716)) +* `azurerm_key_vault_secret` - support for recovering a soft-deleted secret if the `features` flag `recover_soft_deleted_key_vaults` is set to `true` ([#6716](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6716)) +* `azurerm_linux_virtual_machine_scale_set` - support for configuring `create_mode` for data disks ([#6744](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6744)) +* `azurerm_monitor_diagnostic_setting` - `log_analytics_destination_type` supports `AzureDiagnostics` ([#6769](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6769)) +* `azurerm_windows_virtual_machine_scale_set` - support for configuring `create_mode` for data disks ([#6744](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6744)) BUG FIXES: -* provider: raising an error when the environment is set to `AZURESTACKCLOUD` [GH-6817] -* `azurerm_analysis_services_server` - ip restriction name field no longer case sensitive [GH-6774] -* `azurerm_automation_runbook` - the `publish_content_link` property is now optional [GH-6813] -* `azurerm_eventhub_namespace_authorization_rule` - lock to prevent multiple resources won't clash [GH-6701] -* `azurerm_network_interface` - changes to dns servers no longer use incremental update [GH-6624] -* `azurerm_policy_assignment` - allow polices with scopes without `subscription/` (built-in policies) [GH-6792] -* `azurerm_policy_definition` - changes to the dynamic fields (`createdBy`, `createdOn`, `updatedBy`, `updatedOn`) keys in the `metadata` field are excluded from diff's [GH-6734] -* `azurerm_redis_cache` - ensure `rdb_storage_connection_string` is set when `rdb_backup_enabled` is enabled [GH-6819] -* `azurerm_site_recovery_network_mapping` - handling an API Error when checking for the presence of an existing Network Mapping [GH-6747] +* provider: raising an error when the environment is set to `AZURESTACKCLOUD` ([#6817](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6817)) +* `azurerm_analysis_services_server` - ip restriction name field no longer case sensitive ([#6774](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6774)) +* `azurerm_automation_runbook` - the `publish_content_link` property is now optional ([#6813](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6813)) +* `azurerm_eventhub_namespace_authorization_rule` - lock to prevent multiple resources won't clash ([#6701](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6701)) +* `azurerm_network_interface` - changes to dns servers no longer use incremental update ([#6624](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6624)) +* `azurerm_policy_assignment` - allow polices with scopes without `subscription/` (built-in policies) ([#6792](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6792)) +* `azurerm_policy_definition` - changes to the dynamic fields (`createdBy`, `createdOn`, `updatedBy`, `updatedOn`) keys in the `metadata` field are excluded from diff's ([#6734](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6734)) +* `azurerm_redis_cache` - ensure `rdb_storage_connection_string` is set when `rdb_backup_enabled` is enabled ([#6819](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6819)) +* `azurerm_site_recovery_network_mapping` - handling an API Error when checking for the presence of an existing Network Mapping ([#6747](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6747)) ## 2.8.0 (April 30, 2020) From 528740f357677686a1c50ecfc822d145c488946a Mon Sep 17 00:00:00 2001 From: tf-release-bot Date: Fri, 8 May 2020 00:22:04 +0000 Subject: [PATCH 009/104] Cleanup after v2.9.0 release --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b523df8559f64..bdaca7f4de820 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ +## 2.10.0 (Unreleased) ## 2.9.0 (May 07, 2020) FEATURES: From f4d116a649a88ada71f1be736f6e2a0df49492f3 Mon Sep 17 00:00:00 2001 From: Chang Li Date: Sat, 9 May 2020 02:01:35 +0800 Subject: [PATCH 010/104] Update express_route_circuit_peering.html.markdown (#6824) --- website/docs/r/express_route_circuit_peering.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/website/docs/r/express_route_circuit_peering.html.markdown b/website/docs/r/express_route_circuit_peering.html.markdown index 3d003c654f864..4d192756cdd3e 100644 --- a/website/docs/r/express_route_circuit_peering.html.markdown +++ b/website/docs/r/express_route_circuit_peering.html.markdown @@ -66,9 +66,9 @@ The following arguments are supported: * `resource_group_name` - (Required) The name of the resource group in which to create the Express Route Circuit Peering. Changing this forces a new resource to be created. -* `primary_peer_address_prefix` - (Optional) A `/30` subnet for the primary link. -* `secondary_peer_address_prefix` - (Optional) A `/30` subnet for the secondary link. -* `vlan_id` - (Optional) A valid VLAN ID to establish this peering on. +* `primary_peer_address_prefix` - (Required) A `/30` subnet for the primary link. +* `secondary_peer_address_prefix` - (Required) A `/30` subnet for the secondary link. +* `vlan_id` - (Required) A valid VLAN ID to establish this peering on. * `shared_key` - (Optional) The shared key. Can be a maximum of 25 characters. * `peer_asn` - (Optional) The Either a 16-bit or a 32-bit ASN. Can either be public or private.. * `microsoft_peering_config` - (Optional) A `microsoft_peering_config` block as defined below. Required when `peering_type` is set to `MicrosoftPeering`. From 745543c746aaefa7aec2d0e900e29158c198baf4 Mon Sep 17 00:00:00 2001 From: Yuping Wei <56525716+yupwei68@users.noreply.github.com> Date: Sat, 9 May 2020 04:33:58 +0800 Subject: [PATCH 011/104] `azurerm_mssql_server` - Add support for `azuread_administrator` (#6822) --- .../internal/services/mssql/client/client.go | 5 + .../services/mssql/mssql_server_resource.go | 120 ++++++++++- .../mssql/tests/mssql_server_resource_test.go | 203 ++++++++++++++++++ website/docs/r/mssql_server.html.markdown | 17 ++ 4 files changed, 344 insertions(+), 1 deletion(-) diff --git a/azurerm/internal/services/mssql/client/client.go b/azurerm/internal/services/mssql/client/client.go index 7588bcdc51ee9..9c3f834b38238 100644 --- a/azurerm/internal/services/mssql/client/client.go +++ b/azurerm/internal/services/mssql/client/client.go @@ -12,6 +12,7 @@ type Client struct { DatabaseThreatDetectionPoliciesClient *sql.DatabaseThreatDetectionPoliciesClient ElasticPoolsClient *sql.ElasticPoolsClient DatabaseVulnerabilityAssessmentRuleBaselinesClient *sql.DatabaseVulnerabilityAssessmentRuleBaselinesClient + ServerAzureADAdministratorsClient *sql.ServerAzureADAdministratorsClient ServersClient *sql.ServersClient ServerExtendedBlobAuditingPoliciesClient *sql.ExtendedServerBlobAuditingPoliciesClient ServerConnectionPoliciesClient *sql.ServerConnectionPoliciesClient @@ -45,6 +46,9 @@ func NewClient(o *common.ClientOptions) *Client { serverVulnerabilityAssessmentsClient := sql.NewServerVulnerabilityAssessmentsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&serverVulnerabilityAssessmentsClient.Client, o.ResourceManagerAuthorizer) + serverAzureADAdministratorsClient := sql.NewServerAzureADAdministratorsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&serverAzureADAdministratorsClient.Client, o.ResourceManagerAuthorizer) + serversClient := sql.NewServersClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&serversClient.Client, o.ResourceManagerAuthorizer) @@ -60,6 +64,7 @@ func NewClient(o *common.ClientOptions) *Client { DatabaseThreatDetectionPoliciesClient: &databaseThreatDetectionPoliciesClient, DatabaseVulnerabilityAssessmentRuleBaselinesClient: &databaseVulnerabilityAssessmentRuleBaselinesClient, ElasticPoolsClient: &elasticPoolsClient, + ServerAzureADAdministratorsClient: &serverAzureADAdministratorsClient, ServersClient: &serversClient, ServerExtendedBlobAuditingPoliciesClient: &serverExtendedBlobAuditingPoliciesClient, ServerConnectionPoliciesClient: &serverConnectionPoliciesClient, diff --git a/azurerm/internal/services/mssql/mssql_server_resource.go b/azurerm/internal/services/mssql/mssql_server_resource.go index 24f91f67a219f..e27645b54c3a9 100644 --- a/azurerm/internal/services/mssql/mssql_server_resource.go +++ b/azurerm/internal/services/mssql/mssql_server_resource.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + uuid "github.com/satori/go.uuid" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" @@ -71,6 +72,35 @@ func resourceArmMsSqlServer() *schema.Resource { Sensitive: true, }, + "azuread_administrator": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + MinItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "login_username": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "object_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.IsUUID, + }, + + "tenant_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.IsUUID, + }, + }, + }, + }, + "connection_policy": { Type: schema.TypeString, Optional: true, @@ -129,6 +159,7 @@ func resourceArmMsSqlServerCreateUpdate(d *schema.ResourceData, meta interface{} client := meta.(*clients.Client).MSSQL.ServersClient auditingClient := meta.(*clients.Client).MSSQL.ServerExtendedBlobAuditingPoliciesClient connectionClient := meta.(*clients.Client).MSSQL.ServerConnectionPoliciesClient + adminClient := meta.(*clients.Client).MSSQL.ServerAzureADAdministratorsClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -198,6 +229,28 @@ func resourceArmMsSqlServerCreateUpdate(d *schema.ResourceData, meta interface{} d.SetId(*resp.ID) + if d.HasChange("azuread_administrator") { + adminDelFuture, err := adminClient.Delete(ctx, resGroup, name) + if err != nil { + return fmt.Errorf("deleting SQL Server %q AAD admin (Resource Group %q): %+v", name, resGroup, err) + } + + if err = adminDelFuture.WaitForCompletionRef(ctx, adminClient.Client); err != nil { + return fmt.Errorf("waiting for SQL Server %q AAD admin (Resource Group %q) to be deleted: %+v", name, resGroup, err) + } + + if adminParams := expandAzureRmMsSqlServerAdministrator(d.Get("azuread_administrator").([]interface{})); adminParams != nil { + adminFuture, err := adminClient.CreateOrUpdate(ctx, resGroup, name, *adminParams) + if err != nil { + return fmt.Errorf("creating SQL Server %q AAD admin (Resource Group %q): %+v", name, resGroup, err) + } + + if err = adminFuture.WaitForCompletionRef(ctx, adminClient.Client); err != nil { + return fmt.Errorf("waiting for creation of SQL Server %q AAD admin (Resource Group %q): %+v", name, resGroup, err) + } + } + } + connection := sql.ServerConnectionPolicy{ ServerConnectionPolicyProperties: &sql.ServerConnectionPolicyProperties{ ConnectionType: sql.ServerConnectionType(d.Get("connection_policy").(string)), @@ -210,10 +263,16 @@ func resourceArmMsSqlServerCreateUpdate(d *schema.ResourceData, meta interface{} auditingProps := sql.ExtendedServerBlobAuditingPolicy{ ExtendedServerBlobAuditingPolicyProperties: helper.ExpandAzureRmSqlServerBlobAuditingPolicies(d.Get("extended_auditing_policy").([]interface{})), } - if _, err = auditingClient.CreateOrUpdate(ctx, resGroup, name, auditingProps); err != nil { + + auditingFuture, err := auditingClient.CreateOrUpdate(ctx, resGroup, name, auditingProps) + if err != nil { return fmt.Errorf("Error issuing create/update request for SQL Server %q Blob Auditing Policies(Resource Group %q): %+v", name, resGroup, err) } + if err = auditingFuture.WaitForCompletionRef(ctx, auditingClient.Client); err != nil { + return fmt.Errorf("waiting for creation of SQL Server %q Blob Auditing Policies(Resource Group %q): %+v", name, resGroup, err) + } + return resourceArmMsSqlServerRead(d, meta) } @@ -221,6 +280,7 @@ func resourceArmMsSqlServerRead(d *schema.ResourceData, meta interface{}) error client := meta.(*clients.Client).MSSQL.ServersClient auditingClient := meta.(*clients.Client).MSSQL.ServerExtendedBlobAuditingPoliciesClient connectionClient := meta.(*clients.Client).MSSQL.ServerConnectionPoliciesClient + adminClient := meta.(*clients.Client).MSSQL.ServerAzureADAdministratorsClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -260,6 +320,17 @@ func resourceArmMsSqlServerRead(d *schema.ResourceData, meta interface{}) error d.Set("public_network_access_enabled", props.PublicNetworkAccess == sql.ServerPublicNetworkAccessEnabled) } + adminResp, err := adminClient.Get(ctx, resGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(adminResp.Response) { + return fmt.Errorf("Error reading SQL Server %s AAD admin: %v", name, err) + } + } else { + if err := d.Set("azuread_administrator", flatternAzureRmMsSqlServerAdministrator(adminResp)); err != nil { + return fmt.Errorf("setting `azuread_administrator`: %+v", err) + } + } + connection, err := connectionClient.Get(ctx, resGroup, name) if err != nil { return fmt.Errorf("Error reading SQL Server %s Blob Connection Policy: %v ", name, err) @@ -328,3 +399,50 @@ func flattenAzureRmSqlServerIdentity(identity *sql.ResourceIdentity) []interface return []interface{}{result} } + +func expandAzureRmMsSqlServerAdministrator(input []interface{}) *sql.ServerAzureADAdministrator { + if len(input) == 0 || input[0] == nil { + return nil + } + + admin := input[0].(map[string]interface{}) + sid, _ := uuid.FromString(admin["object_id"].(string)) + + adminParams := sql.ServerAzureADAdministrator{ + AdministratorProperties: &sql.AdministratorProperties{ + AdministratorType: utils.String("ActiveDirectory"), + Login: utils.String(admin["login_username"].(string)), + Sid: &sid, + }, + } + + if v, ok := admin["tenant_id"]; ok && v != "" { + tid, _ := uuid.FromString(v.(string)) + adminParams.TenantID = &tid + } + + return &adminParams +} + +func flatternAzureRmMsSqlServerAdministrator(admin sql.ServerAzureADAdministrator) []interface{} { + var login, sid, tid string + if admin.Login != nil { + login = *admin.Login + } + + if admin.Sid != nil { + sid = admin.Sid.String() + } + + if admin.TenantID != nil { + tid = admin.TenantID.String() + } + + return []interface{}{ + map[string]interface{}{ + "login_username": login, + "object_id": sid, + "tenant_id": tid, + }, + } +} diff --git a/azurerm/internal/services/mssql/tests/mssql_server_resource_test.go b/azurerm/internal/services/mssql/tests/mssql_server_resource_test.go index 3c8c9bdc29ec8..5b30efa30a29c 100644 --- a/azurerm/internal/services/mssql/tests/mssql_server_resource_test.go +++ b/azurerm/internal/services/mssql/tests/mssql_server_resource_test.go @@ -2,6 +2,7 @@ package tests import ( "fmt" + "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" @@ -147,6 +148,79 @@ func TestAccAzureRMMsSqlServer_identity(t *testing.T) { }) } +func TestAccAzureRMMsSqlServer_azureadAdmin(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mssql_server", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlServer_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), + { + Config: testAccAzureRMMsSqlServer_azureadAdmin(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), + { + Config: testAccAzureRMMsSqlServer_azureadAdminUpdate(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), + { + Config: testAccAzureRMMsSqlServer_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), + }, + }) +} + +func TestAccAzureRMMsSqlServer_blobAuditingPolicies_withFirewall(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mssql_server", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlServer_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password", "extended_auditing_policy.0.storage_account_access_key"), + { + Config: testAccAzureRMMsSqlServer_blobAuditingPolicies_withFirewall(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password", "extended_auditing_policy.0.storage_account_access_key"), + { + Config: testAccAzureRMMsSqlServer_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password", "extended_auditing_policy.0.storage_account_access_key"), + }, + }) +} + func testCheckAzureRMMsSqlServerExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { conn := acceptance.AzureProvider.Meta().(*clients.Client).Sql.ServersClient @@ -376,3 +450,132 @@ resource "azurerm_mssql_server" "test" { } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } + +func testAccAzureRMMsSqlServer_azureadAdmin(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-mssql-%[1]d" + location = "%[2]s" +} + +data "azuread_service_principal" "test" { + application_id = "%[3]s" +} + +resource "azurerm_mssql_server" "test" { + name = "acctestsqlserver%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + version = "12.0" + administrator_login = "missadministrator" + administrator_login_password = "thisIsKat11" + + azuread_administrator { + login_username = "AzureAD Admin" + object_id = data.azuread_service_principal.test.id + } +} +`, data.RandomInteger, data.Locations.Primary, os.Getenv("ARM_CLIENT_ID")) +} + +func testAccAzureRMMsSqlServer_azureadAdminUpdate(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-mssql-%[1]d" + location = "%[2]s" +} + +data "azuread_service_principal" "test" { + application_id = "%[3]s" +} + +resource "azurerm_mssql_server" "test" { + name = "acctestsqlserver%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + version = "12.0" + administrator_login = "missadministrator" + administrator_login_password = "thisIsKat11" + + azuread_administrator { + login_username = "AzureAD Admin2" + object_id = data.azuread_service_principal.test.id + } +} +`, data.RandomInteger, data.Locations.Primary, os.Getenv("ARM_CLIENT_ID")) +} + +func testAccAzureRMMsSqlServer_blobAuditingPolicies_withFirewall(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-mssql-%[1]d" + location = "%[2]s" +} + +resource "azurerm_virtual_network" "test" { + name = "acctestvirtnet%[1]d" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} + +resource "azurerm_subnet" "test" { + name = "acctestsubnet%[1]d" + resource_group_name = azurerm_resource_group.test.name + virtual_network_name = azurerm_virtual_network.test.name + address_prefix = "10.0.2.0/24" + service_endpoints = ["Microsoft.Storage"] +} + +resource "azurerm_storage_account" "test" { + name = "unlikely23exst2acct%[3]s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" + + network_rules { + default_action = "Allow" + ip_rules = ["127.0.0.1"] + virtual_network_subnet_ids = [azurerm_subnet.test.id] + } +} + +data "azuread_service_principal" "test" { + application_id = "%[4]s" +} + +resource "azurerm_mssql_server" "test" { + name = "acctestsqlserver%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + version = "12.0" + administrator_login = "missadministrator" + administrator_login_password = "thisIsKat11" + + azuread_administrator { + login_username = "AzureAD Admin2" + object_id = data.azuread_service_principal.test.id + } + + extended_auditing_policy { + storage_account_access_key = azurerm_storage_account.test.primary_access_key + storage_endpoint = azurerm_storage_account.test.primary_blob_endpoint + storage_account_access_key_is_secondary = true + retention_in_days = 6 + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString, os.Getenv("ARM_CLIENT_ID")) +} diff --git a/website/docs/r/mssql_server.html.markdown b/website/docs/r/mssql_server.html.markdown index 430a07f9ec400..74fce80e497d1 100644 --- a/website/docs/r/mssql_server.html.markdown +++ b/website/docs/r/mssql_server.html.markdown @@ -38,6 +38,11 @@ resource "azurerm_mssql_server" "example" { administrator_login = "missadministrator" administrator_login_password = "thisIsKat11" + azuread_administrator { + login_username = "AzureAD Admin" + object_id = "00000000-0000-0000-0000-000000000000" + } + extended_auditing_policy { storage_endpoint = azurerm_storage_account.example.primary_blob_endpoint storage_account_access_key = azurerm_storage_account.example.primary_access_key @@ -66,6 +71,8 @@ The following arguments are supported: * `administrator_login_password` - (Required) The password associated with the `administrator_login` user. Needs to comply with Azure's [Password Policy](https://msdn.microsoft.com/library/ms161959.aspx) +* `azuread_administrator` - (Optional) An `azuread_administrator` block as defined below. + * `connection_policy` - (Optional) The connection policy the server will use. Possible values are `Default`, `Proxy`, and `Redirect`. Defaults to `Default`. * `identity` - (Optional) An `identity` block as defined below. @@ -102,6 +109,16 @@ The following attributes are exported: --- +A `azuread_administrator` block supports the following: + +* `login_username` - (Required) The login username of the Azure AD Administrator of this SQL Server. + +* `object_id` - (Required) The object id of the Azure AD Administrator of this SQL Server. + +* `tenant_id` - (Optional) The tenant id of the Azure AD Administrator of this SQL Server. + +--- + A `extended_auditing_policy` block supports the following: * `storage_account_access_key` - (Required) Specifies the access key to use for the auditing storage account. From 6be9d44ecd0359f3393db3380607c3deb38f4e43 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Fri, 8 May 2020 13:34:39 -0700 Subject: [PATCH 012/104] Update for #6822 --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdaca7f4de820..e3f6a3ea0159f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,9 @@ ## 2.10.0 (Unreleased) + +IMPROVEMENTS: + +* `azurerm_mssql_server` - Add support for `azuread_administrator` [GH-6822] + ## 2.9.0 (May 07, 2020) FEATURES: From a177e53f7fd9f5b2502136dbe7ead8dae0d98ee2 Mon Sep 17 00:00:00 2001 From: Tracy P Holmes <12778804+tracypholmes@users.noreply.github.com> Date: Fri, 8 May 2020 16:05:44 -0500 Subject: [PATCH 013/104] docs: added note to `infrastructure_encryption_enabled` property (#6831) --- website/docs/r/postgresql_server.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/r/postgresql_server.html.markdown b/website/docs/r/postgresql_server.html.markdown index 904841049d539..7aa92293383df 100644 --- a/website/docs/r/postgresql_server.html.markdown +++ b/website/docs/r/postgresql_server.html.markdown @@ -75,6 +75,8 @@ The following arguments are supported: * `infrastructure_encryption_enabled` - (Optional) Whether or not infrastructure is encrypted for this server. Defaults to `false`. Changing this forces a new resource to be created. +~> **Note:** This property is currently still in development by Microsoft. It is suggested to leave as `false` as not doing so can lead to unclear error messages. + * `public_network_access_enabled` - (Optional) Whether or not public network access is allowed for this server. Defaults to `true`. * `restore_point_in_time` - (Optional) When `create_mode` is `PointInTimeRestore` the point in time to restore from `creation_source_server_id`. From 54d48df7b3706aa81d9aa988fe323086cff21e9d Mon Sep 17 00:00:00 2001 From: magodo Date: Sat, 9 May 2020 16:29:50 +0800 Subject: [PATCH 014/104] `azurerm_automation_account` DS set its own ID Previously, it uses the automation account agent registration info's ID as its ID, which cause other resource which refers to that ID will fail to parse the resource ID (as it doesn't apply to resource ID format). Nevertheless, we shall change to use the ID of resource `azurerm_automation_account` as the DS's ID. --- .../automation_account_data_source.go | 19 ++++++++++++++----- .../automation_account_data_source_test.go | 3 +++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/azurerm/internal/services/automation/automation_account_data_source.go b/azurerm/internal/services/automation/automation_account_data_source.go index c63bbb24198ab..2ced13127ebb8 100644 --- a/azurerm/internal/services/automation/automation_account_data_source.go +++ b/azurerm/internal/services/automation/automation_account_data_source.go @@ -44,7 +44,8 @@ func dataSourceArmAutomationAccount() *schema.Resource { } func dataSourceAutomationAccountRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*clients.Client).Automation.AgentRegistrationInfoClient + iclient := meta.(*clients.Client).Automation.AgentRegistrationInfoClient + client := meta.(*clients.Client).Automation.AccountClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -56,11 +57,19 @@ func dataSourceAutomationAccountRead(d *schema.ResourceData, meta interface{}) e if utils.ResponseWasNotFound(resp.Response) { return fmt.Errorf("Error: Automation Account %q (Resource Group %q) was not found", name, resourceGroupName) } - return fmt.Errorf("Error making Read request on Automation Account Registration Information %q (Resource Group %q): %+v", name, resourceGroupName, err) + return fmt.Errorf("Error making Read request on Automation %q (Resource Group %q): %+v", name, resourceGroupName, err) } d.SetId(*resp.ID) - d.Set("primary_key", resp.Keys.Primary) - d.Set("secondary_key", resp.Keys.Secondary) - d.Set("endpoint", resp.Endpoint) + + iresp, err := iclient.Get(ctx, resourceGroupName, name) + if err != nil { + if utils.ResponseWasNotFound(iresp.Response) { + return fmt.Errorf("Error: Automation Account Registration Information %q (Resource Group %q) was not found", name, resourceGroupName) + } + return fmt.Errorf("Error making Read request on Automation Account Registration Information %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + d.Set("primary_key", iresp.Keys.Primary) + d.Set("secondary_key", iresp.Keys.Secondary) + d.Set("endpoint", iresp.Endpoint) return nil } diff --git a/azurerm/internal/services/automation/tests/automation_account_data_source_test.go b/azurerm/internal/services/automation/tests/automation_account_data_source_test.go index 902c56fa0af6b..831b25f2a814e 100644 --- a/azurerm/internal/services/automation/tests/automation_account_data_source_test.go +++ b/azurerm/internal/services/automation/tests/automation_account_data_source_test.go @@ -2,6 +2,7 @@ package tests import ( "fmt" + "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" @@ -20,6 +21,8 @@ func TestAccDataSourceAutomationAccount(t *testing.T) { Config: testAccDataSourceAutomationAccount_complete(resourceGroupName, data), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(data.ResourceName, "resource_group_name", resourceGroupName), + resource.TestMatchResourceAttr(data.ResourceName, "id", + regexp.MustCompile(`^/subscriptions/[^/]+/resourceGroups/[^/]+/providers/Microsoft.Automation/automationAccounts/[^/]+$`)), ), }, }, From b2bc8ea46dd0b2d93c6ec8c0920245ef17689c6e Mon Sep 17 00:00:00 2001 From: Roy Dragseth Date: Sat, 9 May 2020 18:46:40 +0200 Subject: [PATCH 015/104] Fix load-balancer example with new syntax for v2.0 (#6836) --- .../2-vms-loadbalancer-lbrules/main.tf | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/examples/virtual-machines/virtual_machine/2-vms-loadbalancer-lbrules/main.tf b/examples/virtual-machines/virtual_machine/2-vms-loadbalancer-lbrules/main.tf index 2de6f93df24d5..4d77945afc1c1 100644 --- a/examples/virtual-machines/virtual_machine/2-vms-loadbalancer-lbrules/main.tf +++ b/examples/virtual-machines/virtual_machine/2-vms-loadbalancer-lbrules/main.tf @@ -109,11 +109,18 @@ resource "azurerm_network_interface" "nic" { name = "ipconfig${count.index}" subnet_id = "${azurerm_subnet.subnet.id}" private_ip_address_allocation = "Dynamic" - load_balancer_backend_address_pools_ids = ["${azurerm_lb_backend_address_pool.backend_pool.id}"] - load_balancer_inbound_nat_rules_ids = ["${element(azurerm_lb_nat_rule.tcp.*.id, count.index)}"] } } + +resource "azurerm_network_interface_nat_rule_association" "natrule" { + network_interface_id = "element(azurerm_network_interface.nic.*.id, count.index)" + ip_configuration_name = "ipconfig${count.index}" + nat_rule_id = "element(azurerm_lb_nat_rule.tcp.*.id, count.index)" + count = 2 +} + + resource "azurerm_virtual_machine" "vm" { name = "vm${count.index}" location = "${var.location}" From 7c0b9f02bd3a310665d3d28ee8e67ebedb94a787 Mon Sep 17 00:00:00 2001 From: Rob Selway Date: Sun, 10 May 2020 21:35:01 +0100 Subject: [PATCH 016/104] New data source azurerm_eventhub --- .../services/eventhub/eventhub_data_source.go | 80 +++++++++++++++++++ .../services/eventhub/registration.go | 1 + .../tests/eventhub_data_source_test.go | 62 ++++++++++++++ website/docs/d/eventhub.html.markdown | 51 ++++++++++++ 4 files changed, 194 insertions(+) create mode 100644 azurerm/internal/services/eventhub/eventhub_data_source.go create mode 100644 azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go create mode 100644 website/docs/d/eventhub.html.markdown diff --git a/azurerm/internal/services/eventhub/eventhub_data_source.go b/azurerm/internal/services/eventhub/eventhub_data_source.go new file mode 100644 index 0000000000000..a04cf05e84b7f --- /dev/null +++ b/azurerm/internal/services/eventhub/eventhub_data_source.go @@ -0,0 +1,80 @@ +package eventhub + +import ( + "fmt" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func dataSourceEventHub() *schema.Resource { + return &schema.Resource{ + Read: dataSourceEventHubRead, + + Timeouts: &schema.ResourceTimeout{ + Read: schema.DefaultTimeout(5 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "namespace_name": { + Type: schema.TypeString, + Required: true, + }, + + "resource_group_name": azure.SchemaResourceGroupNameForDataSource(), + + "partition_count": { + Type: schema.TypeInt, + Computed: true, + }, + + "partition_ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + } +} + +func dataSourceEventHubRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Eventhub.EventHubsClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) + namespaceName := d.Get("namespace_name").(string) + + resp, err := client.Get(ctx, resourceGroup, namespaceName, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Error: EventHub %q (Resource Group %q / Namespace Name %q) was not found", name, resourceGroup, namespaceName) + } + + return fmt.Errorf("Error making Read request on EventHub %q (Resource Group %q / Namespace Name %q): %+v", name, resourceGroup, namespaceName, err) + } + + d.SetId(*resp.ID) + + d.Set("name", name) + d.Set("namespace_name", namespaceName) + d.Set("resource_group_name", resourceGroup) + + if props := resp.Properties; props != nil { + d.Set("partition_count", props.PartitionCount) + d.Set("partition_ids", props.PartitionIds) + } + + return nil +} diff --git a/azurerm/internal/services/eventhub/registration.go b/azurerm/internal/services/eventhub/registration.go index 864c7bf8159de..8e1c7c5ec006f 100644 --- a/azurerm/internal/services/eventhub/registration.go +++ b/azurerm/internal/services/eventhub/registration.go @@ -21,6 +21,7 @@ func (r Registration) WebsiteCategories() []string { // SupportedDataSources returns the supported Data Sources supported by this Service func (r Registration) SupportedDataSources() map[string]*schema.Resource { return map[string]*schema.Resource{ + "azurerm_eventhub": dataSourceEventHub(), "azurerm_eventhub_authorization_rule": dataSourceEventHubAuthorizationRule(), "azurerm_eventhub_consumer_group": dataSourceEventHubConsumerGroup(), "azurerm_eventhub_namespace": dataSourceEventHubNamespace(), diff --git a/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go b/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go new file mode 100644 index 0000000000000..13d4659ddeb69 --- /dev/null +++ b/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go @@ -0,0 +1,62 @@ +package tests + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" +) + +func TestAccDataSourceAzureRMEventHub_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_eventhub", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceEventHub_basic(data), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(data.ResourceName, "partition_count", "2"), + resource.TestCheckResourceAttr(data.ResourceName, "partition_ids.#", "2"), + ), + }, + }, + }) +} + +func testAccDataSourceEventHub_basic(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-eventhub-%[1]d" + location = "%[2]s" +} + +resource "azurerm_eventhub_namespace" "test" { + name = "acctest-EHN-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + + sku = "Basic" +} + +resource "azurerm_eventhub" "test" { + name = "acctest-eh-%[1]d" + resource_group_name = azurerm_resource_group.test.name + namespace_name = azurerm_eventhub_namespace.test.name + partition_count = 2 + message_retention = 1 +} + +data "azurerm_eventhub" "test" { + name = azurerm_eventhub.test.name + namespace_name = azurerm_eventhub_namespace.test.name + resource_group_name = azurerm_resource_group.test.name +} +`, data.RandomInteger, data.Locations.Primary) +} diff --git a/website/docs/d/eventhub.html.markdown b/website/docs/d/eventhub.html.markdown new file mode 100644 index 0000000000000..4ca967228c5bb --- /dev/null +++ b/website/docs/d/eventhub.html.markdown @@ -0,0 +1,51 @@ +--- +subcategory: "Messaging" +layout: "azurerm" +page_title: "Azure Resource Manager: Data Source: azurerm_eventhub" +description: |- + Gets information about an existing Event Hub. +--- + +# Data Source: azurerm_eventhub + +Use this data source to access information about an existing Event Hub. + +## Example Usage + +```hcl +data "azurerm_eventhub" "example" { + name = "search-eventhub" + resource_group_name = "search-service" + namespace_name = "search-eventhubns" +} + +output "eventhub_id" { + value = data.azurerm_eventhub.example.id +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) The name of this Event Hub. + +* `resource_group_name` - (Required) The name of the Resource Group where the Event Hub exists. + +* `namespace_name` - (Required) The name of the EventHub Namespace where the Event Hub exists. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Event Hub. + +* `partition_count` - The number of partitions in the Event Hub. + +* `partition_ids` - The identifiers for partitions of this Event Hub. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `read` - (Defaults to 5 minutes) Used when retrieving the Event Hub. \ No newline at end of file From 9ca0dff0b7898bfe03c88894c6a1b9f6ed83a010 Mon Sep 17 00:00:00 2001 From: Rob Selway Date: Sun, 10 May 2020 21:47:19 +0100 Subject: [PATCH 017/104] Removed space from Event Hub in docs --- website/docs/d/eventhub.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/website/docs/d/eventhub.html.markdown b/website/docs/d/eventhub.html.markdown index 4ca967228c5bb..b6566d7011bfe 100644 --- a/website/docs/d/eventhub.html.markdown +++ b/website/docs/d/eventhub.html.markdown @@ -3,12 +3,12 @@ subcategory: "Messaging" layout: "azurerm" page_title: "Azure Resource Manager: Data Source: azurerm_eventhub" description: |- - Gets information about an existing Event Hub. + Gets information about an existing EventHub. --- # Data Source: azurerm_eventhub -Use this data source to access information about an existing Event Hub. +Use this data source to access information about an existing EventHub. ## Example Usage @@ -28,24 +28,24 @@ output "eventhub_id" { The following arguments are supported: -* `name` - (Required) The name of this Event Hub. +* `name` - (Required) The name of this EventHub. -* `resource_group_name` - (Required) The name of the Resource Group where the Event Hub exists. +* `resource_group_name` - (Required) The name of the Resource Group where the EventHub exists. -* `namespace_name` - (Required) The name of the EventHub Namespace where the Event Hub exists. +* `namespace_name` - (Required) The name of the EventHub Namespace where the EventHub exists. ## Attributes Reference In addition to the Arguments listed above - the following Attributes are exported: -* `id` - The ID of the Event Hub. +* `id` - The ID of the EventHub. -* `partition_count` - The number of partitions in the Event Hub. +* `partition_count` - The number of partitions in the EventHub. -* `partition_ids` - The identifiers for partitions of this Event Hub. +* `partition_ids` - The identifiers for the partitions of this EventHub. ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: -* `read` - (Defaults to 5 minutes) Used when retrieving the Event Hub. \ No newline at end of file +* `read` - (Defaults to 5 minutes) Used when retrieving the EventHub. \ No newline at end of file From 877890ab9ae3fe55482a58c89d831c7bb76ddf50 Mon Sep 17 00:00:00 2001 From: magodo Date: Mon, 11 May 2020 10:03:24 +0800 Subject: [PATCH 018/104] modify regexp: escape dot --- .../automation/tests/automation_account_data_source_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/internal/services/automation/tests/automation_account_data_source_test.go b/azurerm/internal/services/automation/tests/automation_account_data_source_test.go index 831b25f2a814e..fe75fb1a28034 100644 --- a/azurerm/internal/services/automation/tests/automation_account_data_source_test.go +++ b/azurerm/internal/services/automation/tests/automation_account_data_source_test.go @@ -22,7 +22,7 @@ func TestAccDataSourceAutomationAccount(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(data.ResourceName, "resource_group_name", resourceGroupName), resource.TestMatchResourceAttr(data.ResourceName, "id", - regexp.MustCompile(`^/subscriptions/[^/]+/resourceGroups/[^/]+/providers/Microsoft.Automation/automationAccounts/[^/]+$`)), + regexp.MustCompile(`^/subscriptions/[^/]+/resourceGroups/[^/]+/providers/Microsoft\.Automation/automationAccounts/[^/]+$`)), ), }, }, From 48b534b671e6e60810d01a2b6986b1483fe88aff Mon Sep 17 00:00:00 2001 From: Rob Selway Date: Mon, 11 May 2020 08:23:08 +0100 Subject: [PATCH 019/104] Fixed tflint errors --- .../eventhub/tests/eventhub_data_source_test.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go b/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go index 13d4659ddeb69..79fcd0a122319 100644 --- a/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go +++ b/azurerm/internal/services/eventhub/tests/eventhub_data_source_test.go @@ -46,17 +46,17 @@ resource "azurerm_eventhub_namespace" "test" { } resource "azurerm_eventhub" "test" { - name = "acctest-eh-%[1]d" - resource_group_name = azurerm_resource_group.test.name - namespace_name = azurerm_eventhub_namespace.test.name - partition_count = 2 - message_retention = 1 + name = "acctest-eh-%[1]d" + resource_group_name = azurerm_resource_group.test.name + namespace_name = azurerm_eventhub_namespace.test.name + partition_count = 2 + message_retention = 1 } data "azurerm_eventhub" "test" { - name = azurerm_eventhub.test.name - namespace_name = azurerm_eventhub_namespace.test.name - resource_group_name = azurerm_resource_group.test.name + name = azurerm_eventhub.test.name + namespace_name = azurerm_eventhub_namespace.test.name + resource_group_name = azurerm_resource_group.test.name } `, data.RandomInteger, data.Locations.Primary) } From b20c35accb61775e6114a43d0038949ff6f5fd37 Mon Sep 17 00:00:00 2001 From: Rob Selway Date: Mon, 11 May 2020 08:27:25 +0100 Subject: [PATCH 020/104] Added azurerm_eventhub data source to website navigation --- website/azurerm.erb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/website/azurerm.erb b/website/azurerm.erb index 28474f9ca9d12..685e435743743 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -210,6 +210,10 @@ azurerm_disk_encryption_set +
  • + azurerm_eventhub +
  • +
  • azurerm_eventhub_authorization_rule
  • From f58e815070a024dc1f2d0aca845a7be7567b4bbe Mon Sep 17 00:00:00 2001 From: Rob Selway Date: Mon, 11 May 2020 08:29:02 +0100 Subject: [PATCH 021/104] tf format in website docs --- website/docs/d/eventhub.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/website/docs/d/eventhub.html.markdown b/website/docs/d/eventhub.html.markdown index b6566d7011bfe..a905a108e8856 100644 --- a/website/docs/d/eventhub.html.markdown +++ b/website/docs/d/eventhub.html.markdown @@ -14,9 +14,9 @@ Use this data source to access information about an existing EventHub. ```hcl data "azurerm_eventhub" "example" { - name = "search-eventhub" + name = "search-eventhub" resource_group_name = "search-service" - namespace_name = "search-eventhubns" + namespace_name = "search-eventhubns" } output "eventhub_id" { @@ -48,4 +48,4 @@ In addition to the Arguments listed above - the following Attributes are exporte The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: -* `read` - (Defaults to 5 minutes) Used when retrieving the EventHub. \ No newline at end of file +* `read` - (Defaults to 5 minutes) Used when retrieving the EventHub. From 078aea92d33d6ff429db6ce5b44aeabdbdeb29c9 Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Mon, 11 May 2020 12:34:29 +0200 Subject: [PATCH 022/104] updating to include #6848 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3f6a3ea0159f..478adaaf760e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ IMPROVEMENTS: * `azurerm_mssql_server` - Add support for `azuread_administrator` [GH-6822] +BUG FIXES: + +* Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] + ## 2.9.0 (May 07, 2020) FEATURES: From bed3d85eab012baddb1a8f9cbda7002f863eab43 Mon Sep 17 00:00:00 2001 From: Rob Selway Date: Mon, 11 May 2020 13:16:01 +0100 Subject: [PATCH 023/104] Changed partition_ids from TypeSet to TypeList --- azurerm/internal/services/eventhub/eventhub_data_source.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/azurerm/internal/services/eventhub/eventhub_data_source.go b/azurerm/internal/services/eventhub/eventhub_data_source.go index a04cf05e84b7f..69a27e6f8cab2 100644 --- a/azurerm/internal/services/eventhub/eventhub_data_source.go +++ b/azurerm/internal/services/eventhub/eventhub_data_source.go @@ -38,10 +38,9 @@ func dataSourceEventHub() *schema.Resource { }, "partition_ids": { - Type: schema.TypeSet, + Type: schema.TypeList, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, }, } From d3bf35655ffa3211528ae5cb4dcbd4c154ba4ff4 Mon Sep 17 00:00:00 2001 From: Arcturus Date: Mon, 11 May 2020 22:43:11 +0800 Subject: [PATCH 024/104] `data.azurerm_virtual_machine` - export `identity` attribute (#6826) --- .../tests/virtual_machine_data_source_test.go | 120 ++++++------------ .../services/compute/virtual_machine.go | 11 ++ .../compute/virtual_machine_data_source.go | 41 +++++- website/docs/d/virtual_machine.html.markdown | 19 +++ .../r/linux_virtual_machine.html.markdown | 6 + .../r/windows_virtual_machine.html.markdown | 6 + 6 files changed, 120 insertions(+), 83 deletions(-) diff --git a/azurerm/internal/services/compute/tests/virtual_machine_data_source_test.go b/azurerm/internal/services/compute/tests/virtual_machine_data_source_test.go index 391f04c0ba218..cf71e37f166f5 100644 --- a/azurerm/internal/services/compute/tests/virtual_machine_data_source_test.go +++ b/azurerm/internal/services/compute/tests/virtual_machine_data_source_test.go @@ -8,109 +8,67 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" ) -func TestAccDataSourceVirtualMachine_basic(t *testing.T) { +func TestAccDataSourceAzureRMVirtualMachine_basicLinux(t *testing.T) { data := acceptance.BuildTestData(t, "data.azurerm_virtual_machine", "test") - name := fmt.Sprintf("acctvm-%d", data.RandomInteger) - resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, Steps: []resource.TestStep{ { - Config: testAccDataSourceVirtualMachine_basic(data), - Check: resource.TestCheckResourceAttr(data.ResourceName, "name", name), + Config: testAccDataSourceAzureRMVirtualMachine_basicLinux(data), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(data.ResourceName, "identity.#", "1"), + resource.TestCheckResourceAttr(data.ResourceName, "identity.0.type", "SystemAssigned"), + resource.TestCheckResourceAttrSet(data.ResourceName, "identity.0.principal_id"), + resource.TestCheckResourceAttrSet(data.ResourceName, "identity.0.tenant_id"), + ), }, }, }) } -func testAccDataSourceVirtualMachine_basic(data acceptance.TestData) string { - return fmt.Sprintf(` -provider "azurerm" { - features {} -} - -resource "azurerm_resource_group" "test" { - name = "acctestRG-%[1]d" - location = "%[2]s" -} +func TestAccDataSourceAzureRMVirtualMachine_basicWindows(t *testing.T) { + data := acceptance.BuildTestData(t, "data.azurerm_virtual_machine", "test") -resource "azurerm_virtual_network" "test" { - name = "acctvn-%[1]d" - address_space = ["10.0.0.0/16"] - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAzureRMVirtualMachine_basicWindows(data), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(data.ResourceName, "identity.#", "1"), + resource.TestCheckResourceAttr(data.ResourceName, "identity.0.type", "SystemAssigned"), + resource.TestCheckResourceAttrSet(data.ResourceName, "identity.0.principal_id"), + resource.TestCheckResourceAttrSet(data.ResourceName, "identity.0.tenant_id"), + ), + }, + }, + }) } -resource "azurerm_subnet" "test" { - name = "acctsub-%[1]d" - resource_group_name = azurerm_resource_group.test.name - virtual_network_name = azurerm_virtual_network.test.name - address_prefix = "10.0.2.0/24" -} +func testAccDataSourceAzureRMVirtualMachine_basicLinux(data acceptance.TestData) string { + template := testLinuxVirtualMachine_identitySystemAssigned(data) + return fmt.Sprintf(` +%s -resource "azurerm_network_interface" "test" { - name = "acctni-%[1]d" - location = azurerm_resource_group.test.location +data "azurerm_virtual_machine" "test" { + name = azurerm_linux_virtual_machine.test.name resource_group_name = azurerm_resource_group.test.name - - ip_configuration { - name = "testconfiguration1" - subnet_id = azurerm_subnet.test.id - private_ip_address_allocation = "dynamic" - } } - -resource "azurerm_storage_account" "test" { - name = "accsa%[1]d" - resource_group_name = azurerm_resource_group.test.name - location = azurerm_resource_group.test.location - account_tier = "Standard" - account_replication_type = "LRS" -} - -resource "azurerm_storage_container" "test" { - name = "vhds" - storage_account_name = azurerm_storage_account.test.name - container_access_type = "private" +`, template) } -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%[1]d" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - network_interface_ids = [azurerm_network_interface.test.id] - vm_size = "Standard_D1_v2" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "16.04-LTS" - version = "latest" - } - - storage_os_disk { - name = "myosdisk1" - vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" - caching = "ReadWrite" - create_option = "FromImage" - } - - os_profile { - computer_name = "linuxhost01" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } -} +func testAccDataSourceAzureRMVirtualMachine_basicWindows(data acceptance.TestData) string { + template := testWindowsVirtualMachine_identitySystemAssigned(data) + return fmt.Sprintf(` +%s data "azurerm_virtual_machine" "test" { + name = azurerm_windows_virtual_machine.test.name resource_group_name = azurerm_resource_group.test.name - name = azurerm_virtual_machine.test.name } -`, data.RandomInteger, data.Locations.Primary) +`, template) } diff --git a/azurerm/internal/services/compute/virtual_machine.go b/azurerm/internal/services/compute/virtual_machine.go index 5e545d1c4a610..5f323b400c60f 100644 --- a/azurerm/internal/services/compute/virtual_machine.go +++ b/azurerm/internal/services/compute/virtual_machine.go @@ -96,6 +96,11 @@ func virtualMachineIdentitySchema() *schema.Schema { Type: schema.TypeString, Computed: true, }, + + "tenant_id": { + Type: schema.TypeString, + Computed: true, + }, }, }, } @@ -149,11 +154,17 @@ func flattenVirtualMachineIdentity(input *compute.VirtualMachineIdentity) []inte principalId = *input.PrincipalID } + tenantId := "" + if input.TenantID != nil { + tenantId = *input.TenantID + } + return []interface{}{ map[string]interface{}{ "type": string(input.Type), "identity_ids": identityIds, "principal_id": principalId, + "tenant_id": tenantId, }, } } diff --git a/azurerm/internal/services/compute/virtual_machine_data_source.go b/azurerm/internal/services/compute/virtual_machine_data_source.go index 0cfb385fd6171..a1e33f1af70fa 100644 --- a/azurerm/internal/services/compute/virtual_machine_data_source.go +++ b/azurerm/internal/services/compute/virtual_machine_data_source.go @@ -21,13 +21,46 @@ func dataSourceArmVirtualMachine() *schema.Resource { }, Schema: map[string]*schema.Schema{ - "resource_group_name": azure.SchemaResourceGroupNameForDataSource(), - "name": { Type: schema.TypeString, Required: true, ValidateFunc: validation.NoZeroValues, }, + + "resource_group_name": azure.SchemaResourceGroupNameForDataSource(), + + "location": azure.SchemaLocationForDataSource(), + + "identity": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Computed: true, + }, + + "identity_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "principal_id": { + Type: schema.TypeString, + Computed: true, + }, + + "tenant_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, }, } } @@ -51,5 +84,9 @@ func dataSourceArmVirtualMachineRead(d *schema.ResourceData, meta interface{}) e d.SetId(*resp.ID) + if err := d.Set("identity", flattenVirtualMachineIdentity(resp.Identity)); err != nil { + return fmt.Errorf("setting `identity`: %+v", err) + } + return nil } diff --git a/website/docs/d/virtual_machine.html.markdown b/website/docs/d/virtual_machine.html.markdown index b8d3b60660df1..ed009706d4105 100644 --- a/website/docs/d/virtual_machine.html.markdown +++ b/website/docs/d/virtual_machine.html.markdown @@ -13,6 +13,10 @@ Use this data source to access information about an existing Virtual Machine. ## Example Usage ```hcl +provider "azurerm" { + features {} +} + data "azurerm_virtual_machine" "example" { name = "production" resource_group_name = "networking" @@ -26,12 +30,27 @@ output "virtual_machine_id" { ## Argument Reference * `name` - Specifies the name of the Virtual Machine. + * `resource_group_name` - Specifies the name of the resource group the Virtual Machine is located in. ## Attributes Reference * `id` - The ID of the Virtual Machine. +* `identity` - A `identity` block as defined below. + +--- + +An `identity` block exports the following: + +* `identity_ids` - The list of User Managed Identity ID's which are assigned to the Virtual Machine. + +* `principal_id` - The ID of the System Managed Service Principal assigned to the Virtual Machine. + +* `tenant_id` - The ID of the Tenant of the System Managed Service Principal assigned to the Virtual Machine. + +* `type` - The identity type of the Managed Identity assigned to the Virtual Machine. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: diff --git a/website/docs/r/linux_virtual_machine.html.markdown b/website/docs/r/linux_virtual_machine.html.markdown index bd7fa60748322..6f090d0df2b5b 100644 --- a/website/docs/r/linux_virtual_machine.html.markdown +++ b/website/docs/r/linux_virtual_machine.html.markdown @@ -27,6 +27,10 @@ Manages a Linux Virtual Machine. This example provisions a basic Linux Virtual Machine on an internal network. Additional examples of how to use the `azurerm_linux_virtual_machine` resource can be found [in the ./examples/virtual-machine/linux` directory within the Github Repository](https://github.com/terraform-providers/terraform-provider-azurerm/tree/master/examples/virtual-machines/linux). ```hcl +provider "azurerm" { + features {} +} + resource "azurerm_resource_group" "example" { name = "example-resources" location = "West Europe" @@ -282,6 +286,8 @@ An `identity` block exports the following: * `principal_id` - The ID of the System Managed Service Principal. +* `tenant_id` - The ID of the Tenant the System Managed Service Principal is assigned in. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: diff --git a/website/docs/r/windows_virtual_machine.html.markdown b/website/docs/r/windows_virtual_machine.html.markdown index c061e023baec6..4628fce707635 100644 --- a/website/docs/r/windows_virtual_machine.html.markdown +++ b/website/docs/r/windows_virtual_machine.html.markdown @@ -27,6 +27,10 @@ Manages a Windows Virtual Machine. This example provisions a basic Windows Virtual Machine on an internal network. Additional examples of how to use the `azurerm_windows_virtual_machine` resource can be found [in the ./examples/virtual-machine/windows` directory within the Github Repository](https://github.com/terraform-providers/terraform-provider-azurerm/tree/master/examples/virtual-machine/windows). ```hcl +provider "azurerm" { + features {} +} + resource "azurerm_resource_group" "example" { name = "example-resources" location = "West Europe" @@ -283,6 +287,8 @@ An `identity` block exports the following: * `principal_id` - The ID of the System Managed Service Principal. +* `tenant_id` - The ID of the Tenant the System Managed Service Principal is assigned in. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: From 6c4ce4382add3b08e48c2b37d385905cde9f9ff9 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Mon, 11 May 2020 07:43:58 -0700 Subject: [PATCH 025/104] Update changelog for #6826 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 478adaaf760e7..ee625ef21c465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ IMPROVEMENTS: * `azurerm_mssql_server` - Add support for `azuread_administrator` [GH-6822] +* `data.azurerm_virtual_machine` - export `identity` attribute [GH-6826] BUG FIXES: From 98087b3141db66d83455641b03d9022d16894df9 Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Mon, 11 May 2020 18:01:10 +0200 Subject: [PATCH 026/104] updating to include #6841 --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee625ef21c465..8181fec658711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,13 @@ ## 2.10.0 (Unreleased) +FEATURES: + +* **New Data Source:** `azurerm_eventhub` [GH-6841] + IMPROVEMENTS: +* Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] * `azurerm_mssql_server` - Add support for `azuread_administrator` [GH-6822] -* `data.azurerm_virtual_machine` - export `identity` attribute [GH-6826] BUG FIXES: From d92443c61f034c4ea331124d7df649d39dbdd72a Mon Sep 17 00:00:00 2001 From: Neil Ye Date: Tue, 12 May 2020 00:24:13 +0800 Subject: [PATCH 027/104] Updates doc for aks node pool (#6825) --- website/docs/r/kubernetes_cluster_node_pool.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/website/docs/r/kubernetes_cluster_node_pool.html.markdown b/website/docs/r/kubernetes_cluster_node_pool.html.markdown index e5fbf4dc79cc8..a88df2846cabd 100644 --- a/website/docs/r/kubernetes_cluster_node_pool.html.markdown +++ b/website/docs/r/kubernetes_cluster_node_pool.html.markdown @@ -56,10 +56,12 @@ The following arguments are supported: * `name` - (Required) The name of the Node Pool which should be created within the Kubernetes Cluster. Changing this forces a new resource to be created. --> **NOTE:** A Windows Node Pool cannot have a `name` longer than 6 characters. +~> **NOTE:** A Windows Node Pool cannot have a `name` longer than 6 characters. * `kubernetes_cluster_id` - (Required) The ID of the Kubernetes Cluster where this Node Pool should exist. Changing this forces a new resource to be created. +~> **NOTE:** The type of Default Node Pool for the Kubernetes Cluster must be `VirtualMachineScaleSets` to attach multiple node pools. + * `vm_size` - (Required) The SKU which should be used for the Virtual Machines used in this Node Pool. Changing this forces a new resource to be created. --- @@ -68,7 +70,7 @@ The following arguments are supported: * `enable_auto_scaling` - (Optional) Whether to enable [auto-scaler](https://docs.microsoft.com/en-us/azure/aks/cluster-autoscaler). Defaults to `false`. --> **NOTE:** Additional fields must be configured depending on the value of this field - see below. +~> **NOTE:** Additional fields must be configured depending on the value of this field - see below. * `enable_node_public_ip` - (Optional) Should each node have a Public IP Address? Defaults to `false`. From 0a635d7f03fdd5f6d4f9ba0274fa9c3150cc001b Mon Sep 17 00:00:00 2001 From: Jochen Rauschenbusch Date: Mon, 11 May 2020 21:55:46 +0200 Subject: [PATCH 028/104] Upgrade EventGrid SDK to 2020-04-01-preview (#6837) Upgrade EventGrid SDK to 2020-04-01-preview from 2018-09-15-preview to address @katbyte comments in PR #5948. --- .../services/eventgrid/client/client.go | 2 +- .../eventgrid/eventgrid_domain_resource.go | 48 +- .../eventgrid_event_subscription_resource.go | 66 +- .../eventgrid/eventgrid_topic_resource.go | 38 +- .../eventgrid/parse/eventgrid_domain.go | 33 + .../parse/eventgrid_event_subscription.go | 39 + .../eventgrid/parse/eventgrid_topic.go | 33 + .../tests/eventgrid_domain_resource_test.go | 41 + ...ntgrid_event_subscription_resource_test.go | 4 +- azurerm/utils/array.go | 11 + go.sum | 1 + .../eventgrid/domaintopics.go | 196 - .../2018-09-15-preview/eventgrid/models.go | 3712 -------- .../eventgrid/client.go | 2 +- .../eventgrid/domains.go | 181 +- .../eventgrid/domaintopics.go | 403 + .../eventgrid/eventchannels.go | 406 + .../eventgrid/eventsubscriptions.go | 750 +- .../eventgrid/extensiontopics.go | 120 + .../2020-04-01-preview/eventgrid/models.go | 8181 +++++++++++++++++ .../eventgrid/operations.go | 4 +- .../eventgrid/partnernamespaces.go | 764 ++ .../eventgrid/partnerregistrations.go | 669 ++ .../partnertopiceventsubscriptions.go | 572 ++ .../eventgrid/partnertopics.go | 674 ++ .../eventgrid/privateendpointconnections.go | 415 + .../eventgrid/privatelinkresources.go | 253 + .../systemtopiceventsubscriptions.go | 572 ++ .../eventgrid/systemtopics.go | 601 ++ .../eventgrid/topics.go | 189 +- .../eventgrid/topictypes.go | 16 +- .../eventgrid/version.go | 2 +- vendor/modules.txt | 2 +- website/docs/r/eventgrid_domain.html.markdown | 2 +- ...eventgrid_event_subscription.html.markdown | 10 +- 35 files changed, 14805 insertions(+), 4207 deletions(-) create mode 100644 azurerm/internal/services/eventgrid/parse/eventgrid_domain.go create mode 100644 azurerm/internal/services/eventgrid/parse/eventgrid_event_subscription.go create mode 100644 azurerm/internal/services/eventgrid/parse/eventgrid_topic.go create mode 100644 azurerm/utils/array.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domaintopics.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/models.go rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/client.go (98%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/domains.go (78%) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domaintopics.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventchannels.go rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/eventsubscriptions.go (59%) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/extensiontopics.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/models.go rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/operations.go (98%) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnernamespaces.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnerregistrations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopiceventsubscriptions.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopics.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/privateendpointconnections.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/privatelinkresources.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopiceventsubscriptions.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopics.go rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/topics.go (79%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/topictypes.go (96%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/{2018-09-15-preview => 2020-04-01-preview}/eventgrid/version.go (93%) diff --git a/azurerm/internal/services/eventgrid/client/client.go b/azurerm/internal/services/eventgrid/client/client.go index e32a89cac3b4f..2e74b0c0f3c00 100644 --- a/azurerm/internal/services/eventgrid/client/client.go +++ b/azurerm/internal/services/eventgrid/client/client.go @@ -1,7 +1,7 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid" + "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/common" ) diff --git a/azurerm/internal/services/eventgrid/eventgrid_domain_resource.go b/azurerm/internal/services/eventgrid/eventgrid_domain_resource.go index 6330b171cf834..dbf0683d5def9 100644 --- a/azurerm/internal/services/eventgrid/eventgrid_domain_resource.go +++ b/azurerm/internal/services/eventgrid/eventgrid_domain_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid" + "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid" "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" @@ -13,7 +13,9 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid/parse" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -24,9 +26,6 @@ func resourceArmEventGridDomain() *schema.Resource { Read: resourceArmEventGridDomainRead, Update: resourceArmEventGridDomainCreateUpdate, Delete: resourceArmEventGridDomainDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(30 * time.Minute), @@ -35,6 +34,11 @@ func resourceArmEventGridDomain() *schema.Resource { Delete: schema.DefaultTimeout(30 * time.Minute), }, + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.EventGridDomainID(id) + return err + }), + Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -54,7 +58,7 @@ func resourceArmEventGridDomain() *schema.Resource { Default: string(eventgrid.InputSchemaEventGridSchema), ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(eventgrid.InputSchemaCloudEventV01Schema), + string(eventgrid.InputSchemaCloudEventSchemaV10), string(eventgrid.InputSchemaCustomEventSchema), string(eventgrid.InputSchemaEventGridSchema), }, false), @@ -211,26 +215,24 @@ func resourceArmEventGridDomainRead(d *schema.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.EventGridDomainID(d.Id()) if err != nil { return err } - resourceGroup := id.ResourceGroup - name := id.Path["domains"] - resp, err := client.Get(ctx, resourceGroup, name) + resp, err := client.Get(ctx, id.ResourceGroup, id.Name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[WARN] EventGrid Domain %q was not found (Resource Group %q)", name, resourceGroup) + log.Printf("[WARN] EventGrid Domain %q was not found (Resource Group %q)", id.Name, id.ResourceGroup) d.SetId("") return nil } - return fmt.Errorf("Error making Read request on EventGrid Domain %q: %+v", name, err) + return fmt.Errorf("Error making Read request on EventGrid Domain %q: %+v", id.Name, err) } d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) + d.Set("resource_group_name", id.ResourceGroup) if location := resp.Location; location != nil { d.Set("location", azure.NormalizeLocation(*location)) } @@ -242,24 +244,24 @@ func resourceArmEventGridDomainRead(d *schema.ResourceData, meta interface{}) er inputMappingFields, err := flattenAzureRmEventgridDomainInputMapping(props.InputSchemaMapping) if err != nil { - return fmt.Errorf("Unable to flatten `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err) + return fmt.Errorf("Unable to flatten `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) } if err := d.Set("input_mapping_fields", inputMappingFields); err != nil { - return fmt.Errorf("Error setting `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err) + return fmt.Errorf("Error setting `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) } inputMappingDefaultValues, err := flattenAzureRmEventgridDomainInputMappingDefaultValues(props.InputSchemaMapping) if err != nil { - return fmt.Errorf("Unable to flatten `input_schema_mapping_default_values` for EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err) + return fmt.Errorf("Unable to flatten `input_schema_mapping_default_values` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) } if err := d.Set("input_mapping_default_values", inputMappingDefaultValues); err != nil { - return fmt.Errorf("Error setting `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", name, resourceGroup, err) + return fmt.Errorf("Error setting `input_schema_mapping_fields` for EventGrid Domain %q (Resource Group %q): %s", id.Name, id.ResourceGroup, err) } } - keys, err := client.ListSharedAccessKeys(ctx, resourceGroup, name) + keys, err := client.ListSharedAccessKeys(ctx, id.ResourceGroup, id.Name) if err != nil { - return fmt.Errorf("Error retrieving Shared Access Keys for EventGrid Domain %q: %+v", name, err) + return fmt.Errorf("Error retrieving Shared Access Keys for EventGrid Domain %q: %+v", id.Name, err) } d.Set("primary_access_key", keys.Key1) d.Set("secondary_access_key", keys.Key2) @@ -272,26 +274,24 @@ func resourceArmEventGridDomainDelete(d *schema.ResourceData, meta interface{}) ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.EventGridDomainID(d.Id()) if err != nil { return err } - resGroup := id.ResourceGroup - name := id.Path["domains"] - future, err := client.Delete(ctx, resGroup, name) + future, err := client.Delete(ctx, id.ResourceGroup, id.Name) if err != nil { if response.WasNotFound(future.Response()) { return nil } - return fmt.Errorf("Error deleting Event Grid Domain %q: %+v", name, err) + return fmt.Errorf("Error deleting Event Grid Domain %q: %+v", id.Name, err) } if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { if response.WasNotFound(future.Response()) { return nil } - return fmt.Errorf("Error deleting Event Grid Domain %q: %+v", name, err) + return fmt.Errorf("Error deleting Event Grid Domain %q: %+v", id.Name, err) } return nil diff --git a/azurerm/internal/services/eventgrid/eventgrid_event_subscription_resource.go b/azurerm/internal/services/eventgrid/eventgrid_event_subscription_resource.go index e78ec1676ce0c..a19f6c9f7ded1 100644 --- a/azurerm/internal/services/eventgrid/eventgrid_event_subscription_resource.go +++ b/azurerm/internal/services/eventgrid/eventgrid_event_subscription_resource.go @@ -3,10 +3,9 @@ package eventgrid import ( "fmt" "log" - "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid" + "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid" "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" @@ -14,19 +13,22 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid/parse" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) +func getEnpointTypes() []string { + return []string{"webhook_endpoint", "storage_queue_endpoint", "eventhub_endpoint", "hybrid_connection_endpoint"} +} + func resourceArmEventGridEventSubscription() *schema.Resource { return &schema.Resource{ Create: resourceArmEventGridEventSubscriptionCreateUpdate, Read: resourceArmEventGridEventSubscriptionRead, Update: resourceArmEventGridEventSubscriptionCreateUpdate, Delete: resourceArmEventGridEventSubscriptionDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(30 * time.Minute), @@ -35,6 +37,11 @@ func resourceArmEventGridEventSubscription() *schema.Resource { Delete: schema.DefaultTimeout(30 * time.Minute), }, + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.EventGridEventSubscriptionID(id) + return err + }), + Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -56,9 +63,9 @@ func resourceArmEventGridEventSubscription() *schema.Resource { ForceNew: true, Default: string(eventgrid.EventGridSchema), ValidateFunc: validation.StringInSlice([]string{ - string(eventgrid.CloudEventV01Schema), - string(eventgrid.CustomInputSchema), string(eventgrid.EventGridSchema), + string(eventgrid.CloudEventSchemaV10), + string(eventgrid.CustomInputSchema), }, false), }, @@ -72,7 +79,7 @@ func resourceArmEventGridEventSubscription() *schema.Resource { Type: schema.TypeList, MaxItems: 1, Optional: true, - ConflictsWith: []string{"eventhub_endpoint", "hybrid_connection_endpoint", "webhook_endpoint"}, + ConflictsWith: utils.RemoveFromStringArray(getEnpointTypes(), "storage_queue_endpoint"), Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "storage_account_id": { @@ -93,7 +100,7 @@ func resourceArmEventGridEventSubscription() *schema.Resource { Type: schema.TypeList, MaxItems: 1, Optional: true, - ConflictsWith: []string{"storage_queue_endpoint", "hybrid_connection_endpoint", "webhook_endpoint"}, + ConflictsWith: utils.RemoveFromStringArray(getEnpointTypes(), "eventhub_endpoint"), Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "eventhub_id": { @@ -109,7 +116,7 @@ func resourceArmEventGridEventSubscription() *schema.Resource { Type: schema.TypeList, MaxItems: 1, Optional: true, - ConflictsWith: []string{"storage_queue_endpoint", "eventhub_endpoint", "webhook_endpoint"}, + ConflictsWith: utils.RemoveFromStringArray(getEnpointTypes(), "hybrid_connection_endpoint"), Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "hybrid_connection_id": { @@ -125,7 +132,7 @@ func resourceArmEventGridEventSubscription() *schema.Resource { Type: schema.TypeList, MaxItems: 1, Optional: true, - ConflictsWith: []string{"storage_queue_endpoint", "eventhub_endpoint", "hybrid_connection_endpoint"}, + ConflictsWith: utils.RemoveFromStringArray(getEnpointTypes(), "webhook_endpoint"), Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "url": { @@ -142,7 +149,8 @@ func resourceArmEventGridEventSubscription() *schema.Resource { Optional: true, Computed: true, Elem: &schema.Schema{ - Type: schema.TypeString, + Type: schema.TypeString, + ValidateFunc: validation.StringIsNotEmpty, }, }, @@ -243,22 +251,20 @@ func resourceArmEventGridEventSubscriptionCreateUpdate(d *schema.ResourceData, m destination := expandEventGridEventSubscriptionDestination(d) if destination == nil { - return fmt.Errorf("One of `webhook_endpoint`, eventhub_endpoint` `hybrid_connection_endpoint` or `storage_queue_endpoint` must be specificed to create an EventGrid Event Subscription") + return fmt.Errorf("One of the following endpoint types must be specificed to create an EventGrid Event Subscription: %q", getEnpointTypes()) } + filter := expandEventGridEventSubscriptionFilter(d) + eventSubscriptionProperties := eventgrid.EventSubscriptionProperties{ Destination: destination, - Filter: expandEventGridEventSubscriptionFilter(d), + Filter: filter, DeadLetterDestination: expandEventGridEventSubscriptionStorageBlobDeadLetterDestination(d), RetryPolicy: expandEventGridEventSubscriptionRetryPolicy(d), Labels: utils.ExpandStringSlice(d.Get("labels").([]interface{})), EventDeliverySchema: eventgrid.EventDeliverySchema(d.Get("event_delivery_schema").(string)), } - if v, ok := d.GetOk("topic_name"); ok { - eventSubscriptionProperties.Topic = utils.String(v.(string)) - } - eventSubscription := eventgrid.EventSubscription{ EventSubscriptionProperties: &eventSubscriptionProperties, } @@ -292,7 +298,7 @@ func resourceArmEventGridEventSubscriptionRead(d *schema.ResourceData, meta inte ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parseAzureEventGridEventSubscriptionID(d.Id()) + id, err := parse.EventGridEventSubscriptionID(d.Id()) if err != nil { return err } @@ -377,7 +383,7 @@ func resourceArmEventGridEventSubscriptionDelete(d *schema.ResourceData, meta in ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parseAzureEventGridEventSubscriptionID(d.Id()) + id, err := parse.EventGridEventSubscriptionID(d.Id()) if err != nil { return err } @@ -400,26 +406,6 @@ func resourceArmEventGridEventSubscriptionDelete(d *schema.ResourceData, meta in return nil } -type AzureEventGridEventSubscriptionID struct { - Scope string - Name string -} - -func parseAzureEventGridEventSubscriptionID(id string) (*AzureEventGridEventSubscriptionID, error) { - segments := strings.Split(id, "/providers/Microsoft.EventGrid/eventSubscriptions/") - if len(segments) != 2 { - return nil, fmt.Errorf("Expected ID to be in the format `{scope}/providers/Microsoft.EventGrid/eventSubscriptions/{name} - got %d segments", len(segments)) - } - - scope := segments[0] - name := segments[1] - eventSubscriptionID := AzureEventGridEventSubscriptionID{ - Scope: scope, - Name: name, - } - return &eventSubscriptionID, nil -} - func expandEventGridEventSubscriptionDestination(d *schema.ResourceData) eventgrid.BasicEventSubscriptionDestination { if _, ok := d.GetOk("storage_queue_endpoint"); ok { return expandEventGridEventSubscriptionStorageQueueEndpoint(d) diff --git a/azurerm/internal/services/eventgrid/eventgrid_topic_resource.go b/azurerm/internal/services/eventgrid/eventgrid_topic_resource.go index 1272e83144839..be5f023e351f2 100644 --- a/azurerm/internal/services/eventgrid/eventgrid_topic_resource.go +++ b/azurerm/internal/services/eventgrid/eventgrid_topic_resource.go @@ -5,7 +5,7 @@ import ( "log" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid" + "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid" "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" @@ -13,7 +13,9 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid/parse" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -24,9 +26,6 @@ func resourceArmEventGridTopic() *schema.Resource { Read: resourceArmEventGridTopicRead, Update: resourceArmEventGridTopicCreateUpdate, Delete: resourceArmEventGridTopicDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(30 * time.Minute), @@ -35,6 +34,11 @@ func resourceArmEventGridTopic() *schema.Resource { Delete: schema.DefaultTimeout(30 * time.Minute), }, + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.EventGridTopicID(id) + return err + }), + Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -128,31 +132,29 @@ func resourceArmEventGridTopicRead(d *schema.ResourceData, meta interface{}) err ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.EventGridTopicID(d.Id()) if err != nil { return err } - resourceGroup := id.ResourceGroup - name := id.Path["topics"] - resp, err := client.Get(ctx, resourceGroup, name) + resp, err := client.Get(ctx, id.ResourceGroup, id.Name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[WARN] EventGrid Topic '%s' was not found (resource group '%s')", name, resourceGroup) + log.Printf("[WARN] EventGrid Topic '%s' was not found (resource group '%s')", id.Name, id.ResourceGroup) d.SetId("") return nil } - return fmt.Errorf("Error making Read request on EventGrid Topic '%s': %+v", name, err) + return fmt.Errorf("Error making Read request on EventGrid Topic '%s': %+v", id.Name, err) } - keys, err := client.ListSharedAccessKeys(ctx, resourceGroup, name) + keys, err := client.ListSharedAccessKeys(ctx, id.ResourceGroup, id.Name) if err != nil { - return fmt.Errorf("Error retrieving Shared Access Keys for EventGrid Topic '%s': %+v", name, err) + return fmt.Errorf("Error retrieving Shared Access Keys for EventGrid Topic '%s': %+v", id.Name, err) } d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) + d.Set("resource_group_name", id.ResourceGroup) if location := resp.Location; location != nil { d.Set("location", azure.NormalizeLocation(*location)) } @@ -172,26 +174,24 @@ func resourceArmEventGridTopicDelete(d *schema.ResourceData, meta interface{}) e ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.EventGridTopicID(d.Id()) if err != nil { return err } - resGroup := id.ResourceGroup - name := id.Path["topics"] - future, err := client.Delete(ctx, resGroup, name) + future, err := client.Delete(ctx, id.ResourceGroup, id.Name) if err != nil { if response.WasNotFound(future.Response()) { return nil } - return fmt.Errorf("Error deleting Event Grid Topic %q: %+v", name, err) + return fmt.Errorf("Error deleting EventGrid Topic %q: %+v", id.Name, err) } if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { if response.WasNotFound(future.Response()) { return nil } - return fmt.Errorf("Error deleting Event Grid Topic %q: %+v", name, err) + return fmt.Errorf("Error deleting EventGrid Topic %q: %+v", id.Name, err) } return nil diff --git a/azurerm/internal/services/eventgrid/parse/eventgrid_domain.go b/azurerm/internal/services/eventgrid/parse/eventgrid_domain.go new file mode 100644 index 0000000000000..f6db8c651fb8a --- /dev/null +++ b/azurerm/internal/services/eventgrid/parse/eventgrid_domain.go @@ -0,0 +1,33 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type EventGridDomainId struct { + ResourceGroup string + Name string +} + +func EventGridDomainID(input string) (*EventGridDomainId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse EventGrid Domain ID %q: %+v", input, err) + } + + domain := EventGridDomainId{ + ResourceGroup: id.ResourceGroup, + } + + if domain.Name, err = id.PopSegment("domains"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &domain, nil +} diff --git a/azurerm/internal/services/eventgrid/parse/eventgrid_event_subscription.go b/azurerm/internal/services/eventgrid/parse/eventgrid_event_subscription.go new file mode 100644 index 0000000000000..a36965dafa3b3 --- /dev/null +++ b/azurerm/internal/services/eventgrid/parse/eventgrid_event_subscription.go @@ -0,0 +1,39 @@ +package parse + +import ( + "fmt" + "strings" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type EventGridEventSubscriptionId struct { + Scope string + Name string +} + +func EventGridEventSubscriptionID(input string) (*EventGridEventSubscriptionId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse EventGrid Event Subscription ID %q: %+v", input, err) + } + + segments := strings.Split(input, "/providers/Microsoft.EventGrid/eventSubscriptions/") + if len(segments) != 2 { + return nil, fmt.Errorf("Expected ID to be in the format `{scope}/providers/Microsoft.EventGrid/eventSubscriptions/{name} - got %d segments", len(segments)) + } + + eventSubscription := EventGridEventSubscriptionId{ + Scope: segments[0], + } + + if eventSubscription.Name, err = id.PopSegment("eventSubscriptions"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &eventSubscription, nil +} diff --git a/azurerm/internal/services/eventgrid/parse/eventgrid_topic.go b/azurerm/internal/services/eventgrid/parse/eventgrid_topic.go new file mode 100644 index 0000000000000..ad95e03128465 --- /dev/null +++ b/azurerm/internal/services/eventgrid/parse/eventgrid_topic.go @@ -0,0 +1,33 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type EventGridTopicId struct { + ResourceGroup string + Name string +} + +func EventGridTopicID(input string) (*EventGridTopicId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse EventGrid Topic ID %q: %+v", input, err) + } + + topic := EventGridTopicId{ + ResourceGroup: id.ResourceGroup, + } + + if topic.Name, err = id.PopSegment("topics"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &topic, nil +} diff --git a/azurerm/internal/services/eventgrid/tests/eventgrid_domain_resource_test.go b/azurerm/internal/services/eventgrid/tests/eventgrid_domain_resource_test.go index 3dd1e68cfccc6..1a406056fc4b8 100644 --- a/azurerm/internal/services/eventgrid/tests/eventgrid_domain_resource_test.go +++ b/azurerm/internal/services/eventgrid/tests/eventgrid_domain_resource_test.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -34,6 +35,33 @@ func TestAccAzureRMEventGridDomain_basic(t *testing.T) { }) } +func TestAccAzureRMEventGridDomain_requiresImport(t *testing.T) { + if !features.ShouldResourcesBeImported() { + t.Skip("Skipping since resources aren't required to be imported") + return + } + + data := acceptance.BuildTestData(t, "azurerm_eventgrid_domain", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMEventGridDomainDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMEventGridDomain_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMEventGridDomainExists(data.ResourceName), + ), + }, + { + Config: testAccAzureRMEventGridDomain_requiresImport(data), + ExpectError: acceptance.RequiresImportError("azurerm_eventgrid_domain"), + }, + }, + }) +} + func TestAccAzureRMEventGridDomain_mapping(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_eventgrid_domain", "test") @@ -156,6 +184,19 @@ resource "azurerm_eventgrid_domain" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } +func testAccAzureRMEventGridDomain_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMEventGridDomain_basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_eventgrid_domain" "import" { + name = azurerm_eventgrid_domain.test.name + location = azurerm_eventgrid_domain.test.location + resource_group_name = azurerm_eventgrid_domain.test.resource_group_name +} +`, template) +} + func testAccAzureRMEventGridDomain_mapping(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/azurerm/internal/services/eventgrid/tests/eventgrid_event_subscription_resource_test.go b/azurerm/internal/services/eventgrid/tests/eventgrid_event_subscription_resource_test.go index 5d0000541e6d7..32ef7d96271e9 100644 --- a/azurerm/internal/services/eventgrid/tests/eventgrid_event_subscription_resource_test.go +++ b/azurerm/internal/services/eventgrid/tests/eventgrid_event_subscription_resource_test.go @@ -44,7 +44,7 @@ func TestAccAzureRMEventGridEventSubscription_eventhub(t *testing.T) { Config: testAccAzureRMEventGridEventSubscription_eventhub(data), Check: resource.ComposeTestCheckFunc( testCheckAzureRMEventGridEventSubscriptionExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "event_delivery_schema", "CloudEventV01Schema"), + resource.TestCheckResourceAttr(data.ResourceName, "event_delivery_schema", "CloudEventSchemaV1_0"), resource.TestCheckResourceAttr(data.ResourceName, "eventhub_endpoint.#", "1"), ), }, @@ -346,7 +346,7 @@ resource "azurerm_eventhub" "test" { resource "azurerm_eventgrid_event_subscription" "test" { name = "acctesteg-%d" scope = azurerm_resource_group.test.id - event_delivery_schema = "CloudEventV01Schema" + event_delivery_schema = "CloudEventSchemaV1_0" eventhub_endpoint { eventhub_id = azurerm_eventhub.test.id diff --git a/azurerm/utils/array.go b/azurerm/utils/array.go new file mode 100644 index 0000000000000..24a4c6a713dbb --- /dev/null +++ b/azurerm/utils/array.go @@ -0,0 +1,11 @@ +package utils + +// RemoveFromStringArray removes all matching values from a string array +func RemoveFromStringArray(elements []string, remove string) []string { + for i, v := range elements { + if v == remove { + return append(elements[:i], elements[i+1:]...) + } + } + return elements +} diff --git a/go.sum b/go.sum index 73c819a2062a8..5232a314397d2 100644 --- a/go.sum +++ b/go.sum @@ -308,6 +308,7 @@ golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0 h1:Dh6fw+p6FyRl5x/FvNswO1ji0lIGzm3KP8Y9VkS9PTE= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domaintopics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domaintopics.go deleted file mode 100644 index 0c8b9214eaa8e..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domaintopics.go +++ /dev/null @@ -1,196 +0,0 @@ -package eventgrid - -// 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" -) - -// DomainTopicsClient is the azure EventGrid Management Client -type DomainTopicsClient struct { - BaseClient -} - -// NewDomainTopicsClient creates an instance of the DomainTopicsClient client. -func NewDomainTopicsClient(subscriptionID string) DomainTopicsClient { - return NewDomainTopicsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewDomainTopicsClientWithBaseURI creates an instance of the DomainTopicsClient client using a custom endpoint. Use -// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). -func NewDomainTopicsClientWithBaseURI(baseURI string, subscriptionID string) DomainTopicsClient { - return DomainTopicsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// Get get properties of a domain topic -// Parameters: -// resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain -// topicName - name of the topic -func (client DomainTopicsClient) Get(ctx context.Context, resourceGroupName string, domainName string, topicName string) (result DomainTopic, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.Get") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetPreparer(ctx, resourceGroupName, domainName, topicName) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client DomainTopicsClient) GetPreparer(ctx context.Context, resourceGroupName string, domainName string, topicName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "topicName": autorest.Encode("path", topicName), - } - - const APIVersion = "2018-09-15-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/domains/{domainName}/topics/{topicName}", 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 DomainTopicsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client DomainTopicsClient) GetResponder(resp *http.Response) (result DomainTopic, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByDomain list all the topics in a domain. -// Parameters: -// resourceGroupName - the name of the resource group within the user's subscription. -// domainName - domain name. -func (client DomainTopicsClient) ListByDomain(ctx context.Context, resourceGroupName string, domainName string) (result DomainTopicsListResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.ListByDomain") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.ListByDomainPreparer(ctx, resourceGroupName, domainName) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "ListByDomain", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDomainSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "ListByDomain", resp, "Failure sending request") - return - } - - result, err = client.ListByDomainResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "ListByDomain", resp, "Failure responding to request") - } - - return -} - -// ListByDomainPreparer prepares the ListByDomain request. -func (client DomainTopicsClient) ListByDomainPreparer(ctx context.Context, resourceGroupName string, domainName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "domainName": autorest.Encode("path", domainName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2018-09-15-preview" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/domains/{domainName}/topics", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDomainSender sends the ListByDomain request. The method will close the -// http.Response Body if it receives an error. -func (client DomainTopicsClient) ListByDomainSender(req *http.Request) (*http.Response, error) { - return client.Send(req, azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDomainResponder handles the response to the ListByDomain request. The method always -// closes the http.Response Body. -func (client DomainTopicsClient) ListByDomainResponder(resp *http.Response) (result DomainTopicsListResult, 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/eventgrid/mgmt/2018-09-15-preview/eventgrid/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/models.go deleted file mode 100644 index 53c8b1cb83eab..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/models.go +++ /dev/null @@ -1,3712 +0,0 @@ -package eventgrid - -// 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/date" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid" - -// DomainProvisioningState enumerates the values for domain provisioning state. -type DomainProvisioningState string - -const ( - // Canceled ... - Canceled DomainProvisioningState = "Canceled" - // Creating ... - Creating DomainProvisioningState = "Creating" - // Deleting ... - Deleting DomainProvisioningState = "Deleting" - // Failed ... - Failed DomainProvisioningState = "Failed" - // Succeeded ... - Succeeded DomainProvisioningState = "Succeeded" - // Updating ... - Updating DomainProvisioningState = "Updating" -) - -// PossibleDomainProvisioningStateValues returns an array of possible values for the DomainProvisioningState const type. -func PossibleDomainProvisioningStateValues() []DomainProvisioningState { - return []DomainProvisioningState{Canceled, Creating, Deleting, Failed, Succeeded, Updating} -} - -// EndpointType enumerates the values for endpoint type. -type EndpointType string - -const ( - // EndpointTypeEventHub ... - EndpointTypeEventHub EndpointType = "EventHub" - // EndpointTypeEventSubscriptionDestination ... - EndpointTypeEventSubscriptionDestination EndpointType = "EventSubscriptionDestination" - // EndpointTypeHybridConnection ... - EndpointTypeHybridConnection EndpointType = "HybridConnection" - // EndpointTypeStorageQueue ... - EndpointTypeStorageQueue EndpointType = "StorageQueue" - // EndpointTypeWebHook ... - EndpointTypeWebHook EndpointType = "WebHook" -) - -// PossibleEndpointTypeValues returns an array of possible values for the EndpointType const type. -func PossibleEndpointTypeValues() []EndpointType { - return []EndpointType{EndpointTypeEventHub, EndpointTypeEventSubscriptionDestination, EndpointTypeHybridConnection, EndpointTypeStorageQueue, EndpointTypeWebHook} -} - -// EndpointTypeBasicDeadLetterDestination enumerates the values for endpoint type basic dead letter -// destination. -type EndpointTypeBasicDeadLetterDestination string - -const ( - // EndpointTypeDeadLetterDestination ... - EndpointTypeDeadLetterDestination EndpointTypeBasicDeadLetterDestination = "DeadLetterDestination" - // EndpointTypeStorageBlob ... - EndpointTypeStorageBlob EndpointTypeBasicDeadLetterDestination = "StorageBlob" -) - -// PossibleEndpointTypeBasicDeadLetterDestinationValues returns an array of possible values for the EndpointTypeBasicDeadLetterDestination const type. -func PossibleEndpointTypeBasicDeadLetterDestinationValues() []EndpointTypeBasicDeadLetterDestination { - return []EndpointTypeBasicDeadLetterDestination{EndpointTypeDeadLetterDestination, EndpointTypeStorageBlob} -} - -// EventDeliverySchema enumerates the values for event delivery schema. -type EventDeliverySchema string - -const ( - // CloudEventV01Schema ... - CloudEventV01Schema EventDeliverySchema = "CloudEventV01Schema" - // CustomInputSchema ... - CustomInputSchema EventDeliverySchema = "CustomInputSchema" - // EventGridSchema ... - EventGridSchema EventDeliverySchema = "EventGridSchema" -) - -// PossibleEventDeliverySchemaValues returns an array of possible values for the EventDeliverySchema const type. -func PossibleEventDeliverySchemaValues() []EventDeliverySchema { - return []EventDeliverySchema{CloudEventV01Schema, CustomInputSchema, EventGridSchema} -} - -// EventSubscriptionProvisioningState enumerates the values for event subscription provisioning state. -type EventSubscriptionProvisioningState string - -const ( - // EventSubscriptionProvisioningStateAwaitingManualAction ... - EventSubscriptionProvisioningStateAwaitingManualAction EventSubscriptionProvisioningState = "AwaitingManualAction" - // EventSubscriptionProvisioningStateCanceled ... - EventSubscriptionProvisioningStateCanceled EventSubscriptionProvisioningState = "Canceled" - // EventSubscriptionProvisioningStateCreating ... - EventSubscriptionProvisioningStateCreating EventSubscriptionProvisioningState = "Creating" - // EventSubscriptionProvisioningStateDeleting ... - EventSubscriptionProvisioningStateDeleting EventSubscriptionProvisioningState = "Deleting" - // EventSubscriptionProvisioningStateFailed ... - EventSubscriptionProvisioningStateFailed EventSubscriptionProvisioningState = "Failed" - // EventSubscriptionProvisioningStateSucceeded ... - EventSubscriptionProvisioningStateSucceeded EventSubscriptionProvisioningState = "Succeeded" - // EventSubscriptionProvisioningStateUpdating ... - EventSubscriptionProvisioningStateUpdating EventSubscriptionProvisioningState = "Updating" -) - -// PossibleEventSubscriptionProvisioningStateValues returns an array of possible values for the EventSubscriptionProvisioningState const type. -func PossibleEventSubscriptionProvisioningStateValues() []EventSubscriptionProvisioningState { - return []EventSubscriptionProvisioningState{EventSubscriptionProvisioningStateAwaitingManualAction, EventSubscriptionProvisioningStateCanceled, EventSubscriptionProvisioningStateCreating, EventSubscriptionProvisioningStateDeleting, EventSubscriptionProvisioningStateFailed, EventSubscriptionProvisioningStateSucceeded, EventSubscriptionProvisioningStateUpdating} -} - -// InputSchema enumerates the values for input schema. -type InputSchema string - -const ( - // InputSchemaCloudEventV01Schema ... - InputSchemaCloudEventV01Schema InputSchema = "CloudEventV01Schema" - // InputSchemaCustomEventSchema ... - InputSchemaCustomEventSchema InputSchema = "CustomEventSchema" - // InputSchemaEventGridSchema ... - InputSchemaEventGridSchema InputSchema = "EventGridSchema" -) - -// PossibleInputSchemaValues returns an array of possible values for the InputSchema const type. -func PossibleInputSchemaValues() []InputSchema { - return []InputSchema{InputSchemaCloudEventV01Schema, InputSchemaCustomEventSchema, InputSchemaEventGridSchema} -} - -// InputSchemaMappingType enumerates the values for input schema mapping type. -type InputSchemaMappingType string - -const ( - // InputSchemaMappingTypeInputSchemaMapping ... - InputSchemaMappingTypeInputSchemaMapping InputSchemaMappingType = "InputSchemaMapping" - // InputSchemaMappingTypeJSON ... - InputSchemaMappingTypeJSON InputSchemaMappingType = "Json" -) - -// PossibleInputSchemaMappingTypeValues returns an array of possible values for the InputSchemaMappingType const type. -func PossibleInputSchemaMappingTypeValues() []InputSchemaMappingType { - return []InputSchemaMappingType{InputSchemaMappingTypeInputSchemaMapping, InputSchemaMappingTypeJSON} -} - -// OperatorType enumerates the values for operator type. -type OperatorType string - -const ( - // OperatorTypeAdvancedFilter ... - OperatorTypeAdvancedFilter OperatorType = "AdvancedFilter" - // OperatorTypeBoolEquals ... - OperatorTypeBoolEquals OperatorType = "BoolEquals" - // OperatorTypeNumberGreaterThan ... - OperatorTypeNumberGreaterThan OperatorType = "NumberGreaterThan" - // OperatorTypeNumberGreaterThanOrEquals ... - OperatorTypeNumberGreaterThanOrEquals OperatorType = "NumberGreaterThanOrEquals" - // OperatorTypeNumberIn ... - OperatorTypeNumberIn OperatorType = "NumberIn" - // OperatorTypeNumberLessThan ... - OperatorTypeNumberLessThan OperatorType = "NumberLessThan" - // OperatorTypeNumberLessThanOrEquals ... - OperatorTypeNumberLessThanOrEquals OperatorType = "NumberLessThanOrEquals" - // OperatorTypeNumberNotIn ... - OperatorTypeNumberNotIn OperatorType = "NumberNotIn" - // OperatorTypeStringBeginsWith ... - OperatorTypeStringBeginsWith OperatorType = "StringBeginsWith" - // OperatorTypeStringContains ... - OperatorTypeStringContains OperatorType = "StringContains" - // OperatorTypeStringEndsWith ... - OperatorTypeStringEndsWith OperatorType = "StringEndsWith" - // OperatorTypeStringIn ... - OperatorTypeStringIn OperatorType = "StringIn" - // OperatorTypeStringNotIn ... - OperatorTypeStringNotIn OperatorType = "StringNotIn" -) - -// PossibleOperatorTypeValues returns an array of possible values for the OperatorType const type. -func PossibleOperatorTypeValues() []OperatorType { - return []OperatorType{OperatorTypeAdvancedFilter, OperatorTypeBoolEquals, OperatorTypeNumberGreaterThan, OperatorTypeNumberGreaterThanOrEquals, OperatorTypeNumberIn, OperatorTypeNumberLessThan, OperatorTypeNumberLessThanOrEquals, OperatorTypeNumberNotIn, OperatorTypeStringBeginsWith, OperatorTypeStringContains, OperatorTypeStringEndsWith, OperatorTypeStringIn, OperatorTypeStringNotIn} -} - -// ResourceRegionType enumerates the values for resource region type. -type ResourceRegionType string - -const ( - // GlobalResource ... - GlobalResource ResourceRegionType = "GlobalResource" - // RegionalResource ... - RegionalResource ResourceRegionType = "RegionalResource" -) - -// PossibleResourceRegionTypeValues returns an array of possible values for the ResourceRegionType const type. -func PossibleResourceRegionTypeValues() []ResourceRegionType { - return []ResourceRegionType{GlobalResource, RegionalResource} -} - -// TopicProvisioningState enumerates the values for topic provisioning state. -type TopicProvisioningState string - -const ( - // TopicProvisioningStateCanceled ... - TopicProvisioningStateCanceled TopicProvisioningState = "Canceled" - // TopicProvisioningStateCreating ... - TopicProvisioningStateCreating TopicProvisioningState = "Creating" - // TopicProvisioningStateDeleting ... - TopicProvisioningStateDeleting TopicProvisioningState = "Deleting" - // TopicProvisioningStateFailed ... - TopicProvisioningStateFailed TopicProvisioningState = "Failed" - // TopicProvisioningStateSucceeded ... - TopicProvisioningStateSucceeded TopicProvisioningState = "Succeeded" - // TopicProvisioningStateUpdating ... - TopicProvisioningStateUpdating TopicProvisioningState = "Updating" -) - -// PossibleTopicProvisioningStateValues returns an array of possible values for the TopicProvisioningState const type. -func PossibleTopicProvisioningStateValues() []TopicProvisioningState { - return []TopicProvisioningState{TopicProvisioningStateCanceled, TopicProvisioningStateCreating, TopicProvisioningStateDeleting, TopicProvisioningStateFailed, TopicProvisioningStateSucceeded, TopicProvisioningStateUpdating} -} - -// TopicTypeProvisioningState enumerates the values for topic type provisioning state. -type TopicTypeProvisioningState string - -const ( - // TopicTypeProvisioningStateCanceled ... - TopicTypeProvisioningStateCanceled TopicTypeProvisioningState = "Canceled" - // TopicTypeProvisioningStateCreating ... - TopicTypeProvisioningStateCreating TopicTypeProvisioningState = "Creating" - // TopicTypeProvisioningStateDeleting ... - TopicTypeProvisioningStateDeleting TopicTypeProvisioningState = "Deleting" - // TopicTypeProvisioningStateFailed ... - TopicTypeProvisioningStateFailed TopicTypeProvisioningState = "Failed" - // TopicTypeProvisioningStateSucceeded ... - TopicTypeProvisioningStateSucceeded TopicTypeProvisioningState = "Succeeded" - // TopicTypeProvisioningStateUpdating ... - TopicTypeProvisioningStateUpdating TopicTypeProvisioningState = "Updating" -) - -// PossibleTopicTypeProvisioningStateValues returns an array of possible values for the TopicTypeProvisioningState const type. -func PossibleTopicTypeProvisioningStateValues() []TopicTypeProvisioningState { - return []TopicTypeProvisioningState{TopicTypeProvisioningStateCanceled, TopicTypeProvisioningStateCreating, TopicTypeProvisioningStateDeleting, TopicTypeProvisioningStateFailed, TopicTypeProvisioningStateSucceeded, TopicTypeProvisioningStateUpdating} -} - -// BasicAdvancedFilter represents an advanced filter that can be used to filter events based on various event -// envelope/data fields. -type BasicAdvancedFilter interface { - AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) - AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) - AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) - AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) - AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) - AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) - AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) - AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) - AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) - AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) - AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) - AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) - AsAdvancedFilter() (*AdvancedFilter, bool) -} - -// AdvancedFilter represents an advanced filter that can be used to filter events based on various event -// envelope/data fields. -type AdvancedFilter struct { - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -func unmarshalBasicAdvancedFilter(body []byte) (BasicAdvancedFilter, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["operatorType"] { - case string(OperatorTypeNumberIn): - var niaf NumberInAdvancedFilter - err := json.Unmarshal(body, &niaf) - return niaf, err - case string(OperatorTypeNumberNotIn): - var nniaf NumberNotInAdvancedFilter - err := json.Unmarshal(body, &nniaf) - return nniaf, err - case string(OperatorTypeNumberLessThan): - var nltaf NumberLessThanAdvancedFilter - err := json.Unmarshal(body, &nltaf) - return nltaf, err - case string(OperatorTypeNumberGreaterThan): - var ngtaf NumberGreaterThanAdvancedFilter - err := json.Unmarshal(body, &ngtaf) - return ngtaf, err - case string(OperatorTypeNumberLessThanOrEquals): - var nltoeaf NumberLessThanOrEqualsAdvancedFilter - err := json.Unmarshal(body, &nltoeaf) - return nltoeaf, err - case string(OperatorTypeNumberGreaterThanOrEquals): - var ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter - err := json.Unmarshal(body, &ngtoeaf) - return ngtoeaf, err - case string(OperatorTypeBoolEquals): - var beaf BoolEqualsAdvancedFilter - err := json.Unmarshal(body, &beaf) - return beaf, err - case string(OperatorTypeStringIn): - var siaf StringInAdvancedFilter - err := json.Unmarshal(body, &siaf) - return siaf, err - case string(OperatorTypeStringNotIn): - var sniaf StringNotInAdvancedFilter - err := json.Unmarshal(body, &sniaf) - return sniaf, err - case string(OperatorTypeStringBeginsWith): - var sbwaf StringBeginsWithAdvancedFilter - err := json.Unmarshal(body, &sbwaf) - return sbwaf, err - case string(OperatorTypeStringEndsWith): - var sewaf StringEndsWithAdvancedFilter - err := json.Unmarshal(body, &sewaf) - return sewaf, err - case string(OperatorTypeStringContains): - var scaf StringContainsAdvancedFilter - err := json.Unmarshal(body, &scaf) - return scaf, err - default: - var af AdvancedFilter - err := json.Unmarshal(body, &af) - return af, err - } -} -func unmarshalBasicAdvancedFilterArray(body []byte) ([]BasicAdvancedFilter, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - afArray := make([]BasicAdvancedFilter, len(rawMessages)) - - for index, rawMessage := range rawMessages { - af, err := unmarshalBasicAdvancedFilter(*rawMessage) - if err != nil { - return nil, err - } - afArray[index] = af - } - return afArray, nil -} - -// MarshalJSON is the custom marshaler for AdvancedFilter. -func (af AdvancedFilter) MarshalJSON() ([]byte, error) { - af.OperatorType = OperatorTypeAdvancedFilter - objectMap := make(map[string]interface{}) - if af.Key != nil { - objectMap["key"] = af.Key - } - if af.OperatorType != "" { - objectMap["operatorType"] = af.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return &af, true -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. -func (af AdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &af, true -} - -// BoolEqualsAdvancedFilter boolEquals Filter -type BoolEqualsAdvancedFilter struct { - // Value - The filter value - Value *bool `json:"value,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) MarshalJSON() ([]byte, error) { - beaf.OperatorType = OperatorTypeBoolEquals - objectMap := make(map[string]interface{}) - if beaf.Value != nil { - objectMap["value"] = beaf.Value - } - if beaf.Key != nil { - objectMap["key"] = beaf.Key - } - if beaf.OperatorType != "" { - objectMap["operatorType"] = beaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return &beaf, true -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. -func (beaf BoolEqualsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &beaf, true -} - -// BasicDeadLetterDestination information about the dead letter destination for an event subscription. To configure a -// deadletter destination, do not directly instantiate an object of this class. Instead, instantiate an object of a -// derived class. Currently, StorageBlobDeadLetterDestination is the only class that derives from this class. -type BasicDeadLetterDestination interface { - AsStorageBlobDeadLetterDestination() (*StorageBlobDeadLetterDestination, bool) - AsDeadLetterDestination() (*DeadLetterDestination, bool) -} - -// DeadLetterDestination information about the dead letter destination for an event subscription. To configure -// a deadletter destination, do not directly instantiate an object of this class. Instead, instantiate an -// object of a derived class. Currently, StorageBlobDeadLetterDestination is the only class that derives from -// this class. -type DeadLetterDestination struct { - // EndpointType - Possible values include: 'EndpointTypeDeadLetterDestination', 'EndpointTypeStorageBlob' - EndpointType EndpointTypeBasicDeadLetterDestination `json:"endpointType,omitempty"` -} - -func unmarshalBasicDeadLetterDestination(body []byte) (BasicDeadLetterDestination, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["endpointType"] { - case string(EndpointTypeStorageBlob): - var sbdld StorageBlobDeadLetterDestination - err := json.Unmarshal(body, &sbdld) - return sbdld, err - default: - var dld DeadLetterDestination - err := json.Unmarshal(body, &dld) - return dld, err - } -} -func unmarshalBasicDeadLetterDestinationArray(body []byte) ([]BasicDeadLetterDestination, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - dldArray := make([]BasicDeadLetterDestination, len(rawMessages)) - - for index, rawMessage := range rawMessages { - dld, err := unmarshalBasicDeadLetterDestination(*rawMessage) - if err != nil { - return nil, err - } - dldArray[index] = dld - } - return dldArray, nil -} - -// MarshalJSON is the custom marshaler for DeadLetterDestination. -func (dld DeadLetterDestination) MarshalJSON() ([]byte, error) { - dld.EndpointType = EndpointTypeDeadLetterDestination - objectMap := make(map[string]interface{}) - if dld.EndpointType != "" { - objectMap["endpointType"] = dld.EndpointType - } - return json.Marshal(objectMap) -} - -// AsStorageBlobDeadLetterDestination is the BasicDeadLetterDestination implementation for DeadLetterDestination. -func (dld DeadLetterDestination) AsStorageBlobDeadLetterDestination() (*StorageBlobDeadLetterDestination, bool) { - return nil, false -} - -// AsDeadLetterDestination is the BasicDeadLetterDestination implementation for DeadLetterDestination. -func (dld DeadLetterDestination) AsDeadLetterDestination() (*DeadLetterDestination, bool) { - return &dld, true -} - -// AsBasicDeadLetterDestination is the BasicDeadLetterDestination implementation for DeadLetterDestination. -func (dld DeadLetterDestination) AsBasicDeadLetterDestination() (BasicDeadLetterDestination, bool) { - return &dld, true -} - -// Domain eventGrid Domain -type Domain struct { - autorest.Response `json:"-"` - // DomainProperties - Properties of the domain - *DomainProperties `json:"properties,omitempty"` - // Location - Location of the resource - Location *string `json:"location,omitempty"` - // Tags - Tags of the resource - Tags map[string]*string `json:"tags"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Domain. -func (d Domain) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if d.DomainProperties != nil { - objectMap["properties"] = d.DomainProperties - } - if d.Location != nil { - objectMap["location"] = d.Location - } - if d.Tags != nil { - objectMap["tags"] = d.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Domain struct. -func (d *Domain) 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 domainProperties DomainProperties - err = json.Unmarshal(*v, &domainProperties) - if err != nil { - return err - } - d.DomainProperties = &domainProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - d.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - d.Tags = tags - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - d.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - d.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - d.Type = &typeVar - } - } - } - - return nil -} - -// DomainProperties properties of the Domain -type DomainProperties struct { - // ProvisioningState - READ-ONLY; Provisioning state of the domain. Possible values include: 'Creating', 'Updating', 'Deleting', 'Succeeded', 'Canceled', 'Failed' - ProvisioningState DomainProvisioningState `json:"provisioningState,omitempty"` - // Endpoint - READ-ONLY; Endpoint for the domain. - Endpoint *string `json:"endpoint,omitempty"` - // InputSchema - This determines the format that Event Grid should expect for incoming events published to the domain. Possible values include: 'InputSchemaEventGridSchema', 'InputSchemaCustomEventSchema', 'InputSchemaCloudEventV01Schema' - InputSchema InputSchema `json:"inputSchema,omitempty"` - // InputSchemaMapping - Information about the InputSchemaMapping which specified the info about mapping event payload. - InputSchemaMapping BasicInputSchemaMapping `json:"inputSchemaMapping,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for DomainProperties struct. -func (dp *DomainProperties) 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 "provisioningState": - if v != nil { - var provisioningState DomainProvisioningState - err = json.Unmarshal(*v, &provisioningState) - if err != nil { - return err - } - dp.ProvisioningState = provisioningState - } - case "endpoint": - if v != nil { - var endpoint string - err = json.Unmarshal(*v, &endpoint) - if err != nil { - return err - } - dp.Endpoint = &endpoint - } - case "inputSchema": - if v != nil { - var inputSchema InputSchema - err = json.Unmarshal(*v, &inputSchema) - if err != nil { - return err - } - dp.InputSchema = inputSchema - } - case "inputSchemaMapping": - if v != nil { - inputSchemaMapping, err := unmarshalBasicInputSchemaMapping(*v) - if err != nil { - return err - } - dp.InputSchemaMapping = inputSchemaMapping - } - } - } - - return nil -} - -// DomainRegenerateKeyRequest domain regenerate share access key request -type DomainRegenerateKeyRequest struct { - // KeyName - Key name to regenerate key1 or key2 - KeyName *string `json:"keyName,omitempty"` -} - -// DomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DomainsCreateOrUpdateFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *DomainsCreateOrUpdateFuture) Result(client DomainsClient) (d Domain, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.DomainsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { - d, err = client.CreateOrUpdateResponder(d.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainsCreateOrUpdateFuture", "Result", d.Response.Response, "Failure responding to request") - } - } - return -} - -// DomainsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DomainsDeleteFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *DomainsDeleteFuture) Result(client DomainsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.DomainsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// DomainSharedAccessKeys shared access keys of the Domain -type DomainSharedAccessKeys struct { - autorest.Response `json:"-"` - // Key1 - Shared access key1 for the domain. - Key1 *string `json:"key1,omitempty"` - // Key2 - Shared access key2 for the domain. - Key2 *string `json:"key2,omitempty"` -} - -// DomainsListResult result of the List Domains operation -type DomainsListResult struct { - autorest.Response `json:"-"` - // Value - A collection of Domains - Value *[]Domain `json:"value,omitempty"` -} - -// DomainsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type DomainsUpdateFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *DomainsUpdateFuture) Result(client DomainsClient) (d Domain, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.DomainsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { - d, err = client.UpdateResponder(d.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.DomainsUpdateFuture", "Result", d.Response.Response, "Failure responding to request") - } - } - return -} - -// DomainTopic domain Topic -type DomainTopic struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// DomainTopicsListResult result of the List Domain Topics operation -type DomainTopicsListResult struct { - autorest.Response `json:"-"` - // Value - A collection of Domain Topics - Value *[]DomainTopic `json:"value,omitempty"` -} - -// DomainUpdateParameters properties of the Domain update -type DomainUpdateParameters struct { - // Tags - Tags of the domains resource - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for DomainUpdateParameters. -func (dup DomainUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dup.Tags != nil { - objectMap["tags"] = dup.Tags - } - return json.Marshal(objectMap) -} - -// EventHubEventSubscriptionDestination information about the event hub destination for an event -// subscription -type EventHubEventSubscriptionDestination struct { - // EventHubEventSubscriptionDestinationProperties - Event Hub Properties of the event subscription destination - *EventHubEventSubscriptionDestinationProperties `json:"properties,omitempty"` - // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection' - EndpointType EndpointType `json:"endpointType,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) MarshalJSON() ([]byte, error) { - ehesd.EndpointType = EndpointTypeEventHub - objectMap := make(map[string]interface{}) - if ehesd.EventHubEventSubscriptionDestinationProperties != nil { - objectMap["properties"] = ehesd.EventHubEventSubscriptionDestinationProperties - } - if ehesd.EndpointType != "" { - objectMap["endpointType"] = ehesd.EndpointType - } - return json.Marshal(objectMap) -} - -// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { - return &ehesd, true -} - -// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { - return nil, false -} - -// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { - return nil, false -} - -// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. -func (ehesd EventHubEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { - return &ehesd, true -} - -// UnmarshalJSON is the custom unmarshaler for EventHubEventSubscriptionDestination struct. -func (ehesd *EventHubEventSubscriptionDestination) 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 eventHubEventSubscriptionDestinationProperties EventHubEventSubscriptionDestinationProperties - err = json.Unmarshal(*v, &eventHubEventSubscriptionDestinationProperties) - if err != nil { - return err - } - ehesd.EventHubEventSubscriptionDestinationProperties = &eventHubEventSubscriptionDestinationProperties - } - case "endpointType": - if v != nil { - var endpointType EndpointType - err = json.Unmarshal(*v, &endpointType) - if err != nil { - return err - } - ehesd.EndpointType = endpointType - } - } - } - - return nil -} - -// EventHubEventSubscriptionDestinationProperties the properties for a event hub destination. -type EventHubEventSubscriptionDestinationProperties struct { - // ResourceID - The Azure Resource Id that represents the endpoint of an Event Hub destination of an event subscription. - ResourceID *string `json:"resourceId,omitempty"` -} - -// EventSubscription event Subscription -type EventSubscription struct { - autorest.Response `json:"-"` - // EventSubscriptionProperties - Properties of the event subscription - *EventSubscriptionProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventSubscription. -func (es EventSubscription) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if es.EventSubscriptionProperties != nil { - objectMap["properties"] = es.EventSubscriptionProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for EventSubscription struct. -func (es *EventSubscription) 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 eventSubscriptionProperties EventSubscriptionProperties - err = json.Unmarshal(*v, &eventSubscriptionProperties) - if err != nil { - return err - } - es.EventSubscriptionProperties = &eventSubscriptionProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - es.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - es.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - es.Type = &typeVar - } - } - } - - return nil -} - -// BasicEventSubscriptionDestination information about the destination for an event subscription -type BasicEventSubscriptionDestination interface { - AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) - AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) - AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) - AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) - AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) -} - -// EventSubscriptionDestination information about the destination for an event subscription -type EventSubscriptionDestination struct { - // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection' - EndpointType EndpointType `json:"endpointType,omitempty"` -} - -func unmarshalBasicEventSubscriptionDestination(body []byte) (BasicEventSubscriptionDestination, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["endpointType"] { - case string(EndpointTypeWebHook): - var whesd WebHookEventSubscriptionDestination - err := json.Unmarshal(body, &whesd) - return whesd, err - case string(EndpointTypeEventHub): - var ehesd EventHubEventSubscriptionDestination - err := json.Unmarshal(body, &ehesd) - return ehesd, err - case string(EndpointTypeStorageQueue): - var sqesd StorageQueueEventSubscriptionDestination - err := json.Unmarshal(body, &sqesd) - return sqesd, err - case string(EndpointTypeHybridConnection): - var hcesd HybridConnectionEventSubscriptionDestination - err := json.Unmarshal(body, &hcesd) - return hcesd, err - default: - var esd EventSubscriptionDestination - err := json.Unmarshal(body, &esd) - return esd, err - } -} -func unmarshalBasicEventSubscriptionDestinationArray(body []byte) ([]BasicEventSubscriptionDestination, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - esdArray := make([]BasicEventSubscriptionDestination, len(rawMessages)) - - for index, rawMessage := range rawMessages { - esd, err := unmarshalBasicEventSubscriptionDestination(*rawMessage) - if err != nil { - return nil, err - } - esdArray[index] = esd - } - return esdArray, nil -} - -// MarshalJSON is the custom marshaler for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) MarshalJSON() ([]byte, error) { - esd.EndpointType = EndpointTypeEventSubscriptionDestination - objectMap := make(map[string]interface{}) - if esd.EndpointType != "" { - objectMap["endpointType"] = esd.EndpointType - } - return json.Marshal(objectMap) -} - -// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { - return nil, false -} - -// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { - return nil, false -} - -// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { - return &esd, true -} - -// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. -func (esd EventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { - return &esd, true -} - -// EventSubscriptionFilter filter for the Event Subscription -type EventSubscriptionFilter struct { - // SubjectBeginsWith - An optional string to filter events for an event subscription based on a resource path prefix. - // The format of this depends on the publisher of the events. - // Wildcard characters are not supported in this path. - SubjectBeginsWith *string `json:"subjectBeginsWith,omitempty"` - // SubjectEndsWith - An optional string to filter events for an event subscription based on a resource path suffix. - // Wildcard characters are not supported in this path. - SubjectEndsWith *string `json:"subjectEndsWith,omitempty"` - // IncludedEventTypes - A list of applicable event types that need to be part of the event subscription. - // If it is desired to subscribe to all event types, the string "all" needs to be specified as an element in this list. - IncludedEventTypes *[]string `json:"includedEventTypes,omitempty"` - // IsSubjectCaseSensitive - Specifies if the SubjectBeginsWith and SubjectEndsWith properties of the filter - // should be compared in a case sensitive manner. - IsSubjectCaseSensitive *bool `json:"isSubjectCaseSensitive,omitempty"` - // AdvancedFilters - A list of advanced filters. - AdvancedFilters *[]BasicAdvancedFilter `json:"advancedFilters,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for EventSubscriptionFilter struct. -func (esf *EventSubscriptionFilter) 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 "subjectBeginsWith": - if v != nil { - var subjectBeginsWith string - err = json.Unmarshal(*v, &subjectBeginsWith) - if err != nil { - return err - } - esf.SubjectBeginsWith = &subjectBeginsWith - } - case "subjectEndsWith": - if v != nil { - var subjectEndsWith string - err = json.Unmarshal(*v, &subjectEndsWith) - if err != nil { - return err - } - esf.SubjectEndsWith = &subjectEndsWith - } - case "includedEventTypes": - if v != nil { - var includedEventTypes []string - err = json.Unmarshal(*v, &includedEventTypes) - if err != nil { - return err - } - esf.IncludedEventTypes = &includedEventTypes - } - case "isSubjectCaseSensitive": - if v != nil { - var isSubjectCaseSensitive bool - err = json.Unmarshal(*v, &isSubjectCaseSensitive) - if err != nil { - return err - } - esf.IsSubjectCaseSensitive = &isSubjectCaseSensitive - } - case "advancedFilters": - if v != nil { - advancedFilters, err := unmarshalBasicAdvancedFilterArray(*v) - if err != nil { - return err - } - esf.AdvancedFilters = &advancedFilters - } - } - } - - return nil -} - -// EventSubscriptionFullURL full endpoint url of an event subscription -type EventSubscriptionFullURL struct { - autorest.Response `json:"-"` - // EndpointURL - The URL that represents the endpoint of the destination of an event subscription. - EndpointURL *string `json:"endpointUrl,omitempty"` -} - -// EventSubscriptionProperties properties of the Event Subscription -type EventSubscriptionProperties struct { - // Topic - READ-ONLY; Name of the topic of the event subscription. - Topic *string `json:"topic,omitempty"` - // ProvisioningState - READ-ONLY; Provisioning state of the event subscription. Possible values include: 'EventSubscriptionProvisioningStateCreating', 'EventSubscriptionProvisioningStateUpdating', 'EventSubscriptionProvisioningStateDeleting', 'EventSubscriptionProvisioningStateSucceeded', 'EventSubscriptionProvisioningStateCanceled', 'EventSubscriptionProvisioningStateFailed', 'EventSubscriptionProvisioningStateAwaitingManualAction' - ProvisioningState EventSubscriptionProvisioningState `json:"provisioningState,omitempty"` - // Destination - Information about the destination where events have to be delivered for the event subscription. - Destination BasicEventSubscriptionDestination `json:"destination,omitempty"` - // Filter - Information about the filter for the event subscription. - Filter *EventSubscriptionFilter `json:"filter,omitempty"` - // Labels - List of user defined labels. - Labels *[]string `json:"labels,omitempty"` - // ExpirationTimeUtc - Expiration time of the event subscription. - ExpirationTimeUtc *date.Time `json:"expirationTimeUtc,omitempty"` - // EventDeliverySchema - The event delivery schema for the event subscription. Possible values include: 'EventGridSchema', 'CloudEventV01Schema', 'CustomInputSchema' - EventDeliverySchema EventDeliverySchema `json:"eventDeliverySchema,omitempty"` - // RetryPolicy - The retry policy for events. This can be used to configure maximum number of delivery attempts and time to live for events. - RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` - // DeadLetterDestination - The DeadLetter destination of the event subscription. - DeadLetterDestination BasicDeadLetterDestination `json:"deadLetterDestination,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for EventSubscriptionProperties struct. -func (esp *EventSubscriptionProperties) 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 "topic": - if v != nil { - var topic string - err = json.Unmarshal(*v, &topic) - if err != nil { - return err - } - esp.Topic = &topic - } - case "provisioningState": - if v != nil { - var provisioningState EventSubscriptionProvisioningState - err = json.Unmarshal(*v, &provisioningState) - if err != nil { - return err - } - esp.ProvisioningState = provisioningState - } - case "destination": - if v != nil { - destination, err := unmarshalBasicEventSubscriptionDestination(*v) - if err != nil { - return err - } - esp.Destination = destination - } - case "filter": - if v != nil { - var filter EventSubscriptionFilter - err = json.Unmarshal(*v, &filter) - if err != nil { - return err - } - esp.Filter = &filter - } - case "labels": - if v != nil { - var labels []string - err = json.Unmarshal(*v, &labels) - if err != nil { - return err - } - esp.Labels = &labels - } - case "expirationTimeUtc": - if v != nil { - var expirationTimeUtc date.Time - err = json.Unmarshal(*v, &expirationTimeUtc) - if err != nil { - return err - } - esp.ExpirationTimeUtc = &expirationTimeUtc - } - case "eventDeliverySchema": - if v != nil { - var eventDeliverySchema EventDeliverySchema - err = json.Unmarshal(*v, &eventDeliverySchema) - if err != nil { - return err - } - esp.EventDeliverySchema = eventDeliverySchema - } - case "retryPolicy": - if v != nil { - var retryPolicy RetryPolicy - err = json.Unmarshal(*v, &retryPolicy) - if err != nil { - return err - } - esp.RetryPolicy = &retryPolicy - } - case "deadLetterDestination": - if v != nil { - deadLetterDestination, err := unmarshalBasicDeadLetterDestination(*v) - if err != nil { - return err - } - esp.DeadLetterDestination = deadLetterDestination - } - } - } - - return nil -} - -// EventSubscriptionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type EventSubscriptionsCreateOrUpdateFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *EventSubscriptionsCreateOrUpdateFuture) Result(client EventSubscriptionsClient) (es EventSubscription, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.EventSubscriptionsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { - es, err = client.CreateOrUpdateResponder(es.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsCreateOrUpdateFuture", "Result", es.Response.Response, "Failure responding to request") - } - } - return -} - -// EventSubscriptionsDeleteFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type EventSubscriptionsDeleteFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *EventSubscriptionsDeleteFuture) Result(client EventSubscriptionsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.EventSubscriptionsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// EventSubscriptionsListResult result of the List EventSubscriptions operation -type EventSubscriptionsListResult struct { - autorest.Response `json:"-"` - // Value - A collection of EventSubscriptions - Value *[]EventSubscription `json:"value,omitempty"` -} - -// EventSubscriptionsUpdateFuture an abstraction for monitoring and retrieving the results of a -// long-running operation. -type EventSubscriptionsUpdateFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *EventSubscriptionsUpdateFuture) Result(client EventSubscriptionsClient) (es EventSubscription, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.EventSubscriptionsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { - es, err = client.UpdateResponder(es.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsUpdateFuture", "Result", es.Response.Response, "Failure responding to request") - } - } - return -} - -// EventSubscriptionUpdateParameters properties of the Event Subscription update -type EventSubscriptionUpdateParameters struct { - // Destination - Information about the destination where events have to be delivered for the event subscription. - Destination BasicEventSubscriptionDestination `json:"destination,omitempty"` - // Filter - Information about the filter for the event subscription. - Filter *EventSubscriptionFilter `json:"filter,omitempty"` - // Labels - List of user defined labels. - Labels *[]string `json:"labels,omitempty"` - // ExpirationTimeUtc - Information about the expiration time for the event subscription. - ExpirationTimeUtc *date.Time `json:"expirationTimeUtc,omitempty"` - // EventDeliverySchema - The event delivery schema for the event subscription. Possible values include: 'EventGridSchema', 'CloudEventV01Schema', 'CustomInputSchema' - EventDeliverySchema EventDeliverySchema `json:"eventDeliverySchema,omitempty"` - // RetryPolicy - The retry policy for events. This can be used to configure maximum number of delivery attempts and time to live for events. - RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` - // DeadLetterDestination - The DeadLetter destination of the event subscription. - DeadLetterDestination BasicDeadLetterDestination `json:"deadLetterDestination,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for EventSubscriptionUpdateParameters struct. -func (esup *EventSubscriptionUpdateParameters) 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 "destination": - if v != nil { - destination, err := unmarshalBasicEventSubscriptionDestination(*v) - if err != nil { - return err - } - esup.Destination = destination - } - case "filter": - if v != nil { - var filter EventSubscriptionFilter - err = json.Unmarshal(*v, &filter) - if err != nil { - return err - } - esup.Filter = &filter - } - case "labels": - if v != nil { - var labels []string - err = json.Unmarshal(*v, &labels) - if err != nil { - return err - } - esup.Labels = &labels - } - case "expirationTimeUtc": - if v != nil { - var expirationTimeUtc date.Time - err = json.Unmarshal(*v, &expirationTimeUtc) - if err != nil { - return err - } - esup.ExpirationTimeUtc = &expirationTimeUtc - } - case "eventDeliverySchema": - if v != nil { - var eventDeliverySchema EventDeliverySchema - err = json.Unmarshal(*v, &eventDeliverySchema) - if err != nil { - return err - } - esup.EventDeliverySchema = eventDeliverySchema - } - case "retryPolicy": - if v != nil { - var retryPolicy RetryPolicy - err = json.Unmarshal(*v, &retryPolicy) - if err != nil { - return err - } - esup.RetryPolicy = &retryPolicy - } - case "deadLetterDestination": - if v != nil { - deadLetterDestination, err := unmarshalBasicDeadLetterDestination(*v) - if err != nil { - return err - } - esup.DeadLetterDestination = deadLetterDestination - } - } - } - - return nil -} - -// EventType event Type for a subject under a topic -type EventType struct { - // EventTypeProperties - Properties of the event type. - *EventTypeProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for EventType. -func (et EventType) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if et.EventTypeProperties != nil { - objectMap["properties"] = et.EventTypeProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for EventType struct. -func (et *EventType) 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 eventTypeProperties EventTypeProperties - err = json.Unmarshal(*v, &eventTypeProperties) - if err != nil { - return err - } - et.EventTypeProperties = &eventTypeProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - et.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - et.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - et.Type = &typeVar - } - } - } - - return nil -} - -// EventTypeProperties properties of the event type -type EventTypeProperties struct { - // DisplayName - Display name of the event type. - DisplayName *string `json:"displayName,omitempty"` - // Description - Description of the event type. - Description *string `json:"description,omitempty"` - // SchemaURL - Url of the schema for this event type. - SchemaURL *string `json:"schemaUrl,omitempty"` -} - -// EventTypesListResult result of the List Event Types operation -type EventTypesListResult struct { - autorest.Response `json:"-"` - // Value - A collection of event types - Value *[]EventType `json:"value,omitempty"` -} - -// HybridConnectionEventSubscriptionDestination information about the HybridConnection destination for an -// event subscription. -type HybridConnectionEventSubscriptionDestination struct { - // HybridConnectionEventSubscriptionDestinationProperties - Hybrid connection Properties of the event subscription destination - *HybridConnectionEventSubscriptionDestinationProperties `json:"properties,omitempty"` - // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection' - EndpointType EndpointType `json:"endpointType,omitempty"` -} - -// MarshalJSON is the custom marshaler for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) MarshalJSON() ([]byte, error) { - hcesd.EndpointType = EndpointTypeHybridConnection - objectMap := make(map[string]interface{}) - if hcesd.HybridConnectionEventSubscriptionDestinationProperties != nil { - objectMap["properties"] = hcesd.HybridConnectionEventSubscriptionDestinationProperties - } - if hcesd.EndpointType != "" { - objectMap["endpointType"] = hcesd.EndpointType - } - return json.Marshal(objectMap) -} - -// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { - return nil, false -} - -// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { - return nil, false -} - -// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { - return &hcesd, true -} - -// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { - return nil, false -} - -// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. -func (hcesd HybridConnectionEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { - return &hcesd, true -} - -// UnmarshalJSON is the custom unmarshaler for HybridConnectionEventSubscriptionDestination struct. -func (hcesd *HybridConnectionEventSubscriptionDestination) 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 hybridConnectionEventSubscriptionDestinationProperties HybridConnectionEventSubscriptionDestinationProperties - err = json.Unmarshal(*v, &hybridConnectionEventSubscriptionDestinationProperties) - if err != nil { - return err - } - hcesd.HybridConnectionEventSubscriptionDestinationProperties = &hybridConnectionEventSubscriptionDestinationProperties - } - case "endpointType": - if v != nil { - var endpointType EndpointType - err = json.Unmarshal(*v, &endpointType) - if err != nil { - return err - } - hcesd.EndpointType = endpointType - } - } - } - - return nil -} - -// HybridConnectionEventSubscriptionDestinationProperties the properties for a hybrid connection -// destination. -type HybridConnectionEventSubscriptionDestinationProperties struct { - // ResourceID - The Azure Resource ID of an hybrid connection that is the destination of an event subscription. - ResourceID *string `json:"resourceId,omitempty"` -} - -// BasicInputSchemaMapping by default, Event Grid expects events to be in the Event Grid event schema. Specifying an -// input schema mapping enables publishing to Event Grid using a custom input schema. Currently, the only supported -// type of InputSchemaMapping is 'JsonInputSchemaMapping'. -type BasicInputSchemaMapping interface { - AsJSONInputSchemaMapping() (*JSONInputSchemaMapping, bool) - AsInputSchemaMapping() (*InputSchemaMapping, bool) -} - -// InputSchemaMapping by default, Event Grid expects events to be in the Event Grid event schema. Specifying an -// input schema mapping enables publishing to Event Grid using a custom input schema. Currently, the only -// supported type of InputSchemaMapping is 'JsonInputSchemaMapping'. -type InputSchemaMapping struct { - // InputSchemaMappingType - Possible values include: 'InputSchemaMappingTypeInputSchemaMapping', 'InputSchemaMappingTypeJSON' - InputSchemaMappingType InputSchemaMappingType `json:"inputSchemaMappingType,omitempty"` -} - -func unmarshalBasicInputSchemaMapping(body []byte) (BasicInputSchemaMapping, error) { - var m map[string]interface{} - err := json.Unmarshal(body, &m) - if err != nil { - return nil, err - } - - switch m["inputSchemaMappingType"] { - case string(InputSchemaMappingTypeJSON): - var jism JSONInputSchemaMapping - err := json.Unmarshal(body, &jism) - return jism, err - default: - var ism InputSchemaMapping - err := json.Unmarshal(body, &ism) - return ism, err - } -} -func unmarshalBasicInputSchemaMappingArray(body []byte) ([]BasicInputSchemaMapping, error) { - var rawMessages []*json.RawMessage - err := json.Unmarshal(body, &rawMessages) - if err != nil { - return nil, err - } - - ismArray := make([]BasicInputSchemaMapping, len(rawMessages)) - - for index, rawMessage := range rawMessages { - ism, err := unmarshalBasicInputSchemaMapping(*rawMessage) - if err != nil { - return nil, err - } - ismArray[index] = ism - } - return ismArray, nil -} - -// MarshalJSON is the custom marshaler for InputSchemaMapping. -func (ism InputSchemaMapping) MarshalJSON() ([]byte, error) { - ism.InputSchemaMappingType = InputSchemaMappingTypeInputSchemaMapping - objectMap := make(map[string]interface{}) - if ism.InputSchemaMappingType != "" { - objectMap["inputSchemaMappingType"] = ism.InputSchemaMappingType - } - return json.Marshal(objectMap) -} - -// AsJSONInputSchemaMapping is the BasicInputSchemaMapping implementation for InputSchemaMapping. -func (ism InputSchemaMapping) AsJSONInputSchemaMapping() (*JSONInputSchemaMapping, bool) { - return nil, false -} - -// AsInputSchemaMapping is the BasicInputSchemaMapping implementation for InputSchemaMapping. -func (ism InputSchemaMapping) AsInputSchemaMapping() (*InputSchemaMapping, bool) { - return &ism, true -} - -// AsBasicInputSchemaMapping is the BasicInputSchemaMapping implementation for InputSchemaMapping. -func (ism InputSchemaMapping) AsBasicInputSchemaMapping() (BasicInputSchemaMapping, bool) { - return &ism, true -} - -// JSONField this is used to express the source of an input schema mapping for a single target field in the -// Event Grid Event schema. This is currently used in the mappings for the 'id','topic' and 'eventTime' -// properties. This represents a field in the input event schema. -type JSONField struct { - // SourceField - Name of a field in the input event schema that's to be used as the source of a mapping. - SourceField *string `json:"sourceField,omitempty"` -} - -// JSONFieldWithDefault this is used to express the source of an input schema mapping for a single target -// field in the Event Grid Event schema. This is currently used in the mappings for the -// 'subject','eventType' and 'dataVersion' properties. This represents a field in the input event schema -// along with a default value to be used, and at least one of these two properties should be provided. -type JSONFieldWithDefault struct { - // SourceField - Name of a field in the input event schema that's to be used as the source of a mapping. - SourceField *string `json:"sourceField,omitempty"` - // DefaultValue - The default value to be used for mapping when a SourceField is not provided or if there's no property with the specified name in the published JSON event payload. - DefaultValue *string `json:"defaultValue,omitempty"` -} - -// JSONInputSchemaMapping this enables publishing to Event Grid using a custom input schema. This can be -// used to map properties from a custom input JSON schema to the Event Grid event schema. -type JSONInputSchemaMapping struct { - // JSONInputSchemaMappingProperties - JSON Properties of the input schema mapping - *JSONInputSchemaMappingProperties `json:"properties,omitempty"` - // InputSchemaMappingType - Possible values include: 'InputSchemaMappingTypeInputSchemaMapping', 'InputSchemaMappingTypeJSON' - InputSchemaMappingType InputSchemaMappingType `json:"inputSchemaMappingType,omitempty"` -} - -// MarshalJSON is the custom marshaler for JSONInputSchemaMapping. -func (jism JSONInputSchemaMapping) MarshalJSON() ([]byte, error) { - jism.InputSchemaMappingType = InputSchemaMappingTypeJSON - objectMap := make(map[string]interface{}) - if jism.JSONInputSchemaMappingProperties != nil { - objectMap["properties"] = jism.JSONInputSchemaMappingProperties - } - if jism.InputSchemaMappingType != "" { - objectMap["inputSchemaMappingType"] = jism.InputSchemaMappingType - } - return json.Marshal(objectMap) -} - -// AsJSONInputSchemaMapping is the BasicInputSchemaMapping implementation for JSONInputSchemaMapping. -func (jism JSONInputSchemaMapping) AsJSONInputSchemaMapping() (*JSONInputSchemaMapping, bool) { - return &jism, true -} - -// AsInputSchemaMapping is the BasicInputSchemaMapping implementation for JSONInputSchemaMapping. -func (jism JSONInputSchemaMapping) AsInputSchemaMapping() (*InputSchemaMapping, bool) { - return nil, false -} - -// AsBasicInputSchemaMapping is the BasicInputSchemaMapping implementation for JSONInputSchemaMapping. -func (jism JSONInputSchemaMapping) AsBasicInputSchemaMapping() (BasicInputSchemaMapping, bool) { - return &jism, true -} - -// UnmarshalJSON is the custom unmarshaler for JSONInputSchemaMapping struct. -func (jism *JSONInputSchemaMapping) 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 JSONInputSchemaMappingProperties JSONInputSchemaMappingProperties - err = json.Unmarshal(*v, &JSONInputSchemaMappingProperties) - if err != nil { - return err - } - jism.JSONInputSchemaMappingProperties = &JSONInputSchemaMappingProperties - } - case "inputSchemaMappingType": - if v != nil { - var inputSchemaMappingType InputSchemaMappingType - err = json.Unmarshal(*v, &inputSchemaMappingType) - if err != nil { - return err - } - jism.InputSchemaMappingType = inputSchemaMappingType - } - } - } - - return nil -} - -// JSONInputSchemaMappingProperties this can be used to map properties of a source schema (or default -// values, for certain supported properties) to properties of the EventGridEvent schema. -type JSONInputSchemaMappingProperties struct { - // ID - The mapping information for the Id property of the Event Grid Event. - ID *JSONField `json:"id,omitempty"` - // Topic - The mapping information for the Topic property of the Event Grid Event. - Topic *JSONField `json:"topic,omitempty"` - // EventTime - The mapping information for the EventTime property of the Event Grid Event. - EventTime *JSONField `json:"eventTime,omitempty"` - // EventType - The mapping information for the EventType property of the Event Grid Event. - EventType *JSONFieldWithDefault `json:"eventType,omitempty"` - // Subject - The mapping information for the Subject property of the Event Grid Event. - Subject *JSONFieldWithDefault `json:"subject,omitempty"` - // DataVersion - The mapping information for the DataVersion property of the Event Grid Event. - DataVersion *JSONFieldWithDefault `json:"dataVersion,omitempty"` -} - -// NumberGreaterThanAdvancedFilter numberGreaterThan Filter -type NumberGreaterThanAdvancedFilter struct { - // Value - The filter value - Value *float64 `json:"value,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) MarshalJSON() ([]byte, error) { - ngtaf.OperatorType = OperatorTypeNumberGreaterThan - objectMap := make(map[string]interface{}) - if ngtaf.Value != nil { - objectMap["value"] = ngtaf.Value - } - if ngtaf.Key != nil { - objectMap["key"] = ngtaf.Key - } - if ngtaf.OperatorType != "" { - objectMap["operatorType"] = ngtaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return &ngtaf, true -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. -func (ngtaf NumberGreaterThanAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &ngtaf, true -} - -// NumberGreaterThanOrEqualsAdvancedFilter numberGreaterThanOrEquals Filter -type NumberGreaterThanOrEqualsAdvancedFilter struct { - // Value - The filter value - Value *float64 `json:"value,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) MarshalJSON() ([]byte, error) { - ngtoeaf.OperatorType = OperatorTypeNumberGreaterThanOrEquals - objectMap := make(map[string]interface{}) - if ngtoeaf.Value != nil { - objectMap["value"] = ngtoeaf.Value - } - if ngtoeaf.Key != nil { - objectMap["key"] = ngtoeaf.Key - } - if ngtoeaf.OperatorType != "" { - objectMap["operatorType"] = ngtoeaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return &ngtoeaf, true -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. -func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &ngtoeaf, true -} - -// NumberInAdvancedFilter numberIn filter -type NumberInAdvancedFilter struct { - // Values - The set of filter values - Values *[]float64 `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) MarshalJSON() ([]byte, error) { - niaf.OperatorType = OperatorTypeNumberIn - objectMap := make(map[string]interface{}) - if niaf.Values != nil { - objectMap["values"] = niaf.Values - } - if niaf.Key != nil { - objectMap["key"] = niaf.Key - } - if niaf.OperatorType != "" { - objectMap["operatorType"] = niaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return &niaf, true -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. -func (niaf NumberInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &niaf, true -} - -// NumberLessThanAdvancedFilter numberLessThan Filter -type NumberLessThanAdvancedFilter struct { - // Value - The filter value - Value *float64 `json:"value,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) MarshalJSON() ([]byte, error) { - nltaf.OperatorType = OperatorTypeNumberLessThan - objectMap := make(map[string]interface{}) - if nltaf.Value != nil { - objectMap["value"] = nltaf.Value - } - if nltaf.Key != nil { - objectMap["key"] = nltaf.Key - } - if nltaf.OperatorType != "" { - objectMap["operatorType"] = nltaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return &nltaf, true -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. -func (nltaf NumberLessThanAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &nltaf, true -} - -// NumberLessThanOrEqualsAdvancedFilter numberLessThanOrEquals Filter -type NumberLessThanOrEqualsAdvancedFilter struct { - // Value - The filter value - Value *float64 `json:"value,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) MarshalJSON() ([]byte, error) { - nltoeaf.OperatorType = OperatorTypeNumberLessThanOrEquals - objectMap := make(map[string]interface{}) - if nltoeaf.Value != nil { - objectMap["value"] = nltoeaf.Value - } - if nltoeaf.Key != nil { - objectMap["key"] = nltoeaf.Key - } - if nltoeaf.OperatorType != "" { - objectMap["operatorType"] = nltoeaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return &nltoeaf, true -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. -func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &nltoeaf, true -} - -// NumberNotInAdvancedFilter numberNotIn Filter -type NumberNotInAdvancedFilter struct { - // Values - The set of filter values - Values *[]float64 `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) MarshalJSON() ([]byte, error) { - nniaf.OperatorType = OperatorTypeNumberNotIn - objectMap := make(map[string]interface{}) - if nniaf.Values != nil { - objectMap["values"] = nniaf.Values - } - if nniaf.Key != nil { - objectMap["key"] = nniaf.Key - } - if nniaf.OperatorType != "" { - objectMap["operatorType"] = nniaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return &nniaf, true -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. -func (nniaf NumberNotInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &nniaf, true -} - -// Operation represents an operation returned by the GetOperations request -type Operation struct { - // Name - Name of the operation - Name *string `json:"name,omitempty"` - // Display - Display name of the operation - Display *OperationInfo `json:"display,omitempty"` - // Origin - Origin of the operation - Origin *string `json:"origin,omitempty"` - // Properties - Properties of the operation - Properties interface{} `json:"properties,omitempty"` -} - -// OperationInfo information about an operation -type OperationInfo struct { - // Provider - Name of the provider - Provider *string `json:"provider,omitempty"` - // Resource - Name of the resource type - Resource *string `json:"resource,omitempty"` - // Operation - Name of the operation - Operation *string `json:"operation,omitempty"` - // Description - Description of the operation - Description *string `json:"description,omitempty"` -} - -// OperationsListResult result of the List Operations operation -type OperationsListResult struct { - autorest.Response `json:"-"` - // Value - A collection of operations - Value *[]Operation `json:"value,omitempty"` -} - -// Resource definition of a Resource -type Resource struct { - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// RetryPolicy information about the retry policy for an event subscription -type RetryPolicy struct { - // MaxDeliveryAttempts - Maximum number of delivery retry attempts for events. - MaxDeliveryAttempts *int32 `json:"maxDeliveryAttempts,omitempty"` - // EventTimeToLiveInMinutes - Time To Live (in minutes) for events. - EventTimeToLiveInMinutes *int32 `json:"eventTimeToLiveInMinutes,omitempty"` -} - -// StorageBlobDeadLetterDestination information about the storage blob based dead letter destination. -type StorageBlobDeadLetterDestination struct { - // StorageBlobDeadLetterDestinationProperties - The properties of the Storage Blob based deadletter destination - *StorageBlobDeadLetterDestinationProperties `json:"properties,omitempty"` - // EndpointType - Possible values include: 'EndpointTypeDeadLetterDestination', 'EndpointTypeStorageBlob' - EndpointType EndpointTypeBasicDeadLetterDestination `json:"endpointType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StorageBlobDeadLetterDestination. -func (sbdld StorageBlobDeadLetterDestination) MarshalJSON() ([]byte, error) { - sbdld.EndpointType = EndpointTypeStorageBlob - objectMap := make(map[string]interface{}) - if sbdld.StorageBlobDeadLetterDestinationProperties != nil { - objectMap["properties"] = sbdld.StorageBlobDeadLetterDestinationProperties - } - if sbdld.EndpointType != "" { - objectMap["endpointType"] = sbdld.EndpointType - } - return json.Marshal(objectMap) -} - -// AsStorageBlobDeadLetterDestination is the BasicDeadLetterDestination implementation for StorageBlobDeadLetterDestination. -func (sbdld StorageBlobDeadLetterDestination) AsStorageBlobDeadLetterDestination() (*StorageBlobDeadLetterDestination, bool) { - return &sbdld, true -} - -// AsDeadLetterDestination is the BasicDeadLetterDestination implementation for StorageBlobDeadLetterDestination. -func (sbdld StorageBlobDeadLetterDestination) AsDeadLetterDestination() (*DeadLetterDestination, bool) { - return nil, false -} - -// AsBasicDeadLetterDestination is the BasicDeadLetterDestination implementation for StorageBlobDeadLetterDestination. -func (sbdld StorageBlobDeadLetterDestination) AsBasicDeadLetterDestination() (BasicDeadLetterDestination, bool) { - return &sbdld, true -} - -// UnmarshalJSON is the custom unmarshaler for StorageBlobDeadLetterDestination struct. -func (sbdld *StorageBlobDeadLetterDestination) 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 storageBlobDeadLetterDestinationProperties StorageBlobDeadLetterDestinationProperties - err = json.Unmarshal(*v, &storageBlobDeadLetterDestinationProperties) - if err != nil { - return err - } - sbdld.StorageBlobDeadLetterDestinationProperties = &storageBlobDeadLetterDestinationProperties - } - case "endpointType": - if v != nil { - var endpointType EndpointTypeBasicDeadLetterDestination - err = json.Unmarshal(*v, &endpointType) - if err != nil { - return err - } - sbdld.EndpointType = endpointType - } - } - } - - return nil -} - -// StorageBlobDeadLetterDestinationProperties properties of the storage blob based dead letter destination. -type StorageBlobDeadLetterDestinationProperties struct { - // ResourceID - The Azure Resource ID of the storage account that is the destination of the deadletter events - ResourceID *string `json:"resourceId,omitempty"` - // BlobContainerName - The name of the Storage blob container that is the destination of the deadletter events - BlobContainerName *string `json:"blobContainerName,omitempty"` -} - -// StorageQueueEventSubscriptionDestination information about the storage queue destination for an event -// subscription. -type StorageQueueEventSubscriptionDestination struct { - // StorageQueueEventSubscriptionDestinationProperties - Storage Queue Properties of the event subscription destination - *StorageQueueEventSubscriptionDestinationProperties `json:"properties,omitempty"` - // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection' - EndpointType EndpointType `json:"endpointType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) MarshalJSON() ([]byte, error) { - sqesd.EndpointType = EndpointTypeStorageQueue - objectMap := make(map[string]interface{}) - if sqesd.StorageQueueEventSubscriptionDestinationProperties != nil { - objectMap["properties"] = sqesd.StorageQueueEventSubscriptionDestinationProperties - } - if sqesd.EndpointType != "" { - objectMap["endpointType"] = sqesd.EndpointType - } - return json.Marshal(objectMap) -} - -// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { - return nil, false -} - -// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { - return &sqesd, true -} - -// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { - return nil, false -} - -// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. -func (sqesd StorageQueueEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { - return &sqesd, true -} - -// UnmarshalJSON is the custom unmarshaler for StorageQueueEventSubscriptionDestination struct. -func (sqesd *StorageQueueEventSubscriptionDestination) 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 storageQueueEventSubscriptionDestinationProperties StorageQueueEventSubscriptionDestinationProperties - err = json.Unmarshal(*v, &storageQueueEventSubscriptionDestinationProperties) - if err != nil { - return err - } - sqesd.StorageQueueEventSubscriptionDestinationProperties = &storageQueueEventSubscriptionDestinationProperties - } - case "endpointType": - if v != nil { - var endpointType EndpointType - err = json.Unmarshal(*v, &endpointType) - if err != nil { - return err - } - sqesd.EndpointType = endpointType - } - } - } - - return nil -} - -// StorageQueueEventSubscriptionDestinationProperties the properties for a storage queue destination. -type StorageQueueEventSubscriptionDestinationProperties struct { - // ResourceID - The Azure Resource ID of the storage account that contains the queue that is the destination of an event subscription. - ResourceID *string `json:"resourceId,omitempty"` - // QueueName - The name of the Storage queue under a storage account that is the destination of an event subscription. - QueueName *string `json:"queueName,omitempty"` -} - -// StringBeginsWithAdvancedFilter stringBeginsWith Filter -type StringBeginsWithAdvancedFilter struct { - // Values - The set of filter values - Values *[]string `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) MarshalJSON() ([]byte, error) { - sbwaf.OperatorType = OperatorTypeStringBeginsWith - objectMap := make(map[string]interface{}) - if sbwaf.Values != nil { - objectMap["values"] = sbwaf.Values - } - if sbwaf.Key != nil { - objectMap["key"] = sbwaf.Key - } - if sbwaf.OperatorType != "" { - objectMap["operatorType"] = sbwaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return &sbwaf, true -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. -func (sbwaf StringBeginsWithAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &sbwaf, true -} - -// StringContainsAdvancedFilter stringContains Filter -type StringContainsAdvancedFilter struct { - // Values - The set of filter values - Values *[]string `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) MarshalJSON() ([]byte, error) { - scaf.OperatorType = OperatorTypeStringContains - objectMap := make(map[string]interface{}) - if scaf.Values != nil { - objectMap["values"] = scaf.Values - } - if scaf.Key != nil { - objectMap["key"] = scaf.Key - } - if scaf.OperatorType != "" { - objectMap["operatorType"] = scaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return &scaf, true -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. -func (scaf StringContainsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &scaf, true -} - -// StringEndsWithAdvancedFilter stringEndsWith Filter -type StringEndsWithAdvancedFilter struct { - // Values - The set of filter values - Values *[]string `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) MarshalJSON() ([]byte, error) { - sewaf.OperatorType = OperatorTypeStringEndsWith - objectMap := make(map[string]interface{}) - if sewaf.Values != nil { - objectMap["values"] = sewaf.Values - } - if sewaf.Key != nil { - objectMap["key"] = sewaf.Key - } - if sewaf.OperatorType != "" { - objectMap["operatorType"] = sewaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return &sewaf, true -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. -func (sewaf StringEndsWithAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &sewaf, true -} - -// StringInAdvancedFilter stringIn Filter -type StringInAdvancedFilter struct { - // Values - The set of filter values - Values *[]string `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) MarshalJSON() ([]byte, error) { - siaf.OperatorType = OperatorTypeStringIn - objectMap := make(map[string]interface{}) - if siaf.Values != nil { - objectMap["values"] = siaf.Values - } - if siaf.Key != nil { - objectMap["key"] = siaf.Key - } - if siaf.OperatorType != "" { - objectMap["operatorType"] = siaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return &siaf, true -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return nil, false -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. -func (siaf StringInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &siaf, true -} - -// StringNotInAdvancedFilter stringNotIn Filter -type StringNotInAdvancedFilter struct { - // Values - The set of filter values - Values *[]string `json:"values,omitempty"` - // Key - The filter key. Represents an event property with up to two levels of nesting. - Key *string `json:"key,omitempty"` - // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' - OperatorType OperatorType `json:"operatorType,omitempty"` -} - -// MarshalJSON is the custom marshaler for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) MarshalJSON() ([]byte, error) { - sniaf.OperatorType = OperatorTypeStringNotIn - objectMap := make(map[string]interface{}) - if sniaf.Values != nil { - objectMap["values"] = sniaf.Values - } - if sniaf.Key != nil { - objectMap["key"] = sniaf.Key - } - if sniaf.OperatorType != "" { - objectMap["operatorType"] = sniaf.OperatorType - } - return json.Marshal(objectMap) -} - -// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { - return nil, false -} - -// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { - return nil, false -} - -// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { - return nil, false -} - -// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { - return &sniaf, true -} - -// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { - return nil, false -} - -// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { - return nil, false -} - -// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { - return nil, false -} - -// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. -func (sniaf StringNotInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { - return &sniaf, true -} - -// Topic eventGrid Topic -type Topic struct { - autorest.Response `json:"-"` - // TopicProperties - Properties of the topic - *TopicProperties `json:"properties,omitempty"` - // Location - Location of the resource - Location *string `json:"location,omitempty"` - // Tags - Tags of the resource - Tags map[string]*string `json:"tags"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for Topic. -func (t Topic) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if t.TopicProperties != nil { - objectMap["properties"] = t.TopicProperties - } - if t.Location != nil { - objectMap["location"] = t.Location - } - if t.Tags != nil { - objectMap["tags"] = t.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Topic struct. -func (t *Topic) 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 topicProperties TopicProperties - err = json.Unmarshal(*v, &topicProperties) - if err != nil { - return err - } - t.TopicProperties = &topicProperties - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - t.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - t.Tags = tags - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - t.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - t.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - t.Type = &typeVar - } - } - } - - return nil -} - -// TopicProperties properties of the Topic -type TopicProperties struct { - // ProvisioningState - READ-ONLY; Provisioning state of the topic. Possible values include: 'TopicProvisioningStateCreating', 'TopicProvisioningStateUpdating', 'TopicProvisioningStateDeleting', 'TopicProvisioningStateSucceeded', 'TopicProvisioningStateCanceled', 'TopicProvisioningStateFailed' - ProvisioningState TopicProvisioningState `json:"provisioningState,omitempty"` - // Endpoint - READ-ONLY; Endpoint for the topic. - Endpoint *string `json:"endpoint,omitempty"` - // InputSchema - This determines the format that Event Grid should expect for incoming events published to the topic. Possible values include: 'InputSchemaEventGridSchema', 'InputSchemaCustomEventSchema', 'InputSchemaCloudEventV01Schema' - InputSchema InputSchema `json:"inputSchema,omitempty"` - // InputSchemaMapping - This enables publishing using custom event schemas. An InputSchemaMapping can be specified to map various properties of a source schema to various required properties of the EventGridEvent schema. - InputSchemaMapping BasicInputSchemaMapping `json:"inputSchemaMapping,omitempty"` -} - -// UnmarshalJSON is the custom unmarshaler for TopicProperties struct. -func (tp *TopicProperties) 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 "provisioningState": - if v != nil { - var provisioningState TopicProvisioningState - err = json.Unmarshal(*v, &provisioningState) - if err != nil { - return err - } - tp.ProvisioningState = provisioningState - } - case "endpoint": - if v != nil { - var endpoint string - err = json.Unmarshal(*v, &endpoint) - if err != nil { - return err - } - tp.Endpoint = &endpoint - } - case "inputSchema": - if v != nil { - var inputSchema InputSchema - err = json.Unmarshal(*v, &inputSchema) - if err != nil { - return err - } - tp.InputSchema = inputSchema - } - case "inputSchemaMapping": - if v != nil { - inputSchemaMapping, err := unmarshalBasicInputSchemaMapping(*v) - if err != nil { - return err - } - tp.InputSchemaMapping = inputSchemaMapping - } - } - } - - return nil -} - -// TopicRegenerateKeyRequest topic regenerate share access key request -type TopicRegenerateKeyRequest struct { - // KeyName - Key name to regenerate key1 or key2 - KeyName *string `json:"keyName,omitempty"` -} - -// TopicsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running -// operation. -type TopicsCreateOrUpdateFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *TopicsCreateOrUpdateFuture) Result(client TopicsClient) (t Topic, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.TopicsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.TopicsCreateOrUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if t.Response.Response, err = future.GetResult(sender); err == nil && t.Response.Response.StatusCode != http.StatusNoContent { - t, err = client.CreateOrUpdateResponder(t.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.TopicsCreateOrUpdateFuture", "Result", t.Response.Response, "Failure responding to request") - } - } - return -} - -// TopicsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type TopicsDeleteFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *TopicsDeleteFuture) Result(client TopicsClient) (ar autorest.Response, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.TopicsDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.TopicsDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// TopicSharedAccessKeys shared access keys of the Topic -type TopicSharedAccessKeys struct { - autorest.Response `json:"-"` - // Key1 - Shared access key1 for the topic. - Key1 *string `json:"key1,omitempty"` - // Key2 - Shared access key2 for the topic. - Key2 *string `json:"key2,omitempty"` -} - -// TopicsListResult result of the List Topics operation -type TopicsListResult struct { - autorest.Response `json:"-"` - // Value - A collection of Topics - Value *[]Topic `json:"value,omitempty"` -} - -// TopicsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type TopicsUpdateFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *TopicsUpdateFuture) Result(client TopicsClient) (t Topic, err error) { - var done bool - done, err = future.DoneWithContext(context.Background(), client) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.TopicsUpdateFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("eventgrid.TopicsUpdateFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if t.Response.Response, err = future.GetResult(sender); err == nil && t.Response.Response.StatusCode != http.StatusNoContent { - t, err = client.UpdateResponder(t.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "eventgrid.TopicsUpdateFuture", "Result", t.Response.Response, "Failure responding to request") - } - } - return -} - -// TopicTypeInfo properties of a topic type info. -type TopicTypeInfo struct { - autorest.Response `json:"-"` - // TopicTypeProperties - Properties of the topic type info - *TopicTypeProperties `json:"properties,omitempty"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for TopicTypeInfo. -func (tti TopicTypeInfo) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if tti.TopicTypeProperties != nil { - objectMap["properties"] = tti.TopicTypeProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for TopicTypeInfo struct. -func (tti *TopicTypeInfo) 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 topicTypeProperties TopicTypeProperties - err = json.Unmarshal(*v, &topicTypeProperties) - if err != nil { - return err - } - tti.TopicTypeProperties = &topicTypeProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - tti.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - tti.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - tti.Type = &typeVar - } - } - } - - return nil -} - -// TopicTypeProperties properties of a topic type. -type TopicTypeProperties struct { - // Provider - Namespace of the provider of the topic type. - Provider *string `json:"provider,omitempty"` - // DisplayName - Display Name for the topic type. - DisplayName *string `json:"displayName,omitempty"` - // Description - Description of the topic type. - Description *string `json:"description,omitempty"` - // ResourceRegionType - Region type of the resource. Possible values include: 'RegionalResource', 'GlobalResource' - ResourceRegionType ResourceRegionType `json:"resourceRegionType,omitempty"` - // ProvisioningState - Provisioning state of the topic type. Possible values include: 'TopicTypeProvisioningStateCreating', 'TopicTypeProvisioningStateUpdating', 'TopicTypeProvisioningStateDeleting', 'TopicTypeProvisioningStateSucceeded', 'TopicTypeProvisioningStateCanceled', 'TopicTypeProvisioningStateFailed' - ProvisioningState TopicTypeProvisioningState `json:"provisioningState,omitempty"` - // SupportedLocations - List of locations supported by this topic type. - SupportedLocations *[]string `json:"supportedLocations,omitempty"` -} - -// TopicTypesListResult result of the List Topic Types operation -type TopicTypesListResult struct { - autorest.Response `json:"-"` - // Value - A collection of topic types - Value *[]TopicTypeInfo `json:"value,omitempty"` -} - -// TopicUpdateParameters properties of the Topic update -type TopicUpdateParameters struct { - // Tags - Tags of the resource - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for TopicUpdateParameters. -func (tup TopicUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if tup.Tags != nil { - objectMap["tags"] = tup.Tags - } - return json.Marshal(objectMap) -} - -// TrackedResource definition of a Tracked Resource -type TrackedResource struct { - // Location - Location of the resource - Location *string `json:"location,omitempty"` - // Tags - Tags of the resource - Tags map[string]*string `json:"tags"` - // ID - READ-ONLY; Fully qualified identifier of the resource - ID *string `json:"id,omitempty"` - // Name - READ-ONLY; Name of the resource - Name *string `json:"name,omitempty"` - // Type - READ-ONLY; Type of the resource - Type *string `json:"type,omitempty"` -} - -// MarshalJSON is the custom marshaler for TrackedResource. -func (tr TrackedResource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if tr.Location != nil { - objectMap["location"] = tr.Location - } - if tr.Tags != nil { - objectMap["tags"] = tr.Tags - } - return json.Marshal(objectMap) -} - -// WebHookEventSubscriptionDestination information about the webhook destination for an event subscription -type WebHookEventSubscriptionDestination struct { - // WebHookEventSubscriptionDestinationProperties - WebHook Properties of the event subscription destination - *WebHookEventSubscriptionDestinationProperties `json:"properties,omitempty"` - // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection' - EndpointType EndpointType `json:"endpointType,omitempty"` -} - -// MarshalJSON is the custom marshaler for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) MarshalJSON() ([]byte, error) { - whesd.EndpointType = EndpointTypeWebHook - objectMap := make(map[string]interface{}) - if whesd.WebHookEventSubscriptionDestinationProperties != nil { - objectMap["properties"] = whesd.WebHookEventSubscriptionDestinationProperties - } - if whesd.EndpointType != "" { - objectMap["endpointType"] = whesd.EndpointType - } - return json.Marshal(objectMap) -} - -// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { - return &whesd, true -} - -// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { - return nil, false -} - -// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { - return nil, false -} - -// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { - return nil, false -} - -// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { - return nil, false -} - -// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. -func (whesd WebHookEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { - return &whesd, true -} - -// UnmarshalJSON is the custom unmarshaler for WebHookEventSubscriptionDestination struct. -func (whesd *WebHookEventSubscriptionDestination) 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 webHookEventSubscriptionDestinationProperties WebHookEventSubscriptionDestinationProperties - err = json.Unmarshal(*v, &webHookEventSubscriptionDestinationProperties) - if err != nil { - return err - } - whesd.WebHookEventSubscriptionDestinationProperties = &webHookEventSubscriptionDestinationProperties - } - case "endpointType": - if v != nil { - var endpointType EndpointType - err = json.Unmarshal(*v, &endpointType) - if err != nil { - return err - } - whesd.EndpointType = endpointType - } - } - } - - return nil -} - -// WebHookEventSubscriptionDestinationProperties information about the webhook destination properties for -// an event subscription. -type WebHookEventSubscriptionDestinationProperties struct { - // EndpointURL - The URL that represents the endpoint of the destination of an event subscription. - EndpointURL *string `json:"endpointUrl,omitempty"` - // EndpointBaseURL - READ-ONLY; The base URL that represents the endpoint of the destination of an event subscription. - EndpointBaseURL *string `json:"endpointBaseUrl,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/client.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/client.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/client.go index 05818ba810a57..08ddae2a2e790 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/client.go @@ -1,4 +1,4 @@ -// Package eventgrid implements the Azure ARM Eventgrid service API version 2018-09-15-preview. +// Package eventgrid implements the Azure ARM Eventgrid service API version 2020-04-01-preview. // // Azure EventGrid Management Client package eventgrid diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domains.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domains.go similarity index 78% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domains.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domains.go index 1dbd761b7bfac..23426c11b0113 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/domains.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domains.go @@ -42,11 +42,11 @@ func NewDomainsClientWithBaseURI(baseURI string, subscriptionID string) DomainsC return DomainsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// CreateOrUpdate asynchronously creates a new domain with the specified parameters. +// CreateOrUpdate asynchronously creates or updates a new domain with the specified parameters. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain -// domainInfo - domain information +// domainName - name of the domain. +// domainInfo - domain information. func (client DomainsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, domainName string, domainInfo Domain) (result DomainsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.CreateOrUpdate") @@ -81,7 +81,7 @@ func (client DomainsClient) CreateOrUpdatePreparer(ctx context.Context, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -121,10 +121,10 @@ func (client DomainsClient) CreateOrUpdateResponder(resp *http.Response) (result return } -// Delete delete existing domain +// Delete delete existing domain. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain +// domainName - name of the domain. func (client DomainsClient) Delete(ctx context.Context, resourceGroupName string, domainName string) (result DomainsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.Delete") @@ -159,7 +159,7 @@ func (client DomainsClient) DeletePreparer(ctx context.Context, resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -196,10 +196,10 @@ func (client DomainsClient) DeleteResponder(resp *http.Response) (result autores return } -// Get get properties of a domain +// Get get properties of a domain. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain +// domainName - name of the domain. func (client DomainsClient) Get(ctx context.Context, resourceGroupName string, domainName string) (result Domain, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.Get") @@ -240,7 +240,7 @@ func (client DomainsClient) GetPreparer(ctx context.Context, resourceGroupName s "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -272,21 +272,30 @@ func (client DomainsClient) GetResponder(resp *http.Response) (result Domain, er return } -// ListByResourceGroup list all the domains under a resource group +// ListByResourceGroup list all the domains under a resource group. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -func (client DomainsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result DomainsListResult, err error) { +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client DomainsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result DomainsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.ListByResourceGroup") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.dlr.Response.Response != nil { + sc = result.dlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "ListByResourceGroup", nil, "Failure preparing request") return @@ -294,12 +303,12 @@ func (client DomainsClient) ListByResourceGroup(ctx context.Context, resourceGro resp, err := client.ListByResourceGroupSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.dlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "ListByResourceGroup", resp, "Failure sending request") return } - result, err = client.ListByResourceGroupResponder(resp) + result.dlr, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "ListByResourceGroup", resp, "Failure responding to request") } @@ -308,16 +317,22 @@ func (client DomainsClient) ListByResourceGroup(ctx context.Context, resourceGro } // ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client DomainsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { +func (client DomainsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -346,19 +361,66 @@ func (client DomainsClient) ListByResourceGroupResponder(resp *http.Response) (r return } -// ListBySubscription list all the domains under an Azure subscription -func (client DomainsClient) ListBySubscription(ctx context.Context) (result DomainsListResult, err error) { +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client DomainsClient) listByResourceGroupNextResults(ctx context.Context, lastResults DomainsListResult) (result DomainsListResult, err error) { + req, err := lastResults.domainsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "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, "eventgrid.DomainsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client DomainsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result DomainsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.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, filter, top) + return +} + +// ListBySubscription list all the domains under an Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client DomainsClient) ListBySubscription(ctx context.Context, filter string, top *int32) (result DomainsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.ListBySubscription") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.dlr.Response.Response != nil { + sc = result.dlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListBySubscriptionPreparer(ctx) + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "ListBySubscription", nil, "Failure preparing request") return @@ -366,12 +428,12 @@ func (client DomainsClient) ListBySubscription(ctx context.Context) (result Doma resp, err := client.ListBySubscriptionSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.dlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "ListBySubscription", resp, "Failure sending request") return } - result, err = client.ListBySubscriptionResponder(resp) + result.dlr, err = client.ListBySubscriptionResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "ListBySubscription", resp, "Failure responding to request") } @@ -380,15 +442,21 @@ func (client DomainsClient) ListBySubscription(ctx context.Context) (result Doma } // ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client DomainsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { +func (client DomainsClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -417,10 +485,47 @@ func (client DomainsClient) ListBySubscriptionResponder(resp *http.Response) (re return } -// ListSharedAccessKeys list the two keys used to publish to a domain +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client DomainsClient) listBySubscriptionNextResults(ctx context.Context, lastResults DomainsListResult) (result DomainsListResult, err error) { + req, err := lastResults.domainsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client DomainsClient) ListBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result DomainsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.ListBySubscription") + 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.ListBySubscription(ctx, filter, top) + return +} + +// ListSharedAccessKeys list the two keys used to publish to a domain. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain +// domainName - name of the domain. func (client DomainsClient) ListSharedAccessKeys(ctx context.Context, resourceGroupName string, domainName string) (result DomainSharedAccessKeys, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.ListSharedAccessKeys") @@ -461,7 +566,7 @@ func (client DomainsClient) ListSharedAccessKeysPreparer(ctx context.Context, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -493,11 +598,11 @@ func (client DomainsClient) ListSharedAccessKeysResponder(resp *http.Response) ( return } -// RegenerateKey regenerate a shared access key for a domain +// RegenerateKey regenerate a shared access key for a domain. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain -// regenerateKeyRequest - request body to regenerate key +// domainName - name of the domain. +// regenerateKeyRequest - request body to regenerate key. func (client DomainsClient) RegenerateKey(ctx context.Context, resourceGroupName string, domainName string, regenerateKeyRequest DomainRegenerateKeyRequest) (result DomainSharedAccessKeys, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.RegenerateKey") @@ -544,7 +649,7 @@ func (client DomainsClient) RegenerateKeyPreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -581,8 +686,8 @@ func (client DomainsClient) RegenerateKeyResponder(resp *http.Response) (result // Update asynchronously updates a domain with the specified parameters. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the domain -// domainUpdateParameters - domain update information +// domainName - name of the domain. +// domainUpdateParameters - domain update information. func (client DomainsClient) Update(ctx context.Context, resourceGroupName string, domainName string, domainUpdateParameters DomainUpdateParameters) (result DomainsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DomainsClient.Update") @@ -617,7 +722,7 @@ func (client DomainsClient) UpdatePreparer(ctx context.Context, resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domaintopics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domaintopics.go new file mode 100644 index 0000000000000..c077e5d534ba3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/domaintopics.go @@ -0,0 +1,403 @@ +package eventgrid + +// 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" +) + +// DomainTopicsClient is the azure EventGrid Management Client +type DomainTopicsClient struct { + BaseClient +} + +// NewDomainTopicsClient creates an instance of the DomainTopicsClient client. +func NewDomainTopicsClient(subscriptionID string) DomainTopicsClient { + return NewDomainTopicsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDomainTopicsClientWithBaseURI creates an instance of the DomainTopicsClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewDomainTopicsClientWithBaseURI(baseURI string, subscriptionID string) DomainTopicsClient { + return DomainTopicsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate asynchronously creates or updates a new domain topic with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// domainName - name of the domain. +// domainTopicName - name of the domain topic. +func (client DomainTopicsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, domainName string, domainTopicName string) (result DomainTopicsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, domainName, domainTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DomainTopicsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, domainName string, domainTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "domainTopicName": autorest.Encode("path", domainTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/domains/{domainName}/topics/{domainTopicName}", pathParameters), + 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 DomainTopicsClient) CreateOrUpdateSender(req *http.Request) (future DomainTopicsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 DomainTopicsClient) CreateOrUpdateResponder(resp *http.Response) (result DomainTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete existing domain topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// domainName - name of the domain. +// domainTopicName - name of the domain topic. +func (client DomainTopicsClient) Delete(ctx context.Context, resourceGroupName string, domainName string, domainTopicName string) (result DomainTopicsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, domainName, domainTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DomainTopicsClient) DeletePreparer(ctx context.Context, resourceGroupName string, domainName string, domainTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "domainTopicName": autorest.Encode("path", domainTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/domains/{domainName}/topics/{domainTopicName}", 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 DomainTopicsClient) DeleteSender(req *http.Request) (future DomainTopicsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 DomainTopicsClient) 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 get properties of a domain topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// domainName - name of the domain. +// domainTopicName - name of the topic. +func (client DomainTopicsClient) Get(ctx context.Context, resourceGroupName string, domainName string, domainTopicName string) (result DomainTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, domainName, domainTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DomainTopicsClient) GetPreparer(ctx context.Context, resourceGroupName string, domainName string, domainTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "domainTopicName": autorest.Encode("path", domainTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/domains/{domainName}/topics/{domainTopicName}", 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 DomainTopicsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DomainTopicsClient) GetResponder(resp *http.Response) (result DomainTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByDomain list all the topics in a domain. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// domainName - domain name. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client DomainTopicsClient) ListByDomain(ctx context.Context, resourceGroupName string, domainName string, filter string, top *int32) (result DomainTopicsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.ListByDomain") + defer func() { + sc := -1 + if result.dtlr.Response.Response != nil { + sc = result.dtlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByDomainNextResults + req, err := client.ListByDomainPreparer(ctx, resourceGroupName, domainName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "ListByDomain", nil, "Failure preparing request") + return + } + + resp, err := client.ListByDomainSender(req) + if err != nil { + result.dtlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "ListByDomain", resp, "Failure sending request") + return + } + + result.dtlr, err = client.ListByDomainResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "ListByDomain", resp, "Failure responding to request") + } + + return +} + +// ListByDomainPreparer prepares the ListByDomain request. +func (client DomainTopicsClient) ListByDomainPreparer(ctx context.Context, resourceGroupName string, domainName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "domainName": autorest.Encode("path", domainName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/domains/{domainName}/topics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByDomainSender sends the ListByDomain request. The method will close the +// http.Response Body if it receives an error. +func (client DomainTopicsClient) ListByDomainSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByDomainResponder handles the response to the ListByDomain request. The method always +// closes the http.Response Body. +func (client DomainTopicsClient) ListByDomainResponder(resp *http.Response) (result DomainTopicsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByDomainNextResults retrieves the next set of results, if any. +func (client DomainTopicsClient) listByDomainNextResults(ctx context.Context, lastResults DomainTopicsListResult) (result DomainTopicsListResult, err error) { + req, err := lastResults.domainTopicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "listByDomainNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByDomainSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "listByDomainNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByDomainResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsClient", "listByDomainNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByDomainComplete enumerates all values, automatically crossing page boundaries as required. +func (client DomainTopicsClient) ListByDomainComplete(ctx context.Context, resourceGroupName string, domainName string, filter string, top *int32) (result DomainTopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsClient.ListByDomain") + 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.ListByDomain(ctx, resourceGroupName, domainName, filter, top) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventchannels.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventchannels.go new file mode 100644 index 0000000000000..a177d56b9af73 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventchannels.go @@ -0,0 +1,406 @@ +package eventgrid + +// 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" +) + +// EventChannelsClient is the azure EventGrid Management Client +type EventChannelsClient struct { + BaseClient +} + +// NewEventChannelsClient creates an instance of the EventChannelsClient client. +func NewEventChannelsClient(subscriptionID string) EventChannelsClient { + return NewEventChannelsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewEventChannelsClientWithBaseURI creates an instance of the EventChannelsClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewEventChannelsClientWithBaseURI(baseURI string, subscriptionID string) EventChannelsClient { + return EventChannelsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate asynchronously creates a new event channel with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// eventChannelName - name of the event channel. +// eventChannelInfo - eventChannel information. +func (client EventChannelsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, partnerNamespaceName string, eventChannelName string, eventChannelInfo EventChannel) (result EventChannel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, partnerNamespaceName, eventChannelName, eventChannelInfo) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client EventChannelsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, eventChannelName string, eventChannelInfo EventChannel) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventChannelName": autorest.Encode("path", eventChannelName), + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/partnerNamespaces/{partnerNamespaceName}/eventChannels/{eventChannelName}", pathParameters), + autorest.WithJSON(eventChannelInfo), + 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 EventChannelsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client EventChannelsClient) CreateOrUpdateResponder(resp *http.Response) (result EventChannel, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete existing event channel. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// eventChannelName - name of the event channel. +func (client EventChannelsClient) Delete(ctx context.Context, resourceGroupName string, partnerNamespaceName string, eventChannelName string) (result EventChannelsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, partnerNamespaceName, eventChannelName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client EventChannelsClient) DeletePreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, eventChannelName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventChannelName": autorest.Encode("path", eventChannelName), + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}/eventChannels/{eventChannelName}", 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 EventChannelsClient) DeleteSender(req *http.Request) (future EventChannelsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 EventChannelsClient) 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 get properties of an event channel. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// eventChannelName - name of the event channel. +func (client EventChannelsClient) Get(ctx context.Context, resourceGroupName string, partnerNamespaceName string, eventChannelName string) (result EventChannel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, partnerNamespaceName, eventChannelName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client EventChannelsClient) GetPreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, eventChannelName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventChannelName": autorest.Encode("path", eventChannelName), + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}/eventChannels/{eventChannelName}", 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 EventChannelsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client EventChannelsClient) GetResponder(resp *http.Response) (result EventChannel, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByPartnerNamespace list all the event channels in a partner namespace. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventChannelsClient) ListByPartnerNamespace(ctx context.Context, resourceGroupName string, partnerNamespaceName string, filter string, top *int32) (result EventChannelsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsClient.ListByPartnerNamespace") + defer func() { + sc := -1 + if result.eclr.Response.Response != nil { + sc = result.eclr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByPartnerNamespaceNextResults + req, err := client.ListByPartnerNamespacePreparer(ctx, resourceGroupName, partnerNamespaceName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "ListByPartnerNamespace", nil, "Failure preparing request") + return + } + + resp, err := client.ListByPartnerNamespaceSender(req) + if err != nil { + result.eclr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "ListByPartnerNamespace", resp, "Failure sending request") + return + } + + result.eclr, err = client.ListByPartnerNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "ListByPartnerNamespace", resp, "Failure responding to request") + } + + return +} + +// ListByPartnerNamespacePreparer prepares the ListByPartnerNamespace request. +func (client EventChannelsClient) ListByPartnerNamespacePreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}/eventChannels", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByPartnerNamespaceSender sends the ListByPartnerNamespace request. The method will close the +// http.Response Body if it receives an error. +func (client EventChannelsClient) ListByPartnerNamespaceSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByPartnerNamespaceResponder handles the response to the ListByPartnerNamespace request. The method always +// closes the http.Response Body. +func (client EventChannelsClient) ListByPartnerNamespaceResponder(resp *http.Response) (result EventChannelsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByPartnerNamespaceNextResults retrieves the next set of results, if any. +func (client EventChannelsClient) listByPartnerNamespaceNextResults(ctx context.Context, lastResults EventChannelsListResult) (result EventChannelsListResult, err error) { + req, err := lastResults.eventChannelsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "listByPartnerNamespaceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByPartnerNamespaceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "listByPartnerNamespaceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByPartnerNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsClient", "listByPartnerNamespaceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByPartnerNamespaceComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventChannelsClient) ListByPartnerNamespaceComplete(ctx context.Context, resourceGroupName string, partnerNamespaceName string, filter string, top *int32) (result EventChannelsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsClient.ListByPartnerNamespace") + 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.ListByPartnerNamespace(ctx, resourceGroupName, partnerNamespaceName, filter, top) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/eventsubscriptions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventsubscriptions.go similarity index 59% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/eventsubscriptions.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventsubscriptions.go index a3ade990e8c73..a5330daea2179 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/eventsubscriptions.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/eventsubscriptions.go @@ -55,7 +55,7 @@ func NewEventSubscriptionsClientWithBaseURI(baseURI string, subscriptionID strin // for an EventGrid topic. // eventSubscriptionName - name of the event subscription. Event subscription names must be between 3 and 64 // characters in length and should use alphanumeric letters only. -// eventSubscriptionInfo - event subscription properties containing the destination and filter information +// eventSubscriptionInfo - event subscription properties containing the destination and filter information. func (client EventSubscriptionsClient) CreateOrUpdate(ctx context.Context, scope string, eventSubscriptionName string, eventSubscriptionInfo EventSubscription) (result EventSubscriptionsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.CreateOrUpdate") @@ -89,7 +89,7 @@ func (client EventSubscriptionsClient) CreateOrUpdatePreparer(ctx context.Contex "scope": scope, } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -129,7 +129,7 @@ func (client EventSubscriptionsClient) CreateOrUpdateResponder(resp *http.Respon return } -// Delete delete an existing event subscription +// Delete delete an existing event subscription. // Parameters: // scope - the scope of the event subscription. The scope can be a subscription, or a resource group, or a top // level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use @@ -139,7 +139,7 @@ func (client EventSubscriptionsClient) CreateOrUpdateResponder(resp *http.Respon // for a resource, and // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' // for an EventGrid topic. -// eventSubscriptionName - name of the event subscription +// eventSubscriptionName - name of the event subscription. func (client EventSubscriptionsClient) Delete(ctx context.Context, scope string, eventSubscriptionName string) (result EventSubscriptionsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.Delete") @@ -173,7 +173,7 @@ func (client EventSubscriptionsClient) DeletePreparer(ctx context.Context, scope "scope": scope, } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -210,7 +210,7 @@ func (client EventSubscriptionsClient) DeleteResponder(resp *http.Response) (res return } -// Get get properties of an event subscription +// Get get properties of an event subscription. // Parameters: // scope - the scope of the event subscription. The scope can be a subscription, or a resource group, or a top // level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use @@ -220,7 +220,7 @@ func (client EventSubscriptionsClient) DeleteResponder(resp *http.Response) (res // for a resource, and // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' // for an EventGrid topic. -// eventSubscriptionName - name of the event subscription +// eventSubscriptionName - name of the event subscription. func (client EventSubscriptionsClient) Get(ctx context.Context, scope string, eventSubscriptionName string) (result EventSubscription, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.Get") @@ -260,7 +260,7 @@ func (client EventSubscriptionsClient) GetPreparer(ctx context.Context, scope st "scope": scope, } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -292,7 +292,7 @@ func (client EventSubscriptionsClient) GetResponder(resp *http.Response) (result return } -// GetFullURL get the full endpoint URL for an event subscription +// GetFullURL get the full endpoint URL for an event subscription. // Parameters: // scope - the scope of the event subscription. The scope can be a subscription, or a resource group, or a top // level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use @@ -302,7 +302,7 @@ func (client EventSubscriptionsClient) GetResponder(resp *http.Response) (result // for a resource, and // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' // for an EventGrid topic. -// eventSubscriptionName - name of the event subscription +// eventSubscriptionName - name of the event subscription. func (client EventSubscriptionsClient) GetFullURL(ctx context.Context, scope string, eventSubscriptionName string) (result EventSubscriptionFullURL, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.GetFullURL") @@ -342,7 +342,7 @@ func (client EventSubscriptionsClient) GetFullURLPreparer(ctx context.Context, s "scope": scope, } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -374,23 +374,32 @@ func (client EventSubscriptionsClient) GetFullURLResponder(resp *http.Response) return } -// ListByDomainTopic list all event subscriptions that have been created for a specific domain topic +// ListByDomainTopic list all event subscriptions that have been created for a specific domain topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// domainName - name of the top level domain -// topicName - name of the domain topic -func (client EventSubscriptionsClient) ListByDomainTopic(ctx context.Context, resourceGroupName string, domainName string, topicName string) (result EventSubscriptionsListResult, err error) { +// domainName - name of the top level domain. +// topicName - name of the domain topic. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListByDomainTopic(ctx context.Context, resourceGroupName string, domainName string, topicName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListByDomainTopic") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListByDomainTopicPreparer(ctx, resourceGroupName, domainName, topicName) + result.fn = client.listByDomainTopicNextResults + req, err := client.ListByDomainTopicPreparer(ctx, resourceGroupName, domainName, topicName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListByDomainTopic", nil, "Failure preparing request") return @@ -398,12 +407,12 @@ func (client EventSubscriptionsClient) ListByDomainTopic(ctx context.Context, re resp, err := client.ListByDomainTopicSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListByDomainTopic", resp, "Failure sending request") return } - result, err = client.ListByDomainTopicResponder(resp) + result.eslr, err = client.ListByDomainTopicResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListByDomainTopic", resp, "Failure responding to request") } @@ -412,7 +421,7 @@ func (client EventSubscriptionsClient) ListByDomainTopic(ctx context.Context, re } // ListByDomainTopicPreparer prepares the ListByDomainTopic request. -func (client EventSubscriptionsClient) ListByDomainTopicPreparer(ctx context.Context, resourceGroupName string, domainName string, topicName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListByDomainTopicPreparer(ctx context.Context, resourceGroupName string, domainName string, topicName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "domainName": autorest.Encode("path", domainName), "resourceGroupName": autorest.Encode("path", resourceGroupName), @@ -420,10 +429,16 @@ func (client EventSubscriptionsClient) ListByDomainTopicPreparer(ctx context.Con "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -452,24 +467,70 @@ func (client EventSubscriptionsClient) ListByDomainTopicResponder(resp *http.Res return } -// ListByResource list all event subscriptions that have been created for a specific topic +// listByDomainTopicNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listByDomainTopicNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listByDomainTopicNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByDomainTopicSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listByDomainTopicNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByDomainTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listByDomainTopicNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByDomainTopicComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListByDomainTopicComplete(ctx context.Context, resourceGroupName string, domainName string, topicName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListByDomainTopic") + 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.ListByDomainTopic(ctx, resourceGroupName, domainName, topicName, filter, top) + return +} + +// ListByResource list all event subscriptions that have been created for a specific topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// providerNamespace - namespace of the provider of the topic -// resourceTypeName - name of the resource type -// resourceName - name of the resource -func (client EventSubscriptionsClient) ListByResource(ctx context.Context, resourceGroupName string, providerNamespace string, resourceTypeName string, resourceName string) (result EventSubscriptionsListResult, err error) { +// providerNamespace - namespace of the provider of the topic. +// resourceTypeName - name of the resource type. +// resourceName - name of the resource. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListByResource(ctx context.Context, resourceGroupName string, providerNamespace string, resourceTypeName string, resourceName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListByResource") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListByResourcePreparer(ctx, resourceGroupName, providerNamespace, resourceTypeName, resourceName) + result.fn = client.listByResourceNextResults + req, err := client.ListByResourcePreparer(ctx, resourceGroupName, providerNamespace, resourceTypeName, resourceName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListByResource", nil, "Failure preparing request") return @@ -477,12 +538,12 @@ func (client EventSubscriptionsClient) ListByResource(ctx context.Context, resou resp, err := client.ListByResourceSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListByResource", resp, "Failure sending request") return } - result, err = client.ListByResourceResponder(resp) + result.eslr, err = client.ListByResourceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListByResource", resp, "Failure responding to request") } @@ -491,7 +552,7 @@ func (client EventSubscriptionsClient) ListByResource(ctx context.Context, resou } // ListByResourcePreparer prepares the ListByResource request. -func (client EventSubscriptionsClient) ListByResourcePreparer(ctx context.Context, resourceGroupName string, providerNamespace string, resourceTypeName string, resourceName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListByResourcePreparer(ctx context.Context, resourceGroupName string, providerNamespace string, resourceTypeName string, resourceName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "providerNamespace": autorest.Encode("path", providerNamespace), "resourceGroupName": autorest.Encode("path", resourceGroupName), @@ -500,10 +561,16 @@ func (client EventSubscriptionsClient) ListByResourcePreparer(ctx context.Contex "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -532,21 +599,68 @@ func (client EventSubscriptionsClient) ListByResourceResponder(resp *http.Respon return } -// ListGlobalByResourceGroup list all global event subscriptions under a specific Azure subscription and resource group +// listByResourceNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listByResourceNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listByResourceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listByResourceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listByResourceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListByResourceComplete(ctx context.Context, resourceGroupName string, providerNamespace string, resourceTypeName string, resourceName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListByResource") + 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.ListByResource(ctx, resourceGroupName, providerNamespace, resourceTypeName, resourceName, filter, top) + return +} + +// ListGlobalByResourceGroup list all global event subscriptions under a specific Azure subscription and resource +// group. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -func (client EventSubscriptionsClient) ListGlobalByResourceGroup(ctx context.Context, resourceGroupName string) (result EventSubscriptionsListResult, err error) { +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListGlobalByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalByResourceGroup") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListGlobalByResourceGroupPreparer(ctx, resourceGroupName) + result.fn = client.listGlobalByResourceGroupNextResults + req, err := client.ListGlobalByResourceGroupPreparer(ctx, resourceGroupName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalByResourceGroup", nil, "Failure preparing request") return @@ -554,12 +668,12 @@ func (client EventSubscriptionsClient) ListGlobalByResourceGroup(ctx context.Con resp, err := client.ListGlobalByResourceGroupSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalByResourceGroup", resp, "Failure sending request") return } - result, err = client.ListGlobalByResourceGroupResponder(resp) + result.eslr, err = client.ListGlobalByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalByResourceGroup", resp, "Failure responding to request") } @@ -568,16 +682,22 @@ func (client EventSubscriptionsClient) ListGlobalByResourceGroup(ctx context.Con } // ListGlobalByResourceGroupPreparer prepares the ListGlobalByResourceGroup request. -func (client EventSubscriptionsClient) ListGlobalByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListGlobalByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -606,23 +726,69 @@ func (client EventSubscriptionsClient) ListGlobalByResourceGroupResponder(resp * return } +// listGlobalByResourceGroupNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listGlobalByResourceGroupNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListGlobalByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListGlobalByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListGlobalByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListGlobalByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalByResourceGroup") + 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.ListGlobalByResourceGroup(ctx, resourceGroupName, filter, top) + return +} + // ListGlobalByResourceGroupForTopicType list all global event subscriptions under a resource group for a specific // topic type. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicTypeName - name of the topic type -func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicType(ctx context.Context, resourceGroupName string, topicTypeName string) (result EventSubscriptionsListResult, err error) { +// topicTypeName - name of the topic type. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicType(ctx context.Context, resourceGroupName string, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalByResourceGroupForTopicType") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListGlobalByResourceGroupForTopicTypePreparer(ctx, resourceGroupName, topicTypeName) + result.fn = client.listGlobalByResourceGroupForTopicTypeNextResults + req, err := client.ListGlobalByResourceGroupForTopicTypePreparer(ctx, resourceGroupName, topicTypeName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalByResourceGroupForTopicType", nil, "Failure preparing request") return @@ -630,12 +796,12 @@ func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicType(ctx resp, err := client.ListGlobalByResourceGroupForTopicTypeSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalByResourceGroupForTopicType", resp, "Failure sending request") return } - result, err = client.ListGlobalByResourceGroupForTopicTypeResponder(resp) + result.eslr, err = client.ListGlobalByResourceGroupForTopicTypeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalByResourceGroupForTopicType", resp, "Failure responding to request") } @@ -644,17 +810,23 @@ func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicType(ctx } // ListGlobalByResourceGroupForTopicTypePreparer prepares the ListGlobalByResourceGroupForTopicType request. -func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicTypePreparer(ctx context.Context, resourceGroupName string, topicTypeName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicTypePreparer(ctx context.Context, resourceGroupName string, topicTypeName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "topicTypeName": autorest.Encode("path", topicTypeName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -683,19 +855,66 @@ func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicTypeResp return } -// ListGlobalBySubscription list all aggregated global event subscriptions under a specific Azure subscription -func (client EventSubscriptionsClient) ListGlobalBySubscription(ctx context.Context) (result EventSubscriptionsListResult, err error) { +// listGlobalByResourceGroupForTopicTypeNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listGlobalByResourceGroupForTopicTypeNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalByResourceGroupForTopicTypeNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListGlobalByResourceGroupForTopicTypeSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalByResourceGroupForTopicTypeNextResults", resp, "Failure sending next results request") + } + result, err = client.ListGlobalByResourceGroupForTopicTypeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalByResourceGroupForTopicTypeNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListGlobalByResourceGroupForTopicTypeComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListGlobalByResourceGroupForTopicTypeComplete(ctx context.Context, resourceGroupName string, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalByResourceGroupForTopicType") + 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.ListGlobalByResourceGroupForTopicType(ctx, resourceGroupName, topicTypeName, filter, top) + return +} + +// ListGlobalBySubscription list all aggregated global event subscriptions under a specific Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListGlobalBySubscription(ctx context.Context, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalBySubscription") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListGlobalBySubscriptionPreparer(ctx) + result.fn = client.listGlobalBySubscriptionNextResults + req, err := client.ListGlobalBySubscriptionPreparer(ctx, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalBySubscription", nil, "Failure preparing request") return @@ -703,12 +922,12 @@ func (client EventSubscriptionsClient) ListGlobalBySubscription(ctx context.Cont resp, err := client.ListGlobalBySubscriptionSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalBySubscription", resp, "Failure sending request") return } - result, err = client.ListGlobalBySubscriptionResponder(resp) + result.eslr, err = client.ListGlobalBySubscriptionResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalBySubscription", resp, "Failure responding to request") } @@ -717,15 +936,21 @@ func (client EventSubscriptionsClient) ListGlobalBySubscription(ctx context.Cont } // ListGlobalBySubscriptionPreparer prepares the ListGlobalBySubscription request. -func (client EventSubscriptionsClient) ListGlobalBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { +func (client EventSubscriptionsClient) ListGlobalBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -754,22 +979,68 @@ func (client EventSubscriptionsClient) ListGlobalBySubscriptionResponder(resp *h return } +// listGlobalBySubscriptionNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listGlobalBySubscriptionNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListGlobalBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListGlobalBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListGlobalBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListGlobalBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalBySubscription") + 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.ListGlobalBySubscription(ctx, filter, top) + return +} + // ListGlobalBySubscriptionForTopicType list all global event subscriptions under an Azure subscription for a topic // type. // Parameters: -// topicTypeName - name of the topic type -func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicType(ctx context.Context, topicTypeName string) (result EventSubscriptionsListResult, err error) { +// topicTypeName - name of the topic type. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicType(ctx context.Context, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalBySubscriptionForTopicType") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListGlobalBySubscriptionForTopicTypePreparer(ctx, topicTypeName) + result.fn = client.listGlobalBySubscriptionForTopicTypeNextResults + req, err := client.ListGlobalBySubscriptionForTopicTypePreparer(ctx, topicTypeName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalBySubscriptionForTopicType", nil, "Failure preparing request") return @@ -777,12 +1048,12 @@ func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicType(ctx resp, err := client.ListGlobalBySubscriptionForTopicTypeSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalBySubscriptionForTopicType", resp, "Failure sending request") return } - result, err = client.ListGlobalBySubscriptionForTopicTypeResponder(resp) + result.eslr, err = client.ListGlobalBySubscriptionForTopicTypeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListGlobalBySubscriptionForTopicType", resp, "Failure responding to request") } @@ -791,16 +1062,22 @@ func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicType(ctx } // ListGlobalBySubscriptionForTopicTypePreparer prepares the ListGlobalBySubscriptionForTopicType request. -func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicTypePreparer(ctx context.Context, topicTypeName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicTypePreparer(ctx context.Context, topicTypeName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), "topicTypeName": autorest.Encode("path", topicTypeName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -829,23 +1106,69 @@ func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicTypeRespo return } +// listGlobalBySubscriptionForTopicTypeNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listGlobalBySubscriptionForTopicTypeNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalBySubscriptionForTopicTypeNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListGlobalBySubscriptionForTopicTypeSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalBySubscriptionForTopicTypeNextResults", resp, "Failure sending next results request") + } + result, err = client.ListGlobalBySubscriptionForTopicTypeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listGlobalBySubscriptionForTopicTypeNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListGlobalBySubscriptionForTopicTypeComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListGlobalBySubscriptionForTopicTypeComplete(ctx context.Context, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListGlobalBySubscriptionForTopicType") + 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.ListGlobalBySubscriptionForTopicType(ctx, topicTypeName, filter, top) + return +} + // ListRegionalByResourceGroup list all event subscriptions from the given location under a specific Azure subscription -// and resource group +// and resource group. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// location - name of the location -func (client EventSubscriptionsClient) ListRegionalByResourceGroup(ctx context.Context, resourceGroupName string, location string) (result EventSubscriptionsListResult, err error) { +// location - name of the location. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListRegionalByResourceGroup(ctx context.Context, resourceGroupName string, location string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalByResourceGroup") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListRegionalByResourceGroupPreparer(ctx, resourceGroupName, location) + result.fn = client.listRegionalByResourceGroupNextResults + req, err := client.ListRegionalByResourceGroupPreparer(ctx, resourceGroupName, location, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalByResourceGroup", nil, "Failure preparing request") return @@ -853,12 +1176,12 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroup(ctx context.C resp, err := client.ListRegionalByResourceGroupSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalByResourceGroup", resp, "Failure sending request") return } - result, err = client.ListRegionalByResourceGroupResponder(resp) + result.eslr, err = client.ListRegionalByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalByResourceGroup", resp, "Failure responding to request") } @@ -867,17 +1190,23 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroup(ctx context.C } // ListRegionalByResourceGroupPreparer prepares the ListRegionalByResourceGroup request. -func (client EventSubscriptionsClient) ListRegionalByResourceGroupPreparer(ctx context.Context, resourceGroupName string, location string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListRegionalByResourceGroupPreparer(ctx context.Context, resourceGroupName string, location string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -906,24 +1235,70 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroupResponder(resp return } +// listRegionalByResourceGroupNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listRegionalByResourceGroupNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListRegionalByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListRegionalByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListRegionalByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListRegionalByResourceGroupComplete(ctx context.Context, resourceGroupName string, location string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalByResourceGroup") + 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.ListRegionalByResourceGroup(ctx, resourceGroupName, location, filter, top) + return +} + // ListRegionalByResourceGroupForTopicType list all event subscriptions from the given location under a specific Azure -// subscription and resource group and topic type +// subscription and resource group and topic type. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// location - name of the location -// topicTypeName - name of the topic type -func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicType(ctx context.Context, resourceGroupName string, location string, topicTypeName string) (result EventSubscriptionsListResult, err error) { +// location - name of the location. +// topicTypeName - name of the topic type. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicType(ctx context.Context, resourceGroupName string, location string, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalByResourceGroupForTopicType") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListRegionalByResourceGroupForTopicTypePreparer(ctx, resourceGroupName, location, topicTypeName) + result.fn = client.listRegionalByResourceGroupForTopicTypeNextResults + req, err := client.ListRegionalByResourceGroupForTopicTypePreparer(ctx, resourceGroupName, location, topicTypeName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalByResourceGroupForTopicType", nil, "Failure preparing request") return @@ -931,12 +1306,12 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicType(c resp, err := client.ListRegionalByResourceGroupForTopicTypeSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalByResourceGroupForTopicType", resp, "Failure sending request") return } - result, err = client.ListRegionalByResourceGroupForTopicTypeResponder(resp) + result.eslr, err = client.ListRegionalByResourceGroupForTopicTypeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalByResourceGroupForTopicType", resp, "Failure responding to request") } @@ -945,7 +1320,7 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicType(c } // ListRegionalByResourceGroupForTopicTypePreparer prepares the ListRegionalByResourceGroupForTopicType request. -func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicTypePreparer(ctx context.Context, resourceGroupName string, location string, topicTypeName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicTypePreparer(ctx context.Context, resourceGroupName string, location string, topicTypeName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "resourceGroupName": autorest.Encode("path", resourceGroupName), @@ -953,10 +1328,16 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicTypePr "topicTypeName": autorest.Encode("path", topicTypeName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -985,21 +1366,67 @@ func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicTypeRe return } -// ListRegionalBySubscription list all event subscriptions from the given location under a specific Azure subscription +// listRegionalByResourceGroupForTopicTypeNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listRegionalByResourceGroupForTopicTypeNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalByResourceGroupForTopicTypeNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListRegionalByResourceGroupForTopicTypeSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalByResourceGroupForTopicTypeNextResults", resp, "Failure sending next results request") + } + result, err = client.ListRegionalByResourceGroupForTopicTypeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalByResourceGroupForTopicTypeNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListRegionalByResourceGroupForTopicTypeComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListRegionalByResourceGroupForTopicTypeComplete(ctx context.Context, resourceGroupName string, location string, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalByResourceGroupForTopicType") + 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.ListRegionalByResourceGroupForTopicType(ctx, resourceGroupName, location, topicTypeName, filter, top) + return +} + +// ListRegionalBySubscription list all event subscriptions from the given location under a specific Azure subscription. // Parameters: -// location - name of the location -func (client EventSubscriptionsClient) ListRegionalBySubscription(ctx context.Context, location string) (result EventSubscriptionsListResult, err error) { +// location - name of the location. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListRegionalBySubscription(ctx context.Context, location string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalBySubscription") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListRegionalBySubscriptionPreparer(ctx, location) + result.fn = client.listRegionalBySubscriptionNextResults + req, err := client.ListRegionalBySubscriptionPreparer(ctx, location, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalBySubscription", nil, "Failure preparing request") return @@ -1007,12 +1434,12 @@ func (client EventSubscriptionsClient) ListRegionalBySubscription(ctx context.Co resp, err := client.ListRegionalBySubscriptionSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalBySubscription", resp, "Failure sending request") return } - result, err = client.ListRegionalBySubscriptionResponder(resp) + result.eslr, err = client.ListRegionalBySubscriptionResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalBySubscription", resp, "Failure responding to request") } @@ -1021,16 +1448,22 @@ func (client EventSubscriptionsClient) ListRegionalBySubscription(ctx context.Co } // ListRegionalBySubscriptionPreparer prepares the ListRegionalBySubscription request. -func (client EventSubscriptionsClient) ListRegionalBySubscriptionPreparer(ctx context.Context, location string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListRegionalBySubscriptionPreparer(ctx context.Context, location string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -1059,23 +1492,69 @@ func (client EventSubscriptionsClient) ListRegionalBySubscriptionResponder(resp return } +// listRegionalBySubscriptionNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listRegionalBySubscriptionNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListRegionalBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListRegionalBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListRegionalBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListRegionalBySubscriptionComplete(ctx context.Context, location string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalBySubscription") + 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.ListRegionalBySubscription(ctx, location, filter, top) + return +} + // ListRegionalBySubscriptionForTopicType list all event subscriptions from the given location under a specific Azure // subscription and topic type. // Parameters: -// location - name of the location -// topicTypeName - name of the topic type -func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicType(ctx context.Context, location string, topicTypeName string) (result EventSubscriptionsListResult, err error) { +// location - name of the location. +// topicTypeName - name of the topic type. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicType(ctx context.Context, location string, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalBySubscriptionForTopicType") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListRegionalBySubscriptionForTopicTypePreparer(ctx, location, topicTypeName) + result.fn = client.listRegionalBySubscriptionForTopicTypeNextResults + req, err := client.ListRegionalBySubscriptionForTopicTypePreparer(ctx, location, topicTypeName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalBySubscriptionForTopicType", nil, "Failure preparing request") return @@ -1083,12 +1562,12 @@ func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicType(ct resp, err := client.ListRegionalBySubscriptionForTopicTypeSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.eslr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalBySubscriptionForTopicType", resp, "Failure sending request") return } - result, err = client.ListRegionalBySubscriptionForTopicTypeResponder(resp) + result.eslr, err = client.ListRegionalBySubscriptionForTopicTypeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "ListRegionalBySubscriptionForTopicType", resp, "Failure responding to request") } @@ -1097,17 +1576,23 @@ func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicType(ct } // ListRegionalBySubscriptionForTopicTypePreparer prepares the ListRegionalBySubscriptionForTopicType request. -func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicTypePreparer(ctx context.Context, location string, topicTypeName string) (*http.Request, error) { +func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicTypePreparer(ctx context.Context, location string, topicTypeName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "topicTypeName": autorest.Encode("path", topicTypeName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -1136,6 +1621,43 @@ func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicTypeRes return } +// listRegionalBySubscriptionForTopicTypeNextResults retrieves the next set of results, if any. +func (client EventSubscriptionsClient) listRegionalBySubscriptionForTopicTypeNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalBySubscriptionForTopicTypeNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListRegionalBySubscriptionForTopicTypeSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalBySubscriptionForTopicTypeNextResults", resp, "Failure sending next results request") + } + result, err = client.ListRegionalBySubscriptionForTopicTypeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsClient", "listRegionalBySubscriptionForTopicTypeNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListRegionalBySubscriptionForTopicTypeComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicTypeComplete(ctx context.Context, location string, topicTypeName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.ListRegionalBySubscriptionForTopicType") + 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.ListRegionalBySubscriptionForTopicType(ctx, location, topicTypeName, filter, top) + return +} + // Update asynchronously updates an existing event subscription. // Parameters: // scope - the scope of existing event subscription. The scope can be a subscription, or a resource group, or a @@ -1146,8 +1668,8 @@ func (client EventSubscriptionsClient) ListRegionalBySubscriptionForTopicTypeRes // for a resource, and // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' // for an EventGrid topic. -// eventSubscriptionName - name of the event subscription to be updated -// eventSubscriptionUpdateParameters - updated event subscription information +// eventSubscriptionName - name of the event subscription to be updated. +// eventSubscriptionUpdateParameters - updated event subscription information. func (client EventSubscriptionsClient) Update(ctx context.Context, scope string, eventSubscriptionName string, eventSubscriptionUpdateParameters EventSubscriptionUpdateParameters) (result EventSubscriptionsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsClient.Update") @@ -1181,7 +1703,7 @@ func (client EventSubscriptionsClient) UpdatePreparer(ctx context.Context, scope "scope": scope, } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/extensiontopics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/extensiontopics.go new file mode 100644 index 0000000000000..88fa73560d054 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/extensiontopics.go @@ -0,0 +1,120 @@ +package eventgrid + +// 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" +) + +// ExtensionTopicsClient is the azure EventGrid Management Client +type ExtensionTopicsClient struct { + BaseClient +} + +// NewExtensionTopicsClient creates an instance of the ExtensionTopicsClient client. +func NewExtensionTopicsClient(subscriptionID string) ExtensionTopicsClient { + return NewExtensionTopicsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewExtensionTopicsClientWithBaseURI creates an instance of the ExtensionTopicsClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewExtensionTopicsClientWithBaseURI(baseURI string, subscriptionID string) ExtensionTopicsClient { + return ExtensionTopicsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get the properties of an extension topic. +// Parameters: +// scope - the identifier of the resource to which extension topic is queried. The scope can be a subscription, +// or a resource group, or a top level resource belonging to a resource provider namespace. For example, use +// '/subscriptions/{subscriptionId}/' for a subscription, +// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for a resource group, and +// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' +// for Azure resource. +func (client ExtensionTopicsClient) Get(ctx context.Context, scope string) (result ExtensionTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ExtensionTopicsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, scope) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.ExtensionTopicsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.ExtensionTopicsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.ExtensionTopicsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ExtensionTopicsClient) GetPreparer(ctx context.Context, scope string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "scope": autorest.Encode("path", scope), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/{scope}/providers/Microsoft.EventGrid/extensionTopics/default", 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 ExtensionTopicsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ExtensionTopicsClient) GetResponder(resp *http.Response) (result ExtensionTopic, 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/models.go new file mode 100644 index 0000000000000..e4b31240b8ef5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/models.go @@ -0,0 +1,8181 @@ +package eventgrid + +// 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/date" + "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/eventgrid/mgmt/2020-04-01-preview/eventgrid" + +// DomainProvisioningState enumerates the values for domain provisioning state. +type DomainProvisioningState string + +const ( + // Canceled ... + Canceled DomainProvisioningState = "Canceled" + // Creating ... + Creating DomainProvisioningState = "Creating" + // Deleting ... + Deleting DomainProvisioningState = "Deleting" + // Failed ... + Failed DomainProvisioningState = "Failed" + // Succeeded ... + Succeeded DomainProvisioningState = "Succeeded" + // Updating ... + Updating DomainProvisioningState = "Updating" +) + +// PossibleDomainProvisioningStateValues returns an array of possible values for the DomainProvisioningState const type. +func PossibleDomainProvisioningStateValues() []DomainProvisioningState { + return []DomainProvisioningState{Canceled, Creating, Deleting, Failed, Succeeded, Updating} +} + +// DomainTopicProvisioningState enumerates the values for domain topic provisioning state. +type DomainTopicProvisioningState string + +const ( + // DomainTopicProvisioningStateCanceled ... + DomainTopicProvisioningStateCanceled DomainTopicProvisioningState = "Canceled" + // DomainTopicProvisioningStateCreating ... + DomainTopicProvisioningStateCreating DomainTopicProvisioningState = "Creating" + // DomainTopicProvisioningStateDeleting ... + DomainTopicProvisioningStateDeleting DomainTopicProvisioningState = "Deleting" + // DomainTopicProvisioningStateFailed ... + DomainTopicProvisioningStateFailed DomainTopicProvisioningState = "Failed" + // DomainTopicProvisioningStateSucceeded ... + DomainTopicProvisioningStateSucceeded DomainTopicProvisioningState = "Succeeded" + // DomainTopicProvisioningStateUpdating ... + DomainTopicProvisioningStateUpdating DomainTopicProvisioningState = "Updating" +) + +// PossibleDomainTopicProvisioningStateValues returns an array of possible values for the DomainTopicProvisioningState const type. +func PossibleDomainTopicProvisioningStateValues() []DomainTopicProvisioningState { + return []DomainTopicProvisioningState{DomainTopicProvisioningStateCanceled, DomainTopicProvisioningStateCreating, DomainTopicProvisioningStateDeleting, DomainTopicProvisioningStateFailed, DomainTopicProvisioningStateSucceeded, DomainTopicProvisioningStateUpdating} +} + +// EndpointType enumerates the values for endpoint type. +type EndpointType string + +const ( + // EndpointTypeAzureFunction ... + EndpointTypeAzureFunction EndpointType = "AzureFunction" + // EndpointTypeEventHub ... + EndpointTypeEventHub EndpointType = "EventHub" + // EndpointTypeEventSubscriptionDestination ... + EndpointTypeEventSubscriptionDestination EndpointType = "EventSubscriptionDestination" + // EndpointTypeHybridConnection ... + EndpointTypeHybridConnection EndpointType = "HybridConnection" + // EndpointTypeServiceBusQueue ... + EndpointTypeServiceBusQueue EndpointType = "ServiceBusQueue" + // EndpointTypeServiceBusTopic ... + EndpointTypeServiceBusTopic EndpointType = "ServiceBusTopic" + // EndpointTypeStorageQueue ... + EndpointTypeStorageQueue EndpointType = "StorageQueue" + // EndpointTypeWebHook ... + EndpointTypeWebHook EndpointType = "WebHook" +) + +// PossibleEndpointTypeValues returns an array of possible values for the EndpointType const type. +func PossibleEndpointTypeValues() []EndpointType { + return []EndpointType{EndpointTypeAzureFunction, EndpointTypeEventHub, EndpointTypeEventSubscriptionDestination, EndpointTypeHybridConnection, EndpointTypeServiceBusQueue, EndpointTypeServiceBusTopic, EndpointTypeStorageQueue, EndpointTypeWebHook} +} + +// EndpointTypeBasicDeadLetterDestination enumerates the values for endpoint type basic dead letter +// destination. +type EndpointTypeBasicDeadLetterDestination string + +const ( + // EndpointTypeDeadLetterDestination ... + EndpointTypeDeadLetterDestination EndpointTypeBasicDeadLetterDestination = "DeadLetterDestination" + // EndpointTypeStorageBlob ... + EndpointTypeStorageBlob EndpointTypeBasicDeadLetterDestination = "StorageBlob" +) + +// PossibleEndpointTypeBasicDeadLetterDestinationValues returns an array of possible values for the EndpointTypeBasicDeadLetterDestination const type. +func PossibleEndpointTypeBasicDeadLetterDestinationValues() []EndpointTypeBasicDeadLetterDestination { + return []EndpointTypeBasicDeadLetterDestination{EndpointTypeDeadLetterDestination, EndpointTypeStorageBlob} +} + +// EventChannelProvisioningState enumerates the values for event channel provisioning state. +type EventChannelProvisioningState string + +const ( + // EventChannelProvisioningStateCanceled ... + EventChannelProvisioningStateCanceled EventChannelProvisioningState = "Canceled" + // EventChannelProvisioningStateCreating ... + EventChannelProvisioningStateCreating EventChannelProvisioningState = "Creating" + // EventChannelProvisioningStateDeleting ... + EventChannelProvisioningStateDeleting EventChannelProvisioningState = "Deleting" + // EventChannelProvisioningStateFailed ... + EventChannelProvisioningStateFailed EventChannelProvisioningState = "Failed" + // EventChannelProvisioningStateSucceeded ... + EventChannelProvisioningStateSucceeded EventChannelProvisioningState = "Succeeded" + // EventChannelProvisioningStateUpdating ... + EventChannelProvisioningStateUpdating EventChannelProvisioningState = "Updating" +) + +// PossibleEventChannelProvisioningStateValues returns an array of possible values for the EventChannelProvisioningState const type. +func PossibleEventChannelProvisioningStateValues() []EventChannelProvisioningState { + return []EventChannelProvisioningState{EventChannelProvisioningStateCanceled, EventChannelProvisioningStateCreating, EventChannelProvisioningStateDeleting, EventChannelProvisioningStateFailed, EventChannelProvisioningStateSucceeded, EventChannelProvisioningStateUpdating} +} + +// EventDeliverySchema enumerates the values for event delivery schema. +type EventDeliverySchema string + +const ( + // CloudEventSchemaV10 ... + CloudEventSchemaV10 EventDeliverySchema = "CloudEventSchemaV1_0" + // CustomInputSchema ... + CustomInputSchema EventDeliverySchema = "CustomInputSchema" + // EventGridSchema ... + EventGridSchema EventDeliverySchema = "EventGridSchema" +) + +// PossibleEventDeliverySchemaValues returns an array of possible values for the EventDeliverySchema const type. +func PossibleEventDeliverySchemaValues() []EventDeliverySchema { + return []EventDeliverySchema{CloudEventSchemaV10, CustomInputSchema, EventGridSchema} +} + +// EventSubscriptionIdentityType enumerates the values for event subscription identity type. +type EventSubscriptionIdentityType string + +const ( + // SystemAssigned ... + SystemAssigned EventSubscriptionIdentityType = "SystemAssigned" + // UserAssigned ... + UserAssigned EventSubscriptionIdentityType = "UserAssigned" +) + +// PossibleEventSubscriptionIdentityTypeValues returns an array of possible values for the EventSubscriptionIdentityType const type. +func PossibleEventSubscriptionIdentityTypeValues() []EventSubscriptionIdentityType { + return []EventSubscriptionIdentityType{SystemAssigned, UserAssigned} +} + +// EventSubscriptionProvisioningState enumerates the values for event subscription provisioning state. +type EventSubscriptionProvisioningState string + +const ( + // EventSubscriptionProvisioningStateAwaitingManualAction ... + EventSubscriptionProvisioningStateAwaitingManualAction EventSubscriptionProvisioningState = "AwaitingManualAction" + // EventSubscriptionProvisioningStateCanceled ... + EventSubscriptionProvisioningStateCanceled EventSubscriptionProvisioningState = "Canceled" + // EventSubscriptionProvisioningStateCreating ... + EventSubscriptionProvisioningStateCreating EventSubscriptionProvisioningState = "Creating" + // EventSubscriptionProvisioningStateDeleting ... + EventSubscriptionProvisioningStateDeleting EventSubscriptionProvisioningState = "Deleting" + // EventSubscriptionProvisioningStateFailed ... + EventSubscriptionProvisioningStateFailed EventSubscriptionProvisioningState = "Failed" + // EventSubscriptionProvisioningStateSucceeded ... + EventSubscriptionProvisioningStateSucceeded EventSubscriptionProvisioningState = "Succeeded" + // EventSubscriptionProvisioningStateUpdating ... + EventSubscriptionProvisioningStateUpdating EventSubscriptionProvisioningState = "Updating" +) + +// PossibleEventSubscriptionProvisioningStateValues returns an array of possible values for the EventSubscriptionProvisioningState const type. +func PossibleEventSubscriptionProvisioningStateValues() []EventSubscriptionProvisioningState { + return []EventSubscriptionProvisioningState{EventSubscriptionProvisioningStateAwaitingManualAction, EventSubscriptionProvisioningStateCanceled, EventSubscriptionProvisioningStateCreating, EventSubscriptionProvisioningStateDeleting, EventSubscriptionProvisioningStateFailed, EventSubscriptionProvisioningStateSucceeded, EventSubscriptionProvisioningStateUpdating} +} + +// IdentityType enumerates the values for identity type. +type IdentityType string + +const ( + // IdentityTypeNone ... + IdentityTypeNone IdentityType = "None" + // IdentityTypeSystemAssigned ... + IdentityTypeSystemAssigned IdentityType = "SystemAssigned" + // IdentityTypeSystemAssignedUserAssigned ... + IdentityTypeSystemAssignedUserAssigned IdentityType = "SystemAssigned, UserAssigned" + // IdentityTypeUserAssigned ... + IdentityTypeUserAssigned IdentityType = "UserAssigned" +) + +// PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{IdentityTypeNone, IdentityTypeSystemAssigned, IdentityTypeSystemAssignedUserAssigned, IdentityTypeUserAssigned} +} + +// InputSchema enumerates the values for input schema. +type InputSchema string + +const ( + // InputSchemaCloudEventSchemaV10 ... + InputSchemaCloudEventSchemaV10 InputSchema = "CloudEventSchemaV1_0" + // InputSchemaCustomEventSchema ... + InputSchemaCustomEventSchema InputSchema = "CustomEventSchema" + // InputSchemaEventGridSchema ... + InputSchemaEventGridSchema InputSchema = "EventGridSchema" +) + +// PossibleInputSchemaValues returns an array of possible values for the InputSchema const type. +func PossibleInputSchemaValues() []InputSchema { + return []InputSchema{InputSchemaCloudEventSchemaV10, InputSchemaCustomEventSchema, InputSchemaEventGridSchema} +} + +// InputSchemaMappingType enumerates the values for input schema mapping type. +type InputSchemaMappingType string + +const ( + // InputSchemaMappingTypeInputSchemaMapping ... + InputSchemaMappingTypeInputSchemaMapping InputSchemaMappingType = "InputSchemaMapping" + // InputSchemaMappingTypeJSON ... + InputSchemaMappingTypeJSON InputSchemaMappingType = "Json" +) + +// PossibleInputSchemaMappingTypeValues returns an array of possible values for the InputSchemaMappingType const type. +func PossibleInputSchemaMappingTypeValues() []InputSchemaMappingType { + return []InputSchemaMappingType{InputSchemaMappingTypeInputSchemaMapping, InputSchemaMappingTypeJSON} +} + +// IPActionType enumerates the values for ip action type. +type IPActionType string + +const ( + // Allow ... + Allow IPActionType = "Allow" +) + +// PossibleIPActionTypeValues returns an array of possible values for the IPActionType const type. +func PossibleIPActionTypeValues() []IPActionType { + return []IPActionType{Allow} +} + +// OperatorType enumerates the values for operator type. +type OperatorType string + +const ( + // OperatorTypeAdvancedFilter ... + OperatorTypeAdvancedFilter OperatorType = "AdvancedFilter" + // OperatorTypeBoolEquals ... + OperatorTypeBoolEquals OperatorType = "BoolEquals" + // OperatorTypeNumberGreaterThan ... + OperatorTypeNumberGreaterThan OperatorType = "NumberGreaterThan" + // OperatorTypeNumberGreaterThanOrEquals ... + OperatorTypeNumberGreaterThanOrEquals OperatorType = "NumberGreaterThanOrEquals" + // OperatorTypeNumberIn ... + OperatorTypeNumberIn OperatorType = "NumberIn" + // OperatorTypeNumberLessThan ... + OperatorTypeNumberLessThan OperatorType = "NumberLessThan" + // OperatorTypeNumberLessThanOrEquals ... + OperatorTypeNumberLessThanOrEquals OperatorType = "NumberLessThanOrEquals" + // OperatorTypeNumberNotIn ... + OperatorTypeNumberNotIn OperatorType = "NumberNotIn" + // OperatorTypeStringBeginsWith ... + OperatorTypeStringBeginsWith OperatorType = "StringBeginsWith" + // OperatorTypeStringContains ... + OperatorTypeStringContains OperatorType = "StringContains" + // OperatorTypeStringEndsWith ... + OperatorTypeStringEndsWith OperatorType = "StringEndsWith" + // OperatorTypeStringIn ... + OperatorTypeStringIn OperatorType = "StringIn" + // OperatorTypeStringNotIn ... + OperatorTypeStringNotIn OperatorType = "StringNotIn" +) + +// PossibleOperatorTypeValues returns an array of possible values for the OperatorType const type. +func PossibleOperatorTypeValues() []OperatorType { + return []OperatorType{OperatorTypeAdvancedFilter, OperatorTypeBoolEquals, OperatorTypeNumberGreaterThan, OperatorTypeNumberGreaterThanOrEquals, OperatorTypeNumberIn, OperatorTypeNumberLessThan, OperatorTypeNumberLessThanOrEquals, OperatorTypeNumberNotIn, OperatorTypeStringBeginsWith, OperatorTypeStringContains, OperatorTypeStringEndsWith, OperatorTypeStringIn, OperatorTypeStringNotIn} +} + +// PartnerNamespaceProvisioningState enumerates the values for partner namespace provisioning state. +type PartnerNamespaceProvisioningState string + +const ( + // PartnerNamespaceProvisioningStateCanceled ... + PartnerNamespaceProvisioningStateCanceled PartnerNamespaceProvisioningState = "Canceled" + // PartnerNamespaceProvisioningStateCreating ... + PartnerNamespaceProvisioningStateCreating PartnerNamespaceProvisioningState = "Creating" + // PartnerNamespaceProvisioningStateDeleting ... + PartnerNamespaceProvisioningStateDeleting PartnerNamespaceProvisioningState = "Deleting" + // PartnerNamespaceProvisioningStateFailed ... + PartnerNamespaceProvisioningStateFailed PartnerNamespaceProvisioningState = "Failed" + // PartnerNamespaceProvisioningStateSucceeded ... + PartnerNamespaceProvisioningStateSucceeded PartnerNamespaceProvisioningState = "Succeeded" + // PartnerNamespaceProvisioningStateUpdating ... + PartnerNamespaceProvisioningStateUpdating PartnerNamespaceProvisioningState = "Updating" +) + +// PossiblePartnerNamespaceProvisioningStateValues returns an array of possible values for the PartnerNamespaceProvisioningState const type. +func PossiblePartnerNamespaceProvisioningStateValues() []PartnerNamespaceProvisioningState { + return []PartnerNamespaceProvisioningState{PartnerNamespaceProvisioningStateCanceled, PartnerNamespaceProvisioningStateCreating, PartnerNamespaceProvisioningStateDeleting, PartnerNamespaceProvisioningStateFailed, PartnerNamespaceProvisioningStateSucceeded, PartnerNamespaceProvisioningStateUpdating} +} + +// PartnerRegistrationProvisioningState enumerates the values for partner registration provisioning state. +type PartnerRegistrationProvisioningState string + +const ( + // PartnerRegistrationProvisioningStateCanceled ... + PartnerRegistrationProvisioningStateCanceled PartnerRegistrationProvisioningState = "Canceled" + // PartnerRegistrationProvisioningStateCreating ... + PartnerRegistrationProvisioningStateCreating PartnerRegistrationProvisioningState = "Creating" + // PartnerRegistrationProvisioningStateDeleting ... + PartnerRegistrationProvisioningStateDeleting PartnerRegistrationProvisioningState = "Deleting" + // PartnerRegistrationProvisioningStateFailed ... + PartnerRegistrationProvisioningStateFailed PartnerRegistrationProvisioningState = "Failed" + // PartnerRegistrationProvisioningStateSucceeded ... + PartnerRegistrationProvisioningStateSucceeded PartnerRegistrationProvisioningState = "Succeeded" + // PartnerRegistrationProvisioningStateUpdating ... + PartnerRegistrationProvisioningStateUpdating PartnerRegistrationProvisioningState = "Updating" +) + +// PossiblePartnerRegistrationProvisioningStateValues returns an array of possible values for the PartnerRegistrationProvisioningState const type. +func PossiblePartnerRegistrationProvisioningStateValues() []PartnerRegistrationProvisioningState { + return []PartnerRegistrationProvisioningState{PartnerRegistrationProvisioningStateCanceled, PartnerRegistrationProvisioningStateCreating, PartnerRegistrationProvisioningStateDeleting, PartnerRegistrationProvisioningStateFailed, PartnerRegistrationProvisioningStateSucceeded, PartnerRegistrationProvisioningStateUpdating} +} + +// PartnerRegistrationVisibilityState enumerates the values for partner registration visibility state. +type PartnerRegistrationVisibilityState string + +const ( + // GenerallyAvailable ... + GenerallyAvailable PartnerRegistrationVisibilityState = "GenerallyAvailable" + // Hidden ... + Hidden PartnerRegistrationVisibilityState = "Hidden" + // PublicPreview ... + PublicPreview PartnerRegistrationVisibilityState = "PublicPreview" +) + +// PossiblePartnerRegistrationVisibilityStateValues returns an array of possible values for the PartnerRegistrationVisibilityState const type. +func PossiblePartnerRegistrationVisibilityStateValues() []PartnerRegistrationVisibilityState { + return []PartnerRegistrationVisibilityState{GenerallyAvailable, Hidden, PublicPreview} +} + +// PartnerTopicActivationState enumerates the values for partner topic activation state. +type PartnerTopicActivationState string + +const ( + // Activated ... + Activated PartnerTopicActivationState = "Activated" + // Deactivated ... + Deactivated PartnerTopicActivationState = "Deactivated" + // NeverActivated ... + NeverActivated PartnerTopicActivationState = "NeverActivated" +) + +// PossiblePartnerTopicActivationStateValues returns an array of possible values for the PartnerTopicActivationState const type. +func PossiblePartnerTopicActivationStateValues() []PartnerTopicActivationState { + return []PartnerTopicActivationState{Activated, Deactivated, NeverActivated} +} + +// PartnerTopicProvisioningState enumerates the values for partner topic provisioning state. +type PartnerTopicProvisioningState string + +const ( + // PartnerTopicProvisioningStateCanceled ... + PartnerTopicProvisioningStateCanceled PartnerTopicProvisioningState = "Canceled" + // PartnerTopicProvisioningStateCreating ... + PartnerTopicProvisioningStateCreating PartnerTopicProvisioningState = "Creating" + // PartnerTopicProvisioningStateDeleting ... + PartnerTopicProvisioningStateDeleting PartnerTopicProvisioningState = "Deleting" + // PartnerTopicProvisioningStateFailed ... + PartnerTopicProvisioningStateFailed PartnerTopicProvisioningState = "Failed" + // PartnerTopicProvisioningStateSucceeded ... + PartnerTopicProvisioningStateSucceeded PartnerTopicProvisioningState = "Succeeded" + // PartnerTopicProvisioningStateUpdating ... + PartnerTopicProvisioningStateUpdating PartnerTopicProvisioningState = "Updating" +) + +// PossiblePartnerTopicProvisioningStateValues returns an array of possible values for the PartnerTopicProvisioningState const type. +func PossiblePartnerTopicProvisioningStateValues() []PartnerTopicProvisioningState { + return []PartnerTopicProvisioningState{PartnerTopicProvisioningStateCanceled, PartnerTopicProvisioningStateCreating, PartnerTopicProvisioningStateDeleting, PartnerTopicProvisioningStateFailed, PartnerTopicProvisioningStateSucceeded, PartnerTopicProvisioningStateUpdating} +} + +// PartnerTopicTypeAuthorizationState enumerates the values for partner topic type authorization state. +type PartnerTopicTypeAuthorizationState string + +const ( + // Authorized ... + Authorized PartnerTopicTypeAuthorizationState = "Authorized" + // NotApplicable ... + NotApplicable PartnerTopicTypeAuthorizationState = "NotApplicable" + // NotAuthorized ... + NotAuthorized PartnerTopicTypeAuthorizationState = "NotAuthorized" +) + +// PossiblePartnerTopicTypeAuthorizationStateValues returns an array of possible values for the PartnerTopicTypeAuthorizationState const type. +func PossiblePartnerTopicTypeAuthorizationStateValues() []PartnerTopicTypeAuthorizationState { + return []PartnerTopicTypeAuthorizationState{Authorized, NotApplicable, NotAuthorized} +} + +// PersistedConnectionStatus enumerates the values for persisted connection status. +type PersistedConnectionStatus string + +const ( + // Approved ... + Approved PersistedConnectionStatus = "Approved" + // Disconnected ... + Disconnected PersistedConnectionStatus = "Disconnected" + // Pending ... + Pending PersistedConnectionStatus = "Pending" + // Rejected ... + Rejected PersistedConnectionStatus = "Rejected" +) + +// PossiblePersistedConnectionStatusValues returns an array of possible values for the PersistedConnectionStatus const type. +func PossiblePersistedConnectionStatusValues() []PersistedConnectionStatus { + return []PersistedConnectionStatus{Approved, Disconnected, Pending, Rejected} +} + +// PublicNetworkAccess enumerates the values for public network access. +type PublicNetworkAccess string + +const ( + // Disabled ... + Disabled PublicNetworkAccess = "Disabled" + // Enabled ... + Enabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns an array of possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{Disabled, Enabled} +} + +// ResourceProvisioningState enumerates the values for resource provisioning state. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled ... + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateCreating ... + ResourceProvisioningStateCreating ResourceProvisioningState = "Creating" + // ResourceProvisioningStateDeleting ... + ResourceProvisioningStateDeleting ResourceProvisioningState = "Deleting" + // ResourceProvisioningStateFailed ... + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded ... + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" + // ResourceProvisioningStateUpdating ... + ResourceProvisioningStateUpdating ResourceProvisioningState = "Updating" +) + +// PossibleResourceProvisioningStateValues returns an array of possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ResourceProvisioningStateCanceled, ResourceProvisioningStateCreating, ResourceProvisioningStateDeleting, ResourceProvisioningStateFailed, ResourceProvisioningStateSucceeded, ResourceProvisioningStateUpdating} +} + +// ResourceRegionType enumerates the values for resource region type. +type ResourceRegionType string + +const ( + // GlobalResource ... + GlobalResource ResourceRegionType = "GlobalResource" + // RegionalResource ... + RegionalResource ResourceRegionType = "RegionalResource" +) + +// PossibleResourceRegionTypeValues returns an array of possible values for the ResourceRegionType const type. +func PossibleResourceRegionTypeValues() []ResourceRegionType { + return []ResourceRegionType{GlobalResource, RegionalResource} +} + +// Sku enumerates the values for sku. +type Sku string + +const ( + // Basic ... + Basic Sku = "Basic" + // Premium ... + Premium Sku = "Premium" +) + +// PossibleSkuValues returns an array of possible values for the Sku const type. +func PossibleSkuValues() []Sku { + return []Sku{Basic, Premium} +} + +// TopicProvisioningState enumerates the values for topic provisioning state. +type TopicProvisioningState string + +const ( + // TopicProvisioningStateCanceled ... + TopicProvisioningStateCanceled TopicProvisioningState = "Canceled" + // TopicProvisioningStateCreating ... + TopicProvisioningStateCreating TopicProvisioningState = "Creating" + // TopicProvisioningStateDeleting ... + TopicProvisioningStateDeleting TopicProvisioningState = "Deleting" + // TopicProvisioningStateFailed ... + TopicProvisioningStateFailed TopicProvisioningState = "Failed" + // TopicProvisioningStateSucceeded ... + TopicProvisioningStateSucceeded TopicProvisioningState = "Succeeded" + // TopicProvisioningStateUpdating ... + TopicProvisioningStateUpdating TopicProvisioningState = "Updating" +) + +// PossibleTopicProvisioningStateValues returns an array of possible values for the TopicProvisioningState const type. +func PossibleTopicProvisioningStateValues() []TopicProvisioningState { + return []TopicProvisioningState{TopicProvisioningStateCanceled, TopicProvisioningStateCreating, TopicProvisioningStateDeleting, TopicProvisioningStateFailed, TopicProvisioningStateSucceeded, TopicProvisioningStateUpdating} +} + +// TopicTypeProvisioningState enumerates the values for topic type provisioning state. +type TopicTypeProvisioningState string + +const ( + // TopicTypeProvisioningStateCanceled ... + TopicTypeProvisioningStateCanceled TopicTypeProvisioningState = "Canceled" + // TopicTypeProvisioningStateCreating ... + TopicTypeProvisioningStateCreating TopicTypeProvisioningState = "Creating" + // TopicTypeProvisioningStateDeleting ... + TopicTypeProvisioningStateDeleting TopicTypeProvisioningState = "Deleting" + // TopicTypeProvisioningStateFailed ... + TopicTypeProvisioningStateFailed TopicTypeProvisioningState = "Failed" + // TopicTypeProvisioningStateSucceeded ... + TopicTypeProvisioningStateSucceeded TopicTypeProvisioningState = "Succeeded" + // TopicTypeProvisioningStateUpdating ... + TopicTypeProvisioningStateUpdating TopicTypeProvisioningState = "Updating" +) + +// PossibleTopicTypeProvisioningStateValues returns an array of possible values for the TopicTypeProvisioningState const type. +func PossibleTopicTypeProvisioningStateValues() []TopicTypeProvisioningState { + return []TopicTypeProvisioningState{TopicTypeProvisioningStateCanceled, TopicTypeProvisioningStateCreating, TopicTypeProvisioningStateDeleting, TopicTypeProvisioningStateFailed, TopicTypeProvisioningStateSucceeded, TopicTypeProvisioningStateUpdating} +} + +// BasicAdvancedFilter this is the base type that represents an advanced filter. To configure an advanced filter, do +// not directly instantiate an object of this class. Instead, instantiate an object of a derived class such as +// BoolEqualsAdvancedFilter, NumberInAdvancedFilter, StringEqualsAdvancedFilter etc. depending on the type of the key +// based on which you want to filter. +type BasicAdvancedFilter interface { + AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) + AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) + AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) + AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) + AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) + AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) + AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) + AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) + AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) + AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) + AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) + AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) + AsAdvancedFilter() (*AdvancedFilter, bool) +} + +// AdvancedFilter this is the base type that represents an advanced filter. To configure an advanced filter, do +// not directly instantiate an object of this class. Instead, instantiate an object of a derived class such as +// BoolEqualsAdvancedFilter, NumberInAdvancedFilter, StringEqualsAdvancedFilter etc. depending on the type of +// the key based on which you want to filter. +type AdvancedFilter struct { + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +func unmarshalBasicAdvancedFilter(body []byte) (BasicAdvancedFilter, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["operatorType"] { + case string(OperatorTypeNumberIn): + var niaf NumberInAdvancedFilter + err := json.Unmarshal(body, &niaf) + return niaf, err + case string(OperatorTypeNumberNotIn): + var nniaf NumberNotInAdvancedFilter + err := json.Unmarshal(body, &nniaf) + return nniaf, err + case string(OperatorTypeNumberLessThan): + var nltaf NumberLessThanAdvancedFilter + err := json.Unmarshal(body, &nltaf) + return nltaf, err + case string(OperatorTypeNumberGreaterThan): + var ngtaf NumberGreaterThanAdvancedFilter + err := json.Unmarshal(body, &ngtaf) + return ngtaf, err + case string(OperatorTypeNumberLessThanOrEquals): + var nltoeaf NumberLessThanOrEqualsAdvancedFilter + err := json.Unmarshal(body, &nltoeaf) + return nltoeaf, err + case string(OperatorTypeNumberGreaterThanOrEquals): + var ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter + err := json.Unmarshal(body, &ngtoeaf) + return ngtoeaf, err + case string(OperatorTypeBoolEquals): + var beaf BoolEqualsAdvancedFilter + err := json.Unmarshal(body, &beaf) + return beaf, err + case string(OperatorTypeStringIn): + var siaf StringInAdvancedFilter + err := json.Unmarshal(body, &siaf) + return siaf, err + case string(OperatorTypeStringNotIn): + var sniaf StringNotInAdvancedFilter + err := json.Unmarshal(body, &sniaf) + return sniaf, err + case string(OperatorTypeStringBeginsWith): + var sbwaf StringBeginsWithAdvancedFilter + err := json.Unmarshal(body, &sbwaf) + return sbwaf, err + case string(OperatorTypeStringEndsWith): + var sewaf StringEndsWithAdvancedFilter + err := json.Unmarshal(body, &sewaf) + return sewaf, err + case string(OperatorTypeStringContains): + var scaf StringContainsAdvancedFilter + err := json.Unmarshal(body, &scaf) + return scaf, err + default: + var af AdvancedFilter + err := json.Unmarshal(body, &af) + return af, err + } +} +func unmarshalBasicAdvancedFilterArray(body []byte) ([]BasicAdvancedFilter, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + afArray := make([]BasicAdvancedFilter, len(rawMessages)) + + for index, rawMessage := range rawMessages { + af, err := unmarshalBasicAdvancedFilter(*rawMessage) + if err != nil { + return nil, err + } + afArray[index] = af + } + return afArray, nil +} + +// MarshalJSON is the custom marshaler for AdvancedFilter. +func (af AdvancedFilter) MarshalJSON() ([]byte, error) { + af.OperatorType = OperatorTypeAdvancedFilter + objectMap := make(map[string]interface{}) + if af.Key != nil { + objectMap["key"] = af.Key + } + if af.OperatorType != "" { + objectMap["operatorType"] = af.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return &af, true +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for AdvancedFilter. +func (af AdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &af, true +} + +// AzureFunctionEventSubscriptionDestination information about the azure function destination for an event +// subscription. +type AzureFunctionEventSubscriptionDestination struct { + // AzureFunctionEventSubscriptionDestinationProperties - Azure Function Properties of the event subscription destination. + *AzureFunctionEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + afesd.EndpointType = EndpointTypeAzureFunction + objectMap := make(map[string]interface{}) + if afesd.AzureFunctionEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = afesd.AzureFunctionEventSubscriptionDestinationProperties + } + if afesd.EndpointType != "" { + objectMap["endpointType"] = afesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return &afesd, true +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for AzureFunctionEventSubscriptionDestination. +func (afesd AzureFunctionEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &afesd, true +} + +// UnmarshalJSON is the custom unmarshaler for AzureFunctionEventSubscriptionDestination struct. +func (afesd *AzureFunctionEventSubscriptionDestination) 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 azureFunctionEventSubscriptionDestinationProperties AzureFunctionEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &azureFunctionEventSubscriptionDestinationProperties) + if err != nil { + return err + } + afesd.AzureFunctionEventSubscriptionDestinationProperties = &azureFunctionEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + afesd.EndpointType = endpointType + } + } + } + + return nil +} + +// AzureFunctionEventSubscriptionDestinationProperties the properties that represent the Azure Function +// destination of an event subscription. +type AzureFunctionEventSubscriptionDestinationProperties struct { + // ResourceID - The Azure Resource Id that represents the endpoint of the Azure Function destination of an event subscription. + ResourceID *string `json:"resourceId,omitempty"` + // MaxEventsPerBatch - Maximum number of events per batch. + MaxEventsPerBatch *int32 `json:"maxEventsPerBatch,omitempty"` + // PreferredBatchSizeInKilobytes - Preferred batch size in Kilobytes. + PreferredBatchSizeInKilobytes *int32 `json:"preferredBatchSizeInKilobytes,omitempty"` +} + +// BoolEqualsAdvancedFilter boolEquals Advanced Filter. +type BoolEqualsAdvancedFilter struct { + // Value - The boolean filter value. + Value *bool `json:"value,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) MarshalJSON() ([]byte, error) { + beaf.OperatorType = OperatorTypeBoolEquals + objectMap := make(map[string]interface{}) + if beaf.Value != nil { + objectMap["value"] = beaf.Value + } + if beaf.Key != nil { + objectMap["key"] = beaf.Key + } + if beaf.OperatorType != "" { + objectMap["operatorType"] = beaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return &beaf, true +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for BoolEqualsAdvancedFilter. +func (beaf BoolEqualsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &beaf, true +} + +// ConnectionState connectionState information. +type ConnectionState struct { + // Status - Status of the connection. Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' + Status PersistedConnectionStatus `json:"status,omitempty"` + // Description - Description of the connection state. + Description *string `json:"description,omitempty"` + // ActionsRequired - Actions required (if any). + ActionsRequired *string `json:"actionsRequired,omitempty"` +} + +// BasicDeadLetterDestination information about the dead letter destination for an event subscription. To configure a +// deadletter destination, do not directly instantiate an object of this class. Instead, instantiate an object of a +// derived class. Currently, StorageBlobDeadLetterDestination is the only class that derives from this class. +type BasicDeadLetterDestination interface { + AsStorageBlobDeadLetterDestination() (*StorageBlobDeadLetterDestination, bool) + AsDeadLetterDestination() (*DeadLetterDestination, bool) +} + +// DeadLetterDestination information about the dead letter destination for an event subscription. To configure +// a deadletter destination, do not directly instantiate an object of this class. Instead, instantiate an +// object of a derived class. Currently, StorageBlobDeadLetterDestination is the only class that derives from +// this class. +type DeadLetterDestination struct { + // EndpointType - Possible values include: 'EndpointTypeDeadLetterDestination', 'EndpointTypeStorageBlob' + EndpointType EndpointTypeBasicDeadLetterDestination `json:"endpointType,omitempty"` +} + +func unmarshalBasicDeadLetterDestination(body []byte) (BasicDeadLetterDestination, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["endpointType"] { + case string(EndpointTypeStorageBlob): + var sbdld StorageBlobDeadLetterDestination + err := json.Unmarshal(body, &sbdld) + return sbdld, err + default: + var dld DeadLetterDestination + err := json.Unmarshal(body, &dld) + return dld, err + } +} +func unmarshalBasicDeadLetterDestinationArray(body []byte) ([]BasicDeadLetterDestination, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + dldArray := make([]BasicDeadLetterDestination, len(rawMessages)) + + for index, rawMessage := range rawMessages { + dld, err := unmarshalBasicDeadLetterDestination(*rawMessage) + if err != nil { + return nil, err + } + dldArray[index] = dld + } + return dldArray, nil +} + +// MarshalJSON is the custom marshaler for DeadLetterDestination. +func (dld DeadLetterDestination) MarshalJSON() ([]byte, error) { + dld.EndpointType = EndpointTypeDeadLetterDestination + objectMap := make(map[string]interface{}) + if dld.EndpointType != "" { + objectMap["endpointType"] = dld.EndpointType + } + return json.Marshal(objectMap) +} + +// AsStorageBlobDeadLetterDestination is the BasicDeadLetterDestination implementation for DeadLetterDestination. +func (dld DeadLetterDestination) AsStorageBlobDeadLetterDestination() (*StorageBlobDeadLetterDestination, bool) { + return nil, false +} + +// AsDeadLetterDestination is the BasicDeadLetterDestination implementation for DeadLetterDestination. +func (dld DeadLetterDestination) AsDeadLetterDestination() (*DeadLetterDestination, bool) { + return &dld, true +} + +// AsBasicDeadLetterDestination is the BasicDeadLetterDestination implementation for DeadLetterDestination. +func (dld DeadLetterDestination) AsBasicDeadLetterDestination() (BasicDeadLetterDestination, bool) { + return &dld, true +} + +// DeadLetterWithResourceIdentity information about the deadletter destination with resource identity. +type DeadLetterWithResourceIdentity struct { + // Identity - The identity to use when dead-lettering events. + Identity *EventSubscriptionIdentity `json:"identity,omitempty"` + // DeadLetterDestination - Information about the destination where events have to be delivered for the event subscription. + // Uses the managed identity setup on the parent resource (namely, topic or domain) to acquire the authentication tokens being used during delivery / dead-lettering. + DeadLetterDestination BasicDeadLetterDestination `json:"deadLetterDestination,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DeadLetterWithResourceIdentity struct. +func (dlwri *DeadLetterWithResourceIdentity) 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 "identity": + if v != nil { + var identity EventSubscriptionIdentity + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + dlwri.Identity = &identity + } + case "deadLetterDestination": + if v != nil { + deadLetterDestination, err := unmarshalBasicDeadLetterDestination(*v) + if err != nil { + return err + } + dlwri.DeadLetterDestination = deadLetterDestination + } + } + } + + return nil +} + +// DeliveryWithResourceIdentity information about the delivery for an event subscription with resource +// identity. +type DeliveryWithResourceIdentity struct { + // Identity - The identity to use when delivering events. + Identity *EventSubscriptionIdentity `json:"identity,omitempty"` + // Destination - Information about the destination where events have to be delivered for the event subscription. + // Uses Azure Event Grid's identity to acquire the authentication tokens being used during delivery / dead-lettering. + Destination BasicEventSubscriptionDestination `json:"destination,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DeliveryWithResourceIdentity struct. +func (dwri *DeliveryWithResourceIdentity) 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 "identity": + if v != nil { + var identity EventSubscriptionIdentity + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + dwri.Identity = &identity + } + case "destination": + if v != nil { + destination, err := unmarshalBasicEventSubscriptionDestination(*v) + if err != nil { + return err + } + dwri.Destination = destination + } + } + } + + return nil +} + +// Domain eventGrid Domain. +type Domain struct { + autorest.Response `json:"-"` + // DomainProperties - Properties of the domain. + *DomainProperties `json:"properties,omitempty"` + // Sku - The Sku pricing tier for the domain. + Sku *ResourceSku `json:"sku,omitempty"` + // Identity - Identity information for the resource. + Identity *IdentityInfo `json:"identity,omitempty"` + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Domain. +func (d Domain) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if d.DomainProperties != nil { + objectMap["properties"] = d.DomainProperties + } + if d.Sku != nil { + objectMap["sku"] = d.Sku + } + if d.Identity != nil { + objectMap["identity"] = d.Identity + } + if d.Location != nil { + objectMap["location"] = d.Location + } + if d.Tags != nil { + objectMap["tags"] = d.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Domain struct. +func (d *Domain) 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 domainProperties DomainProperties + err = json.Unmarshal(*v, &domainProperties) + if err != nil { + return err + } + d.DomainProperties = &domainProperties + } + case "sku": + if v != nil { + var sku ResourceSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + d.Sku = &sku + } + case "identity": + if v != nil { + var identity IdentityInfo + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + d.Identity = &identity + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + d.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + d.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + d.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + d.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + d.Type = &typeVar + } + } + } + + return nil +} + +// DomainProperties properties of the Domain. +type DomainProperties struct { + // PrivateEndpointConnections - List of private endpoint connections. + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the domain. Possible values include: 'Creating', 'Updating', 'Deleting', 'Succeeded', 'Canceled', 'Failed' + ProvisioningState DomainProvisioningState `json:"provisioningState,omitempty"` + // Endpoint - READ-ONLY; Endpoint for the domain. + Endpoint *string `json:"endpoint,omitempty"` + // InputSchema - This determines the format that Event Grid should expect for incoming events published to the domain. Possible values include: 'InputSchemaEventGridSchema', 'InputSchemaCustomEventSchema', 'InputSchemaCloudEventSchemaV10' + InputSchema InputSchema `json:"inputSchema,omitempty"` + // InputSchemaMapping - Information about the InputSchemaMapping which specified the info about mapping event payload. + InputSchemaMapping BasicInputSchemaMapping `json:"inputSchemaMapping,omitempty"` + // MetricResourceID - READ-ONLY; Metric resource id for the domain. + MetricResourceID *string `json:"metricResourceId,omitempty"` + // PublicNetworkAccess - This determines if traffic is allowed over public network. By default it is enabled. + // You can further restrict to specific IPs by configuring . Possible values include: 'Enabled', 'Disabled' + PublicNetworkAccess PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + // InboundIPRules - This can be used to restrict traffic from specific IPs instead of all IPs. Note: These are considered only if PublicNetworkAccess is enabled. + InboundIPRules *[]InboundIPRule `json:"inboundIpRules,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for DomainProperties struct. +func (dp *DomainProperties) 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 "privateEndpointConnections": + if v != nil { + var privateEndpointConnections []PrivateEndpointConnection + err = json.Unmarshal(*v, &privateEndpointConnections) + if err != nil { + return err + } + dp.PrivateEndpointConnections = &privateEndpointConnections + } + case "provisioningState": + if v != nil { + var provisioningState DomainProvisioningState + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + dp.ProvisioningState = provisioningState + } + case "endpoint": + if v != nil { + var endpoint string + err = json.Unmarshal(*v, &endpoint) + if err != nil { + return err + } + dp.Endpoint = &endpoint + } + case "inputSchema": + if v != nil { + var inputSchema InputSchema + err = json.Unmarshal(*v, &inputSchema) + if err != nil { + return err + } + dp.InputSchema = inputSchema + } + case "inputSchemaMapping": + if v != nil { + inputSchemaMapping, err := unmarshalBasicInputSchemaMapping(*v) + if err != nil { + return err + } + dp.InputSchemaMapping = inputSchemaMapping + } + case "metricResourceId": + if v != nil { + var metricResourceID string + err = json.Unmarshal(*v, &metricResourceID) + if err != nil { + return err + } + dp.MetricResourceID = &metricResourceID + } + case "publicNetworkAccess": + if v != nil { + var publicNetworkAccess PublicNetworkAccess + err = json.Unmarshal(*v, &publicNetworkAccess) + if err != nil { + return err + } + dp.PublicNetworkAccess = publicNetworkAccess + } + case "inboundIpRules": + if v != nil { + var inboundIPRules []InboundIPRule + err = json.Unmarshal(*v, &inboundIPRules) + if err != nil { + return err + } + dp.InboundIPRules = &inboundIPRules + } + } + } + + return nil +} + +// DomainRegenerateKeyRequest domain regenerate share access key request. +type DomainRegenerateKeyRequest struct { + // KeyName - Key name to regenerate key1 or key2. + KeyName *string `json:"keyName,omitempty"` +} + +// DomainsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DomainsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DomainsCreateOrUpdateFuture) Result(client DomainsClient) (d Domain, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.DomainsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.CreateOrUpdateResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsCreateOrUpdateFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DomainsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DomainsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DomainsDeleteFuture) Result(client DomainsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.DomainsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DomainSharedAccessKeys shared access keys of the Domain. +type DomainSharedAccessKeys struct { + autorest.Response `json:"-"` + // Key1 - Shared access key1 for the domain. + Key1 *string `json:"key1,omitempty"` + // Key2 - Shared access key2 for the domain. + Key2 *string `json:"key2,omitempty"` +} + +// DomainsListResult result of the List Domains operation +type DomainsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of Domains + Value *[]Domain `json:"value,omitempty"` + // NextLink - A link for the next page of domains + NextLink *string `json:"nextLink,omitempty"` +} + +// DomainsListResultIterator provides access to a complete listing of Domain values. +type DomainsListResultIterator struct { + i int + page DomainsListResultPage +} + +// 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 *DomainsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainsListResultIterator.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 *DomainsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DomainsListResultIterator) 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 DomainsListResultIterator) Response() DomainsListResult { + 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 DomainsListResultIterator) Value() Domain { + if !iter.page.NotDone() { + return Domain{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the DomainsListResultIterator type. +func NewDomainsListResultIterator(page DomainsListResultPage) DomainsListResultIterator { + return DomainsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (dlr DomainsListResult) IsEmpty() bool { + return dlr.Value == nil || len(*dlr.Value) == 0 +} + +// domainsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (dlr DomainsListResult) domainsListResultPreparer(ctx context.Context) (*http.Request, error) { + if dlr.NextLink == nil || len(to.String(dlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(dlr.NextLink))) +} + +// DomainsListResultPage contains a page of Domain values. +type DomainsListResultPage struct { + fn func(context.Context, DomainsListResult) (DomainsListResult, error) + dlr DomainsListResult +} + +// 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 *DomainsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainsListResultPage.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.dlr) + if err != nil { + return err + } + page.dlr = 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 *DomainsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DomainsListResultPage) NotDone() bool { + return !page.dlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DomainsListResultPage) Response() DomainsListResult { + return page.dlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DomainsListResultPage) Values() []Domain { + if page.dlr.IsEmpty() { + return nil + } + return *page.dlr.Value +} + +// Creates a new instance of the DomainsListResultPage type. +func NewDomainsListResultPage(getNextPage func(context.Context, DomainsListResult) (DomainsListResult, error)) DomainsListResultPage { + return DomainsListResultPage{fn: getNextPage} +} + +// DomainsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DomainsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DomainsUpdateFuture) Result(client DomainsClient) (d Domain, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.DomainsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.UpdateResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainsUpdateFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DomainTopic domain Topic. +type DomainTopic struct { + autorest.Response `json:"-"` + // DomainTopicProperties - Properties of the Domain Topic. + *DomainTopicProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for DomainTopic. +func (dt DomainTopic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dt.DomainTopicProperties != nil { + objectMap["properties"] = dt.DomainTopicProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DomainTopic struct. +func (dt *DomainTopic) 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 domainTopicProperties DomainTopicProperties + err = json.Unmarshal(*v, &domainTopicProperties) + if err != nil { + return err + } + dt.DomainTopicProperties = &domainTopicProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + dt.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + dt.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + dt.Type = &typeVar + } + } + } + + return nil +} + +// DomainTopicProperties properties of the Domain Topic. +type DomainTopicProperties struct { + // ProvisioningState - Provisioning state of the domain topic. Possible values include: 'DomainTopicProvisioningStateCreating', 'DomainTopicProvisioningStateUpdating', 'DomainTopicProvisioningStateDeleting', 'DomainTopicProvisioningStateSucceeded', 'DomainTopicProvisioningStateCanceled', 'DomainTopicProvisioningStateFailed' + ProvisioningState DomainTopicProvisioningState `json:"provisioningState,omitempty"` +} + +// DomainTopicsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type DomainTopicsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DomainTopicsCreateOrUpdateFuture) Result(client DomainTopicsClient) (dt DomainTopic, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.DomainTopicsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if dt.Response.Response, err = future.GetResult(sender); err == nil && dt.Response.Response.StatusCode != http.StatusNoContent { + dt, err = client.CreateOrUpdateResponder(dt.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsCreateOrUpdateFuture", "Result", dt.Response.Response, "Failure responding to request") + } + } + return +} + +// DomainTopicsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DomainTopicsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DomainTopicsDeleteFuture) Result(client DomainTopicsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.DomainTopicsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.DomainTopicsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DomainTopicsListResult result of the List Domain Topics operation +type DomainTopicsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of Domain Topics + Value *[]DomainTopic `json:"value,omitempty"` + // NextLink - A link for the next page of domain topics + NextLink *string `json:"nextLink,omitempty"` +} + +// DomainTopicsListResultIterator provides access to a complete listing of DomainTopic values. +type DomainTopicsListResultIterator struct { + i int + page DomainTopicsListResultPage +} + +// 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 *DomainTopicsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsListResultIterator.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 *DomainTopicsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DomainTopicsListResultIterator) 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 DomainTopicsListResultIterator) Response() DomainTopicsListResult { + 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 DomainTopicsListResultIterator) Value() DomainTopic { + if !iter.page.NotDone() { + return DomainTopic{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the DomainTopicsListResultIterator type. +func NewDomainTopicsListResultIterator(page DomainTopicsListResultPage) DomainTopicsListResultIterator { + return DomainTopicsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (dtlr DomainTopicsListResult) IsEmpty() bool { + return dtlr.Value == nil || len(*dtlr.Value) == 0 +} + +// domainTopicsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (dtlr DomainTopicsListResult) domainTopicsListResultPreparer(ctx context.Context) (*http.Request, error) { + if dtlr.NextLink == nil || len(to.String(dtlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(dtlr.NextLink))) +} + +// DomainTopicsListResultPage contains a page of DomainTopic values. +type DomainTopicsListResultPage struct { + fn func(context.Context, DomainTopicsListResult) (DomainTopicsListResult, error) + dtlr DomainTopicsListResult +} + +// 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 *DomainTopicsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DomainTopicsListResultPage.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.dtlr) + if err != nil { + return err + } + page.dtlr = 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 *DomainTopicsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DomainTopicsListResultPage) NotDone() bool { + return !page.dtlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DomainTopicsListResultPage) Response() DomainTopicsListResult { + return page.dtlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DomainTopicsListResultPage) Values() []DomainTopic { + if page.dtlr.IsEmpty() { + return nil + } + return *page.dtlr.Value +} + +// Creates a new instance of the DomainTopicsListResultPage type. +func NewDomainTopicsListResultPage(getNextPage func(context.Context, DomainTopicsListResult) (DomainTopicsListResult, error)) DomainTopicsListResultPage { + return DomainTopicsListResultPage{fn: getNextPage} +} + +// DomainUpdateParameterProperties information of domain update parameter properties. +type DomainUpdateParameterProperties struct { + // PublicNetworkAccess - This determines if traffic is allowed over public network. By default it is enabled. + // You can further restrict to specific IPs by configuring . Possible values include: 'Enabled', 'Disabled' + PublicNetworkAccess PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + // InboundIPRules - This can be used to restrict traffic from specific IPs instead of all IPs. Note: These are considered only if PublicNetworkAccess is enabled. + InboundIPRules *[]InboundIPRule `json:"inboundIpRules,omitempty"` +} + +// DomainUpdateParameters properties of the Domain update. +type DomainUpdateParameters struct { + // Tags - Tags of the domains resource. + Tags map[string]*string `json:"tags"` + // DomainUpdateParameterProperties - Properties of the resource. + *DomainUpdateParameterProperties `json:"properties,omitempty"` + // Identity - Identity information for the resource. + Identity *IdentityInfo `json:"identity,omitempty"` + // Sku - The Sku pricing tier for the domain. + Sku *ResourceSku `json:"sku,omitempty"` +} + +// MarshalJSON is the custom marshaler for DomainUpdateParameters. +func (dup DomainUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if dup.Tags != nil { + objectMap["tags"] = dup.Tags + } + if dup.DomainUpdateParameterProperties != nil { + objectMap["properties"] = dup.DomainUpdateParameterProperties + } + if dup.Identity != nil { + objectMap["identity"] = dup.Identity + } + if dup.Sku != nil { + objectMap["sku"] = dup.Sku + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DomainUpdateParameters struct. +func (dup *DomainUpdateParameters) 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 "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + dup.Tags = tags + } + case "properties": + if v != nil { + var domainUpdateParameterProperties DomainUpdateParameterProperties + err = json.Unmarshal(*v, &domainUpdateParameterProperties) + if err != nil { + return err + } + dup.DomainUpdateParameterProperties = &domainUpdateParameterProperties + } + case "identity": + if v != nil { + var identity IdentityInfo + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + dup.Identity = &identity + } + case "sku": + if v != nil { + var sku ResourceSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + dup.Sku = &sku + } + } + } + + return nil +} + +// EventChannel event Channel. +type EventChannel struct { + autorest.Response `json:"-"` + // EventChannelProperties - Properties of the EventChannel. + *EventChannelProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventChannel. +func (ec EventChannel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ec.EventChannelProperties != nil { + objectMap["properties"] = ec.EventChannelProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for EventChannel struct. +func (ec *EventChannel) 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 eventChannelProperties EventChannelProperties + err = json.Unmarshal(*v, &eventChannelProperties) + if err != nil { + return err + } + ec.EventChannelProperties = &eventChannelProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ec.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ec.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ec.Type = &typeVar + } + } + } + + return nil +} + +// EventChannelDestination properties of the destination of an event channel. +type EventChannelDestination struct { + // AzureSubscriptionID - Azure subscription ID of the customer creating the event channel. The partner topic + // associated with the event channel will be created under this Azure subscription. + AzureSubscriptionID *string `json:"azureSubscriptionId,omitempty"` + // ResourceGroup - Azure Resource Group of the customer creating the event channel. The partner topic + // associated with the event channel will be created under this resource group. + ResourceGroup *string `json:"resourceGroup,omitempty"` + // PartnerTopicName - Name of the partner topic associated with the event channel. + PartnerTopicName *string `json:"partnerTopicName,omitempty"` +} + +// EventChannelFilter filter for the Event Channel. +type EventChannelFilter struct { + // SubjectBeginsWith - An optional string to filter events for an event channel based on a resource path prefix. + // The format of this depends on the publisher of the events. Wildcard characters are not supported in this path. + SubjectBeginsWith *string `json:"subjectBeginsWith,omitempty"` + // SubjectEndsWith - An optional string to filter events for an event channel based on a resource path suffix. + // Wildcard characters are not supported in this path. + SubjectEndsWith *string `json:"subjectEndsWith,omitempty"` + // IncludedEventTypes - A list of applicable event types that need to be part of the event channel. If it is desired to subscribe to all default event types, set the IncludedEventTypes to null. + IncludedEventTypes *[]string `json:"includedEventTypes,omitempty"` + // IsSubjectCaseSensitive - Specifies if the SubjectBeginsWith and SubjectEndsWith properties of the filter + // should be compared in a case sensitive manner. + IsSubjectCaseSensitive *bool `json:"isSubjectCaseSensitive,omitempty"` + // AdvancedFilters - An array of advanced filters that are used for filtering event channels. + AdvancedFilters *[]BasicAdvancedFilter `json:"advancedFilters,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for EventChannelFilter struct. +func (ecf *EventChannelFilter) 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 "subjectBeginsWith": + if v != nil { + var subjectBeginsWith string + err = json.Unmarshal(*v, &subjectBeginsWith) + if err != nil { + return err + } + ecf.SubjectBeginsWith = &subjectBeginsWith + } + case "subjectEndsWith": + if v != nil { + var subjectEndsWith string + err = json.Unmarshal(*v, &subjectEndsWith) + if err != nil { + return err + } + ecf.SubjectEndsWith = &subjectEndsWith + } + case "includedEventTypes": + if v != nil { + var includedEventTypes []string + err = json.Unmarshal(*v, &includedEventTypes) + if err != nil { + return err + } + ecf.IncludedEventTypes = &includedEventTypes + } + case "isSubjectCaseSensitive": + if v != nil { + var isSubjectCaseSensitive bool + err = json.Unmarshal(*v, &isSubjectCaseSensitive) + if err != nil { + return err + } + ecf.IsSubjectCaseSensitive = &isSubjectCaseSensitive + } + case "advancedFilters": + if v != nil { + advancedFilters, err := unmarshalBasicAdvancedFilterArray(*v) + if err != nil { + return err + } + ecf.AdvancedFilters = &advancedFilters + } + } + } + + return nil +} + +// EventChannelProperties properties of the Event Channel. +type EventChannelProperties struct { + // Source - Source of the event channel. This represents a unique resource in the partner's resource model. + Source *EventChannelSource `json:"source,omitempty"` + // Destination - Represents the destination of an event channel. + Destination *EventChannelDestination `json:"destination,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the event channel. Possible values include: 'EventChannelProvisioningStateCreating', 'EventChannelProvisioningStateUpdating', 'EventChannelProvisioningStateDeleting', 'EventChannelProvisioningStateSucceeded', 'EventChannelProvisioningStateCanceled', 'EventChannelProvisioningStateFailed' + ProvisioningState EventChannelProvisioningState `json:"provisioningState,omitempty"` + // Filter - Information about the filter for the event channel. + Filter *EventChannelFilter `json:"filter,omitempty"` +} + +// EventChannelsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type EventChannelsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EventChannelsDeleteFuture) Result(client EventChannelsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventChannelsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.EventChannelsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// EventChannelsListResult result of the List Event Channels operation +type EventChannelsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of Event Channels + Value *[]EventChannel `json:"value,omitempty"` + // NextLink - A link for the next page of event channels + NextLink *string `json:"nextLink,omitempty"` +} + +// EventChannelsListResultIterator provides access to a complete listing of EventChannel values. +type EventChannelsListResultIterator struct { + i int + page EventChannelsListResultPage +} + +// 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 *EventChannelsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsListResultIterator.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 *EventChannelsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter EventChannelsListResultIterator) 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 EventChannelsListResultIterator) Response() EventChannelsListResult { + 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 EventChannelsListResultIterator) Value() EventChannel { + if !iter.page.NotDone() { + return EventChannel{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the EventChannelsListResultIterator type. +func NewEventChannelsListResultIterator(page EventChannelsListResultPage) EventChannelsListResultIterator { + return EventChannelsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (eclr EventChannelsListResult) IsEmpty() bool { + return eclr.Value == nil || len(*eclr.Value) == 0 +} + +// eventChannelsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (eclr EventChannelsListResult) eventChannelsListResultPreparer(ctx context.Context) (*http.Request, error) { + if eclr.NextLink == nil || len(to.String(eclr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(eclr.NextLink))) +} + +// EventChannelsListResultPage contains a page of EventChannel values. +type EventChannelsListResultPage struct { + fn func(context.Context, EventChannelsListResult) (EventChannelsListResult, error) + eclr EventChannelsListResult +} + +// 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 *EventChannelsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventChannelsListResultPage.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.eclr) + if err != nil { + return err + } + page.eclr = 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 *EventChannelsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page EventChannelsListResultPage) NotDone() bool { + return !page.eclr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page EventChannelsListResultPage) Response() EventChannelsListResult { + return page.eclr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page EventChannelsListResultPage) Values() []EventChannel { + if page.eclr.IsEmpty() { + return nil + } + return *page.eclr.Value +} + +// Creates a new instance of the EventChannelsListResultPage type. +func NewEventChannelsListResultPage(getNextPage func(context.Context, EventChannelsListResult) (EventChannelsListResult, error)) EventChannelsListResultPage { + return EventChannelsListResultPage{fn: getNextPage} +} + +// EventChannelSource properties of the source of an event channel. +type EventChannelSource struct { + // Source - The identifier of the resource that's the source of the events. + // This represents a unique resource in the partner's resource model. + Source *string `json:"source,omitempty"` +} + +// EventHubEventSubscriptionDestination information about the event hub destination for an event +// subscription. +type EventHubEventSubscriptionDestination struct { + // EventHubEventSubscriptionDestinationProperties - Event Hub Properties of the event subscription destination. + *EventHubEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + ehesd.EndpointType = EndpointTypeEventHub + objectMap := make(map[string]interface{}) + if ehesd.EventHubEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = ehesd.EventHubEventSubscriptionDestinationProperties + } + if ehesd.EndpointType != "" { + objectMap["endpointType"] = ehesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return &ehesd, true +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventHubEventSubscriptionDestination. +func (ehesd EventHubEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &ehesd, true +} + +// UnmarshalJSON is the custom unmarshaler for EventHubEventSubscriptionDestination struct. +func (ehesd *EventHubEventSubscriptionDestination) 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 eventHubEventSubscriptionDestinationProperties EventHubEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &eventHubEventSubscriptionDestinationProperties) + if err != nil { + return err + } + ehesd.EventHubEventSubscriptionDestinationProperties = &eventHubEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + ehesd.EndpointType = endpointType + } + } + } + + return nil +} + +// EventHubEventSubscriptionDestinationProperties the properties for a event hub destination. +type EventHubEventSubscriptionDestinationProperties struct { + // ResourceID - The Azure Resource Id that represents the endpoint of an Event Hub destination of an event subscription. + ResourceID *string `json:"resourceId,omitempty"` +} + +// EventSubscription event Subscription +type EventSubscription struct { + autorest.Response `json:"-"` + // EventSubscriptionProperties - Properties of the event subscription. + *EventSubscriptionProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventSubscription. +func (es EventSubscription) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if es.EventSubscriptionProperties != nil { + objectMap["properties"] = es.EventSubscriptionProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for EventSubscription struct. +func (es *EventSubscription) 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 eventSubscriptionProperties EventSubscriptionProperties + err = json.Unmarshal(*v, &eventSubscriptionProperties) + if err != nil { + return err + } + es.EventSubscriptionProperties = &eventSubscriptionProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + es.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + es.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + es.Type = &typeVar + } + } + } + + return nil +} + +// BasicEventSubscriptionDestination information about the destination for an event subscription. +type BasicEventSubscriptionDestination interface { + AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) + AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) + AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) + AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) + AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) + AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) + AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) + AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) +} + +// EventSubscriptionDestination information about the destination for an event subscription. +type EventSubscriptionDestination struct { + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +func unmarshalBasicEventSubscriptionDestination(body []byte) (BasicEventSubscriptionDestination, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["endpointType"] { + case string(EndpointTypeWebHook): + var whesd WebHookEventSubscriptionDestination + err := json.Unmarshal(body, &whesd) + return whesd, err + case string(EndpointTypeEventHub): + var ehesd EventHubEventSubscriptionDestination + err := json.Unmarshal(body, &ehesd) + return ehesd, err + case string(EndpointTypeStorageQueue): + var sqesd StorageQueueEventSubscriptionDestination + err := json.Unmarshal(body, &sqesd) + return sqesd, err + case string(EndpointTypeHybridConnection): + var hcesd HybridConnectionEventSubscriptionDestination + err := json.Unmarshal(body, &hcesd) + return hcesd, err + case string(EndpointTypeServiceBusQueue): + var sbqesd ServiceBusQueueEventSubscriptionDestination + err := json.Unmarshal(body, &sbqesd) + return sbqesd, err + case string(EndpointTypeServiceBusTopic): + var sbtesd ServiceBusTopicEventSubscriptionDestination + err := json.Unmarshal(body, &sbtesd) + return sbtesd, err + case string(EndpointTypeAzureFunction): + var afesd AzureFunctionEventSubscriptionDestination + err := json.Unmarshal(body, &afesd) + return afesd, err + default: + var esd EventSubscriptionDestination + err := json.Unmarshal(body, &esd) + return esd, err + } +} +func unmarshalBasicEventSubscriptionDestinationArray(body []byte) ([]BasicEventSubscriptionDestination, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + esdArray := make([]BasicEventSubscriptionDestination, len(rawMessages)) + + for index, rawMessage := range rawMessages { + esd, err := unmarshalBasicEventSubscriptionDestination(*rawMessage) + if err != nil { + return nil, err + } + esdArray[index] = esd + } + return esdArray, nil +} + +// MarshalJSON is the custom marshaler for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) MarshalJSON() ([]byte, error) { + esd.EndpointType = EndpointTypeEventSubscriptionDestination + objectMap := make(map[string]interface{}) + if esd.EndpointType != "" { + objectMap["endpointType"] = esd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return &esd, true +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for EventSubscriptionDestination. +func (esd EventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &esd, true +} + +// EventSubscriptionFilter filter for the Event Subscription. +type EventSubscriptionFilter struct { + // SubjectBeginsWith - An optional string to filter events for an event subscription based on a resource path prefix. + // The format of this depends on the publisher of the events. + // Wildcard characters are not supported in this path. + SubjectBeginsWith *string `json:"subjectBeginsWith,omitempty"` + // SubjectEndsWith - An optional string to filter events for an event subscription based on a resource path suffix. + // Wildcard characters are not supported in this path. + SubjectEndsWith *string `json:"subjectEndsWith,omitempty"` + // IncludedEventTypes - A list of applicable event types that need to be part of the event subscription. If it is desired to subscribe to all default event types, set the IncludedEventTypes to null. + IncludedEventTypes *[]string `json:"includedEventTypes,omitempty"` + // IsSubjectCaseSensitive - Specifies if the SubjectBeginsWith and SubjectEndsWith properties of the filter + // should be compared in a case sensitive manner. + IsSubjectCaseSensitive *bool `json:"isSubjectCaseSensitive,omitempty"` + // AdvancedFilters - An array of advanced filters that are used for filtering event subscriptions. + AdvancedFilters *[]BasicAdvancedFilter `json:"advancedFilters,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for EventSubscriptionFilter struct. +func (esf *EventSubscriptionFilter) 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 "subjectBeginsWith": + if v != nil { + var subjectBeginsWith string + err = json.Unmarshal(*v, &subjectBeginsWith) + if err != nil { + return err + } + esf.SubjectBeginsWith = &subjectBeginsWith + } + case "subjectEndsWith": + if v != nil { + var subjectEndsWith string + err = json.Unmarshal(*v, &subjectEndsWith) + if err != nil { + return err + } + esf.SubjectEndsWith = &subjectEndsWith + } + case "includedEventTypes": + if v != nil { + var includedEventTypes []string + err = json.Unmarshal(*v, &includedEventTypes) + if err != nil { + return err + } + esf.IncludedEventTypes = &includedEventTypes + } + case "isSubjectCaseSensitive": + if v != nil { + var isSubjectCaseSensitive bool + err = json.Unmarshal(*v, &isSubjectCaseSensitive) + if err != nil { + return err + } + esf.IsSubjectCaseSensitive = &isSubjectCaseSensitive + } + case "advancedFilters": + if v != nil { + advancedFilters, err := unmarshalBasicAdvancedFilterArray(*v) + if err != nil { + return err + } + esf.AdvancedFilters = &advancedFilters + } + } + } + + return nil +} + +// EventSubscriptionFullURL full endpoint url of an event subscription +type EventSubscriptionFullURL struct { + autorest.Response `json:"-"` + // EndpointURL - The URL that represents the endpoint of the destination of an event subscription. + EndpointURL *string `json:"endpointUrl,omitempty"` +} + +// EventSubscriptionIdentity the identity information with the event subscription. +type EventSubscriptionIdentity struct { + // Type - The type of managed identity used. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user-assigned identities. The type 'None' will remove any identity. Possible values include: 'SystemAssigned', 'UserAssigned' + Type EventSubscriptionIdentityType `json:"type,omitempty"` + // UserAssignedIdentity - The user identity associated with the resource. + UserAssignedIdentity *string `json:"userAssignedIdentity,omitempty"` +} + +// EventSubscriptionProperties properties of the Event Subscription. +type EventSubscriptionProperties struct { + // Topic - READ-ONLY; Name of the topic of the event subscription. + Topic *string `json:"topic,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the event subscription. Possible values include: 'EventSubscriptionProvisioningStateCreating', 'EventSubscriptionProvisioningStateUpdating', 'EventSubscriptionProvisioningStateDeleting', 'EventSubscriptionProvisioningStateSucceeded', 'EventSubscriptionProvisioningStateCanceled', 'EventSubscriptionProvisioningStateFailed', 'EventSubscriptionProvisioningStateAwaitingManualAction' + ProvisioningState EventSubscriptionProvisioningState `json:"provisioningState,omitempty"` + // Destination - Information about the destination where events have to be delivered for the event subscription. + // Uses Azure Event Grid's identity to acquire the authentication tokens being used during delivery / dead-lettering. + Destination BasicEventSubscriptionDestination `json:"destination,omitempty"` + // DeliveryWithResourceIdentity - Information about the destination where events have to be delivered for the event subscription. + // Uses the managed identity setup on the parent resource (namely, topic or domain) to acquire the authentication tokens being used during delivery / dead-lettering. + DeliveryWithResourceIdentity *DeliveryWithResourceIdentity `json:"deliveryWithResourceIdentity,omitempty"` + // Filter - Information about the filter for the event subscription. + Filter *EventSubscriptionFilter `json:"filter,omitempty"` + // Labels - List of user defined labels. + Labels *[]string `json:"labels,omitempty"` + // ExpirationTimeUtc - Expiration time of the event subscription. + ExpirationTimeUtc *date.Time `json:"expirationTimeUtc,omitempty"` + // EventDeliverySchema - The event delivery schema for the event subscription. Possible values include: 'EventGridSchema', 'CustomInputSchema', 'CloudEventSchemaV10' + EventDeliverySchema EventDeliverySchema `json:"eventDeliverySchema,omitempty"` + // RetryPolicy - The retry policy for events. This can be used to configure maximum number of delivery attempts and time to live for events. + RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` + // DeadLetterDestination - The dead letter destination of the event subscription. Any event that cannot be delivered to its' destination is sent to the dead letter destination. + // Uses Azure Event Grid's identity to acquire the authentication tokens being used during delivery / dead-lettering. + DeadLetterDestination BasicDeadLetterDestination `json:"deadLetterDestination,omitempty"` + // DeadLetterWithResourceIdentity - The dead letter destination of the event subscription. Any event that cannot be delivered to its' destination is sent to the dead letter destination. + // Uses the managed identity setup on the parent resource (namely, topic or domain) to acquire the authentication tokens being used during delivery / dead-lettering. + DeadLetterWithResourceIdentity *DeadLetterWithResourceIdentity `json:"deadLetterWithResourceIdentity,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for EventSubscriptionProperties struct. +func (esp *EventSubscriptionProperties) 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 "topic": + if v != nil { + var topic string + err = json.Unmarshal(*v, &topic) + if err != nil { + return err + } + esp.Topic = &topic + } + case "provisioningState": + if v != nil { + var provisioningState EventSubscriptionProvisioningState + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + esp.ProvisioningState = provisioningState + } + case "destination": + if v != nil { + destination, err := unmarshalBasicEventSubscriptionDestination(*v) + if err != nil { + return err + } + esp.Destination = destination + } + case "deliveryWithResourceIdentity": + if v != nil { + var deliveryWithResourceIdentity DeliveryWithResourceIdentity + err = json.Unmarshal(*v, &deliveryWithResourceIdentity) + if err != nil { + return err + } + esp.DeliveryWithResourceIdentity = &deliveryWithResourceIdentity + } + case "filter": + if v != nil { + var filter EventSubscriptionFilter + err = json.Unmarshal(*v, &filter) + if err != nil { + return err + } + esp.Filter = &filter + } + case "labels": + if v != nil { + var labels []string + err = json.Unmarshal(*v, &labels) + if err != nil { + return err + } + esp.Labels = &labels + } + case "expirationTimeUtc": + if v != nil { + var expirationTimeUtc date.Time + err = json.Unmarshal(*v, &expirationTimeUtc) + if err != nil { + return err + } + esp.ExpirationTimeUtc = &expirationTimeUtc + } + case "eventDeliverySchema": + if v != nil { + var eventDeliverySchema EventDeliverySchema + err = json.Unmarshal(*v, &eventDeliverySchema) + if err != nil { + return err + } + esp.EventDeliverySchema = eventDeliverySchema + } + case "retryPolicy": + if v != nil { + var retryPolicy RetryPolicy + err = json.Unmarshal(*v, &retryPolicy) + if err != nil { + return err + } + esp.RetryPolicy = &retryPolicy + } + case "deadLetterDestination": + if v != nil { + deadLetterDestination, err := unmarshalBasicDeadLetterDestination(*v) + if err != nil { + return err + } + esp.DeadLetterDestination = deadLetterDestination + } + case "deadLetterWithResourceIdentity": + if v != nil { + var deadLetterWithResourceIdentity DeadLetterWithResourceIdentity + err = json.Unmarshal(*v, &deadLetterWithResourceIdentity) + if err != nil { + return err + } + esp.DeadLetterWithResourceIdentity = &deadLetterWithResourceIdentity + } + } + } + + return nil +} + +// EventSubscriptionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type EventSubscriptionsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EventSubscriptionsCreateOrUpdateFuture) Result(client EventSubscriptionsClient) (es EventSubscription, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.EventSubscriptionsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { + es, err = client.CreateOrUpdateResponder(es.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsCreateOrUpdateFuture", "Result", es.Response.Response, "Failure responding to request") + } + } + return +} + +// EventSubscriptionsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type EventSubscriptionsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EventSubscriptionsDeleteFuture) Result(client EventSubscriptionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.EventSubscriptionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// EventSubscriptionsListResult result of the List EventSubscriptions operation +type EventSubscriptionsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of EventSubscriptions + Value *[]EventSubscription `json:"value,omitempty"` + // NextLink - A link for the next page of event subscriptions + NextLink *string `json:"nextLink,omitempty"` +} + +// EventSubscriptionsListResultIterator provides access to a complete listing of EventSubscription values. +type EventSubscriptionsListResultIterator struct { + i int + page EventSubscriptionsListResultPage +} + +// 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 *EventSubscriptionsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsListResultIterator.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 *EventSubscriptionsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter EventSubscriptionsListResultIterator) 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 EventSubscriptionsListResultIterator) Response() EventSubscriptionsListResult { + 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 EventSubscriptionsListResultIterator) Value() EventSubscription { + if !iter.page.NotDone() { + return EventSubscription{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the EventSubscriptionsListResultIterator type. +func NewEventSubscriptionsListResultIterator(page EventSubscriptionsListResultPage) EventSubscriptionsListResultIterator { + return EventSubscriptionsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (eslr EventSubscriptionsListResult) IsEmpty() bool { + return eslr.Value == nil || len(*eslr.Value) == 0 +} + +// eventSubscriptionsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (eslr EventSubscriptionsListResult) eventSubscriptionsListResultPreparer(ctx context.Context) (*http.Request, error) { + if eslr.NextLink == nil || len(to.String(eslr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(eslr.NextLink))) +} + +// EventSubscriptionsListResultPage contains a page of EventSubscription values. +type EventSubscriptionsListResultPage struct { + fn func(context.Context, EventSubscriptionsListResult) (EventSubscriptionsListResult, error) + eslr EventSubscriptionsListResult +} + +// 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 *EventSubscriptionsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EventSubscriptionsListResultPage.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.eslr) + if err != nil { + return err + } + page.eslr = 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 *EventSubscriptionsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page EventSubscriptionsListResultPage) NotDone() bool { + return !page.eslr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page EventSubscriptionsListResultPage) Response() EventSubscriptionsListResult { + return page.eslr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page EventSubscriptionsListResultPage) Values() []EventSubscription { + if page.eslr.IsEmpty() { + return nil + } + return *page.eslr.Value +} + +// Creates a new instance of the EventSubscriptionsListResultPage type. +func NewEventSubscriptionsListResultPage(getNextPage func(context.Context, EventSubscriptionsListResult) (EventSubscriptionsListResult, error)) EventSubscriptionsListResultPage { + return EventSubscriptionsListResultPage{fn: getNextPage} +} + +// EventSubscriptionsUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type EventSubscriptionsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EventSubscriptionsUpdateFuture) Result(client EventSubscriptionsClient) (es EventSubscription, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.EventSubscriptionsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { + es, err = client.UpdateResponder(es.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.EventSubscriptionsUpdateFuture", "Result", es.Response.Response, "Failure responding to request") + } + } + return +} + +// EventSubscriptionUpdateParameters properties of the Event Subscription update. +type EventSubscriptionUpdateParameters struct { + // Destination - Information about the destination where events have to be delivered for the event subscription. + // Uses Azure Event Grid's identity to acquire the authentication tokens being used during delivery / dead-lettering. + Destination BasicEventSubscriptionDestination `json:"destination,omitempty"` + // DeliveryWithResourceIdentity - Information about the destination where events have to be delivered for the event subscription. + // Uses the managed identity setup on the parent resource (topic / domain) to acquire the authentication tokens being used during delivery / dead-lettering. + DeliveryWithResourceIdentity *DeliveryWithResourceIdentity `json:"deliveryWithResourceIdentity,omitempty"` + // Filter - Information about the filter for the event subscription. + Filter *EventSubscriptionFilter `json:"filter,omitempty"` + // Labels - List of user defined labels. + Labels *[]string `json:"labels,omitempty"` + // ExpirationTimeUtc - Information about the expiration time for the event subscription. + ExpirationTimeUtc *date.Time `json:"expirationTimeUtc,omitempty"` + // EventDeliverySchema - The event delivery schema for the event subscription. Possible values include: 'EventGridSchema', 'CustomInputSchema', 'CloudEventSchemaV10' + EventDeliverySchema EventDeliverySchema `json:"eventDeliverySchema,omitempty"` + // RetryPolicy - The retry policy for events. This can be used to configure maximum number of delivery attempts and time to live for events. + RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` + // DeadLetterDestination - The dead letter destination of the event subscription. Any event that cannot be delivered to its' destination is sent to the dead letter destination. + // Uses Azure Event Grid's identity to acquire the authentication tokens being used during delivery / dead-lettering. + DeadLetterDestination BasicDeadLetterDestination `json:"deadLetterDestination,omitempty"` + // DeadLetterWithResourceIdentity - The dead letter destination of the event subscription. Any event that cannot be delivered to its' destination is sent to the dead letter destination. + // Uses the managed identity setup on the parent resource (topic / domain) to acquire the authentication tokens being used during delivery / dead-lettering. + DeadLetterWithResourceIdentity *DeadLetterWithResourceIdentity `json:"deadLetterWithResourceIdentity,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for EventSubscriptionUpdateParameters struct. +func (esup *EventSubscriptionUpdateParameters) 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 "destination": + if v != nil { + destination, err := unmarshalBasicEventSubscriptionDestination(*v) + if err != nil { + return err + } + esup.Destination = destination + } + case "deliveryWithResourceIdentity": + if v != nil { + var deliveryWithResourceIdentity DeliveryWithResourceIdentity + err = json.Unmarshal(*v, &deliveryWithResourceIdentity) + if err != nil { + return err + } + esup.DeliveryWithResourceIdentity = &deliveryWithResourceIdentity + } + case "filter": + if v != nil { + var filter EventSubscriptionFilter + err = json.Unmarshal(*v, &filter) + if err != nil { + return err + } + esup.Filter = &filter + } + case "labels": + if v != nil { + var labels []string + err = json.Unmarshal(*v, &labels) + if err != nil { + return err + } + esup.Labels = &labels + } + case "expirationTimeUtc": + if v != nil { + var expirationTimeUtc date.Time + err = json.Unmarshal(*v, &expirationTimeUtc) + if err != nil { + return err + } + esup.ExpirationTimeUtc = &expirationTimeUtc + } + case "eventDeliverySchema": + if v != nil { + var eventDeliverySchema EventDeliverySchema + err = json.Unmarshal(*v, &eventDeliverySchema) + if err != nil { + return err + } + esup.EventDeliverySchema = eventDeliverySchema + } + case "retryPolicy": + if v != nil { + var retryPolicy RetryPolicy + err = json.Unmarshal(*v, &retryPolicy) + if err != nil { + return err + } + esup.RetryPolicy = &retryPolicy + } + case "deadLetterDestination": + if v != nil { + deadLetterDestination, err := unmarshalBasicDeadLetterDestination(*v) + if err != nil { + return err + } + esup.DeadLetterDestination = deadLetterDestination + } + case "deadLetterWithResourceIdentity": + if v != nil { + var deadLetterWithResourceIdentity DeadLetterWithResourceIdentity + err = json.Unmarshal(*v, &deadLetterWithResourceIdentity) + if err != nil { + return err + } + esup.DeadLetterWithResourceIdentity = &deadLetterWithResourceIdentity + } + } + } + + return nil +} + +// EventType event Type for a subject under a topic +type EventType struct { + // EventTypeProperties - Properties of the event type. + *EventTypeProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for EventType. +func (et EventType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if et.EventTypeProperties != nil { + objectMap["properties"] = et.EventTypeProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for EventType struct. +func (et *EventType) 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 eventTypeProperties EventTypeProperties + err = json.Unmarshal(*v, &eventTypeProperties) + if err != nil { + return err + } + et.EventTypeProperties = &eventTypeProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + et.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + et.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + et.Type = &typeVar + } + } + } + + return nil +} + +// EventTypeProperties properties of the event type +type EventTypeProperties struct { + // DisplayName - Display name of the event type. + DisplayName *string `json:"displayName,omitempty"` + // Description - Description of the event type. + Description *string `json:"description,omitempty"` + // SchemaURL - Url of the schema for this event type. + SchemaURL *string `json:"schemaUrl,omitempty"` + // IsInDefaultSet - IsInDefaultSet flag of the event type. + IsInDefaultSet *bool `json:"isInDefaultSet,omitempty"` +} + +// EventTypesListResult result of the List Event Types operation +type EventTypesListResult struct { + autorest.Response `json:"-"` + // Value - A collection of event types + Value *[]EventType `json:"value,omitempty"` +} + +// ExtensionTopic event grid Extension Topic. This is used for getting Event Grid related metrics for Azure +// resources. +type ExtensionTopic struct { + autorest.Response `json:"-"` + // ExtensionTopicProperties - Properties of the extension topic + *ExtensionTopicProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ExtensionTopic. +func (et ExtensionTopic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if et.ExtensionTopicProperties != nil { + objectMap["properties"] = et.ExtensionTopicProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ExtensionTopic struct. +func (et *ExtensionTopic) 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 extensionTopicProperties ExtensionTopicProperties + err = json.Unmarshal(*v, &extensionTopicProperties) + if err != nil { + return err + } + et.ExtensionTopicProperties = &extensionTopicProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + et.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + et.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + et.Type = &typeVar + } + } + } + + return nil +} + +// ExtensionTopicProperties properties of the Extension Topic +type ExtensionTopicProperties struct { + // Description - Description of the extension topic. + Description *string `json:"description,omitempty"` + // SystemTopic - System topic resource id which is mapped to the source. + SystemTopic *string `json:"systemTopic,omitempty"` +} + +// HybridConnectionEventSubscriptionDestination information about the HybridConnection destination for an +// event subscription. +type HybridConnectionEventSubscriptionDestination struct { + // HybridConnectionEventSubscriptionDestinationProperties - Hybrid connection Properties of the event subscription destination. + *HybridConnectionEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + hcesd.EndpointType = EndpointTypeHybridConnection + objectMap := make(map[string]interface{}) + if hcesd.HybridConnectionEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = hcesd.HybridConnectionEventSubscriptionDestinationProperties + } + if hcesd.EndpointType != "" { + objectMap["endpointType"] = hcesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return &hcesd, true +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for HybridConnectionEventSubscriptionDestination. +func (hcesd HybridConnectionEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &hcesd, true +} + +// UnmarshalJSON is the custom unmarshaler for HybridConnectionEventSubscriptionDestination struct. +func (hcesd *HybridConnectionEventSubscriptionDestination) 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 hybridConnectionEventSubscriptionDestinationProperties HybridConnectionEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &hybridConnectionEventSubscriptionDestinationProperties) + if err != nil { + return err + } + hcesd.HybridConnectionEventSubscriptionDestinationProperties = &hybridConnectionEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + hcesd.EndpointType = endpointType + } + } + } + + return nil +} + +// HybridConnectionEventSubscriptionDestinationProperties the properties for a hybrid connection +// destination. +type HybridConnectionEventSubscriptionDestinationProperties struct { + // ResourceID - The Azure Resource ID of an hybrid connection that is the destination of an event subscription. + ResourceID *string `json:"resourceId,omitempty"` +} + +// IdentityInfo the identity information for the resource. +type IdentityInfo struct { + // Type - The type of managed identity used. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user-assigned identities. The type 'None' will remove any identity. Possible values include: 'IdentityTypeNone', 'IdentityTypeSystemAssigned', 'IdentityTypeUserAssigned', 'IdentityTypeSystemAssignedUserAssigned' + Type IdentityType `json:"type,omitempty"` + // PrincipalID - The principal ID of resource identity. + PrincipalID *string `json:"principalId,omitempty"` + // TenantID - The tenant ID of resource. + TenantID *string `json:"tenantId,omitempty"` + // UserAssignedIdentities - The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + // This property is currently not used and reserved for future usage. + UserAssignedIdentities map[string]*UserIdentityProperties `json:"userAssignedIdentities"` +} + +// MarshalJSON is the custom marshaler for IdentityInfo. +func (ii IdentityInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ii.Type != "" { + objectMap["type"] = ii.Type + } + if ii.PrincipalID != nil { + objectMap["principalId"] = ii.PrincipalID + } + if ii.TenantID != nil { + objectMap["tenantId"] = ii.TenantID + } + if ii.UserAssignedIdentities != nil { + objectMap["userAssignedIdentities"] = ii.UserAssignedIdentities + } + return json.Marshal(objectMap) +} + +// InboundIPRule ... +type InboundIPRule struct { + // IPMask - IP Address in CIDR notation e.g., 10.0.0.0/8. + IPMask *string `json:"ipMask,omitempty"` + // Action - Action to perform based on the match or no match of the IpMask. Possible values include: 'Allow' + Action IPActionType `json:"action,omitempty"` +} + +// BasicInputSchemaMapping by default, Event Grid expects events to be in the Event Grid event schema. Specifying an +// input schema mapping enables publishing to Event Grid using a custom input schema. Currently, the only supported +// type of InputSchemaMapping is 'JsonInputSchemaMapping'. +type BasicInputSchemaMapping interface { + AsJSONInputSchemaMapping() (*JSONInputSchemaMapping, bool) + AsInputSchemaMapping() (*InputSchemaMapping, bool) +} + +// InputSchemaMapping by default, Event Grid expects events to be in the Event Grid event schema. Specifying an +// input schema mapping enables publishing to Event Grid using a custom input schema. Currently, the only +// supported type of InputSchemaMapping is 'JsonInputSchemaMapping'. +type InputSchemaMapping struct { + // InputSchemaMappingType - Possible values include: 'InputSchemaMappingTypeInputSchemaMapping', 'InputSchemaMappingTypeJSON' + InputSchemaMappingType InputSchemaMappingType `json:"inputSchemaMappingType,omitempty"` +} + +func unmarshalBasicInputSchemaMapping(body []byte) (BasicInputSchemaMapping, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["inputSchemaMappingType"] { + case string(InputSchemaMappingTypeJSON): + var jism JSONInputSchemaMapping + err := json.Unmarshal(body, &jism) + return jism, err + default: + var ism InputSchemaMapping + err := json.Unmarshal(body, &ism) + return ism, err + } +} +func unmarshalBasicInputSchemaMappingArray(body []byte) ([]BasicInputSchemaMapping, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + ismArray := make([]BasicInputSchemaMapping, len(rawMessages)) + + for index, rawMessage := range rawMessages { + ism, err := unmarshalBasicInputSchemaMapping(*rawMessage) + if err != nil { + return nil, err + } + ismArray[index] = ism + } + return ismArray, nil +} + +// MarshalJSON is the custom marshaler for InputSchemaMapping. +func (ism InputSchemaMapping) MarshalJSON() ([]byte, error) { + ism.InputSchemaMappingType = InputSchemaMappingTypeInputSchemaMapping + objectMap := make(map[string]interface{}) + if ism.InputSchemaMappingType != "" { + objectMap["inputSchemaMappingType"] = ism.InputSchemaMappingType + } + return json.Marshal(objectMap) +} + +// AsJSONInputSchemaMapping is the BasicInputSchemaMapping implementation for InputSchemaMapping. +func (ism InputSchemaMapping) AsJSONInputSchemaMapping() (*JSONInputSchemaMapping, bool) { + return nil, false +} + +// AsInputSchemaMapping is the BasicInputSchemaMapping implementation for InputSchemaMapping. +func (ism InputSchemaMapping) AsInputSchemaMapping() (*InputSchemaMapping, bool) { + return &ism, true +} + +// AsBasicInputSchemaMapping is the BasicInputSchemaMapping implementation for InputSchemaMapping. +func (ism InputSchemaMapping) AsBasicInputSchemaMapping() (BasicInputSchemaMapping, bool) { + return &ism, true +} + +// JSONField this is used to express the source of an input schema mapping for a single target field in the +// Event Grid Event schema. This is currently used in the mappings for the 'id', 'topic' and 'eventtime' +// properties. This represents a field in the input event schema. +type JSONField struct { + // SourceField - Name of a field in the input event schema that's to be used as the source of a mapping. + SourceField *string `json:"sourceField,omitempty"` +} + +// JSONFieldWithDefault this is used to express the source of an input schema mapping for a single target +// field +// in the Event Grid Event schema. This is currently used in the mappings for the 'subject', +// 'eventtype' and 'dataversion' properties. This represents a field in the input event schema +// along with a default value to be used, and at least one of these two properties should be provided. +type JSONFieldWithDefault struct { + // SourceField - Name of a field in the input event schema that's to be used as the source of a mapping. + SourceField *string `json:"sourceField,omitempty"` + // DefaultValue - The default value to be used for mapping when a SourceField is not provided or if there's no property with the specified name in the published JSON event payload. + DefaultValue *string `json:"defaultValue,omitempty"` +} + +// JSONInputSchemaMapping this enables publishing to Event Grid using a custom input schema. This can be +// used to map properties from a custom input JSON schema to the Event Grid event schema. +type JSONInputSchemaMapping struct { + // JSONInputSchemaMappingProperties - JSON Properties of the input schema mapping + *JSONInputSchemaMappingProperties `json:"properties,omitempty"` + // InputSchemaMappingType - Possible values include: 'InputSchemaMappingTypeInputSchemaMapping', 'InputSchemaMappingTypeJSON' + InputSchemaMappingType InputSchemaMappingType `json:"inputSchemaMappingType,omitempty"` +} + +// MarshalJSON is the custom marshaler for JSONInputSchemaMapping. +func (jism JSONInputSchemaMapping) MarshalJSON() ([]byte, error) { + jism.InputSchemaMappingType = InputSchemaMappingTypeJSON + objectMap := make(map[string]interface{}) + if jism.JSONInputSchemaMappingProperties != nil { + objectMap["properties"] = jism.JSONInputSchemaMappingProperties + } + if jism.InputSchemaMappingType != "" { + objectMap["inputSchemaMappingType"] = jism.InputSchemaMappingType + } + return json.Marshal(objectMap) +} + +// AsJSONInputSchemaMapping is the BasicInputSchemaMapping implementation for JSONInputSchemaMapping. +func (jism JSONInputSchemaMapping) AsJSONInputSchemaMapping() (*JSONInputSchemaMapping, bool) { + return &jism, true +} + +// AsInputSchemaMapping is the BasicInputSchemaMapping implementation for JSONInputSchemaMapping. +func (jism JSONInputSchemaMapping) AsInputSchemaMapping() (*InputSchemaMapping, bool) { + return nil, false +} + +// AsBasicInputSchemaMapping is the BasicInputSchemaMapping implementation for JSONInputSchemaMapping. +func (jism JSONInputSchemaMapping) AsBasicInputSchemaMapping() (BasicInputSchemaMapping, bool) { + return &jism, true +} + +// UnmarshalJSON is the custom unmarshaler for JSONInputSchemaMapping struct. +func (jism *JSONInputSchemaMapping) 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 JSONInputSchemaMappingProperties JSONInputSchemaMappingProperties + err = json.Unmarshal(*v, &JSONInputSchemaMappingProperties) + if err != nil { + return err + } + jism.JSONInputSchemaMappingProperties = &JSONInputSchemaMappingProperties + } + case "inputSchemaMappingType": + if v != nil { + var inputSchemaMappingType InputSchemaMappingType + err = json.Unmarshal(*v, &inputSchemaMappingType) + if err != nil { + return err + } + jism.InputSchemaMappingType = inputSchemaMappingType + } + } + } + + return nil +} + +// JSONInputSchemaMappingProperties this can be used to map properties of a source schema (or default +// values, for certain supported properties) to properties of the EventGridEvent schema. +type JSONInputSchemaMappingProperties struct { + // ID - The mapping information for the Id property of the Event Grid Event. + ID *JSONField `json:"id,omitempty"` + // Topic - The mapping information for the Topic property of the Event Grid Event. + Topic *JSONField `json:"topic,omitempty"` + // EventTime - The mapping information for the EventTime property of the Event Grid Event. + EventTime *JSONField `json:"eventTime,omitempty"` + // EventType - The mapping information for the EventType property of the Event Grid Event. + EventType *JSONFieldWithDefault `json:"eventType,omitempty"` + // Subject - The mapping information for the Subject property of the Event Grid Event. + Subject *JSONFieldWithDefault `json:"subject,omitempty"` + // DataVersion - The mapping information for the DataVersion property of the Event Grid Event. + DataVersion *JSONFieldWithDefault `json:"dataVersion,omitempty"` +} + +// NumberGreaterThanAdvancedFilter numberGreaterThan Advanced Filter. +type NumberGreaterThanAdvancedFilter struct { + // Value - The filter value. + Value *float64 `json:"value,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) MarshalJSON() ([]byte, error) { + ngtaf.OperatorType = OperatorTypeNumberGreaterThan + objectMap := make(map[string]interface{}) + if ngtaf.Value != nil { + objectMap["value"] = ngtaf.Value + } + if ngtaf.Key != nil { + objectMap["key"] = ngtaf.Key + } + if ngtaf.OperatorType != "" { + objectMap["operatorType"] = ngtaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return &ngtaf, true +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanAdvancedFilter. +func (ngtaf NumberGreaterThanAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &ngtaf, true +} + +// NumberGreaterThanOrEqualsAdvancedFilter numberGreaterThanOrEquals Advanced Filter. +type NumberGreaterThanOrEqualsAdvancedFilter struct { + // Value - The filter value. + Value *float64 `json:"value,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) MarshalJSON() ([]byte, error) { + ngtoeaf.OperatorType = OperatorTypeNumberGreaterThanOrEquals + objectMap := make(map[string]interface{}) + if ngtoeaf.Value != nil { + objectMap["value"] = ngtoeaf.Value + } + if ngtoeaf.Key != nil { + objectMap["key"] = ngtoeaf.Key + } + if ngtoeaf.OperatorType != "" { + objectMap["operatorType"] = ngtoeaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return &ngtoeaf, true +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberGreaterThanOrEqualsAdvancedFilter. +func (ngtoeaf NumberGreaterThanOrEqualsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &ngtoeaf, true +} + +// NumberInAdvancedFilter numberIn Advanced Filter. +type NumberInAdvancedFilter struct { + // Values - The set of filter values. + Values *[]float64 `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) MarshalJSON() ([]byte, error) { + niaf.OperatorType = OperatorTypeNumberIn + objectMap := make(map[string]interface{}) + if niaf.Values != nil { + objectMap["values"] = niaf.Values + } + if niaf.Key != nil { + objectMap["key"] = niaf.Key + } + if niaf.OperatorType != "" { + objectMap["operatorType"] = niaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return &niaf, true +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberInAdvancedFilter. +func (niaf NumberInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &niaf, true +} + +// NumberLessThanAdvancedFilter numberLessThan Advanced Filter. +type NumberLessThanAdvancedFilter struct { + // Value - The filter value. + Value *float64 `json:"value,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) MarshalJSON() ([]byte, error) { + nltaf.OperatorType = OperatorTypeNumberLessThan + objectMap := make(map[string]interface{}) + if nltaf.Value != nil { + objectMap["value"] = nltaf.Value + } + if nltaf.Key != nil { + objectMap["key"] = nltaf.Key + } + if nltaf.OperatorType != "" { + objectMap["operatorType"] = nltaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return &nltaf, true +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanAdvancedFilter. +func (nltaf NumberLessThanAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &nltaf, true +} + +// NumberLessThanOrEqualsAdvancedFilter numberLessThanOrEquals Advanced Filter. +type NumberLessThanOrEqualsAdvancedFilter struct { + // Value - The filter value. + Value *float64 `json:"value,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) MarshalJSON() ([]byte, error) { + nltoeaf.OperatorType = OperatorTypeNumberLessThanOrEquals + objectMap := make(map[string]interface{}) + if nltoeaf.Value != nil { + objectMap["value"] = nltoeaf.Value + } + if nltoeaf.Key != nil { + objectMap["key"] = nltoeaf.Key + } + if nltoeaf.OperatorType != "" { + objectMap["operatorType"] = nltoeaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return &nltoeaf, true +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberLessThanOrEqualsAdvancedFilter. +func (nltoeaf NumberLessThanOrEqualsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &nltoeaf, true +} + +// NumberNotInAdvancedFilter numberNotIn Advanced Filter. +type NumberNotInAdvancedFilter struct { + // Values - The set of filter values. + Values *[]float64 `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) MarshalJSON() ([]byte, error) { + nniaf.OperatorType = OperatorTypeNumberNotIn + objectMap := make(map[string]interface{}) + if nniaf.Values != nil { + objectMap["values"] = nniaf.Values + } + if nniaf.Key != nil { + objectMap["key"] = nniaf.Key + } + if nniaf.OperatorType != "" { + objectMap["operatorType"] = nniaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return &nniaf, true +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for NumberNotInAdvancedFilter. +func (nniaf NumberNotInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &nniaf, true +} + +// Operation represents an operation returned by the GetOperations request +type Operation struct { + // Name - Name of the operation + Name *string `json:"name,omitempty"` + // Display - Display name of the operation + Display *OperationInfo `json:"display,omitempty"` + // Origin - Origin of the operation + Origin *string `json:"origin,omitempty"` + // Properties - Properties of the operation + Properties interface{} `json:"properties,omitempty"` +} + +// OperationInfo information about an operation +type OperationInfo struct { + // Provider - Name of the provider + Provider *string `json:"provider,omitempty"` + // Resource - Name of the resource type + Resource *string `json:"resource,omitempty"` + // Operation - Name of the operation + Operation *string `json:"operation,omitempty"` + // Description - Description of the operation + Description *string `json:"description,omitempty"` +} + +// OperationsListResult result of the List Operations operation +type OperationsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of operations + Value *[]Operation `json:"value,omitempty"` +} + +// PartnerNamespace eventGrid Partner Namespace. +type PartnerNamespace struct { + autorest.Response `json:"-"` + // PartnerNamespaceProperties - Properties of the partner namespace. + *PartnerNamespaceProperties `json:"properties,omitempty"` + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PartnerNamespace. +func (pn PartnerNamespace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pn.PartnerNamespaceProperties != nil { + objectMap["properties"] = pn.PartnerNamespaceProperties + } + if pn.Location != nil { + objectMap["location"] = pn.Location + } + if pn.Tags != nil { + objectMap["tags"] = pn.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PartnerNamespace struct. +func (pn *PartnerNamespace) 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 partnerNamespaceProperties PartnerNamespaceProperties + err = json.Unmarshal(*v, &partnerNamespaceProperties) + if err != nil { + return err + } + pn.PartnerNamespaceProperties = &partnerNamespaceProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + pn.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + pn.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + pn.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + pn.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + pn.Type = &typeVar + } + } + } + + return nil +} + +// PartnerNamespaceProperties properties of the partner namespace. +type PartnerNamespaceProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state of the partner namespace. Possible values include: 'PartnerNamespaceProvisioningStateCreating', 'PartnerNamespaceProvisioningStateUpdating', 'PartnerNamespaceProvisioningStateDeleting', 'PartnerNamespaceProvisioningStateSucceeded', 'PartnerNamespaceProvisioningStateCanceled', 'PartnerNamespaceProvisioningStateFailed' + ProvisioningState PartnerNamespaceProvisioningState `json:"provisioningState,omitempty"` + // PartnerRegistrationFullyQualifiedID - The fully qualified ARM Id of the partner registration that should be associated with this partner namespace. This takes the following format: + // /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerRegistrations/{partnerRegistrationName}. + PartnerRegistrationFullyQualifiedID *string `json:"partnerRegistrationFullyQualifiedId,omitempty"` + // Endpoint - READ-ONLY; Endpoint for the partner namespace. + Endpoint *string `json:"endpoint,omitempty"` +} + +// PartnerNamespaceRegenerateKeyRequest partnerNamespace regenerate shared access key request. +type PartnerNamespaceRegenerateKeyRequest struct { + // KeyName - Key name to regenerate (key1 or key2). + KeyName *string `json:"keyName,omitempty"` +} + +// PartnerNamespacesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type PartnerNamespacesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerNamespacesCreateOrUpdateFuture) Result(client PartnerNamespacesClient) (pn PartnerNamespace, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerNamespacesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if pn.Response.Response, err = future.GetResult(sender); err == nil && pn.Response.Response.StatusCode != http.StatusNoContent { + pn, err = client.CreateOrUpdateResponder(pn.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesCreateOrUpdateFuture", "Result", pn.Response.Response, "Failure responding to request") + } + } + return +} + +// PartnerNamespacesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type PartnerNamespacesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerNamespacesDeleteFuture) Result(client PartnerNamespacesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerNamespacesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PartnerNamespaceSharedAccessKeys shared access keys of the partner namespace. +type PartnerNamespaceSharedAccessKeys struct { + autorest.Response `json:"-"` + // Key1 - Shared access key1 for the partner namespace. + Key1 *string `json:"key1,omitempty"` + // Key2 - Shared access key2 for the partner namespace. + Key2 *string `json:"key2,omitempty"` +} + +// PartnerNamespacesListResult result of the List Partner Namespaces operation +type PartnerNamespacesListResult struct { + autorest.Response `json:"-"` + // Value - A collection of partner namespaces. + Value *[]PartnerNamespace `json:"value,omitempty"` + // NextLink - A link for the next page of partner namespaces. + NextLink *string `json:"nextLink,omitempty"` +} + +// PartnerNamespacesListResultIterator provides access to a complete listing of PartnerNamespace values. +type PartnerNamespacesListResultIterator struct { + i int + page PartnerNamespacesListResultPage +} + +// 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 *PartnerNamespacesListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesListResultIterator.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 *PartnerNamespacesListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PartnerNamespacesListResultIterator) 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 PartnerNamespacesListResultIterator) Response() PartnerNamespacesListResult { + 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 PartnerNamespacesListResultIterator) Value() PartnerNamespace { + if !iter.page.NotDone() { + return PartnerNamespace{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the PartnerNamespacesListResultIterator type. +func NewPartnerNamespacesListResultIterator(page PartnerNamespacesListResultPage) PartnerNamespacesListResultIterator { + return PartnerNamespacesListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (pnlr PartnerNamespacesListResult) IsEmpty() bool { + return pnlr.Value == nil || len(*pnlr.Value) == 0 +} + +// partnerNamespacesListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (pnlr PartnerNamespacesListResult) partnerNamespacesListResultPreparer(ctx context.Context) (*http.Request, error) { + if pnlr.NextLink == nil || len(to.String(pnlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(pnlr.NextLink))) +} + +// PartnerNamespacesListResultPage contains a page of PartnerNamespace values. +type PartnerNamespacesListResultPage struct { + fn func(context.Context, PartnerNamespacesListResult) (PartnerNamespacesListResult, error) + pnlr PartnerNamespacesListResult +} + +// 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 *PartnerNamespacesListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesListResultPage.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.pnlr) + if err != nil { + return err + } + page.pnlr = 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 *PartnerNamespacesListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PartnerNamespacesListResultPage) NotDone() bool { + return !page.pnlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PartnerNamespacesListResultPage) Response() PartnerNamespacesListResult { + return page.pnlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PartnerNamespacesListResultPage) Values() []PartnerNamespace { + if page.pnlr.IsEmpty() { + return nil + } + return *page.pnlr.Value +} + +// Creates a new instance of the PartnerNamespacesListResultPage type. +func NewPartnerNamespacesListResultPage(getNextPage func(context.Context, PartnerNamespacesListResult) (PartnerNamespacesListResult, error)) PartnerNamespacesListResultPage { + return PartnerNamespacesListResultPage{fn: getNextPage} +} + +// PartnerNamespacesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type PartnerNamespacesUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerNamespacesUpdateFuture) Result(client PartnerNamespacesClient) (pn PartnerNamespace, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerNamespacesUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if pn.Response.Response, err = future.GetResult(sender); err == nil && pn.Response.Response.StatusCode != http.StatusNoContent { + pn, err = client.UpdateResponder(pn.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesUpdateFuture", "Result", pn.Response.Response, "Failure responding to request") + } + } + return +} + +// PartnerNamespaceUpdateParameters properties of the PartnerNamespace update. +type PartnerNamespaceUpdateParameters struct { + // Tags - Tags of the partner namespace. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for PartnerNamespaceUpdateParameters. +func (pnup PartnerNamespaceUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pnup.Tags != nil { + objectMap["tags"] = pnup.Tags + } + return json.Marshal(objectMap) +} + +// PartnerRegistration information about a partner registration. +type PartnerRegistration struct { + autorest.Response `json:"-"` + // PartnerRegistrationProperties - Properties of the partner registration. + *PartnerRegistrationProperties `json:"properties,omitempty"` + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PartnerRegistration. +func (pr PartnerRegistration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pr.PartnerRegistrationProperties != nil { + objectMap["properties"] = pr.PartnerRegistrationProperties + } + if pr.Location != nil { + objectMap["location"] = pr.Location + } + if pr.Tags != nil { + objectMap["tags"] = pr.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PartnerRegistration struct. +func (pr *PartnerRegistration) 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 partnerRegistrationProperties PartnerRegistrationProperties + err = json.Unmarshal(*v, &partnerRegistrationProperties) + if err != nil { + return err + } + pr.PartnerRegistrationProperties = &partnerRegistrationProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + pr.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + pr.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + pr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + pr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + pr.Type = &typeVar + } + } + } + + return nil +} + +// PartnerRegistrationEventTypesListResult result of the List Partner Registration Event Types operation. +type PartnerRegistrationEventTypesListResult struct { + // Value - A collection of partner registration event types. + Value *[]EventType `json:"value,omitempty"` + // NextLink - A link for the next page of partner registration event types. + NextLink *string `json:"nextLink,omitempty"` +} + +// PartnerRegistrationProperties properties of the partner registration. +type PartnerRegistrationProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state of the partner registration. Possible values include: 'PartnerRegistrationProvisioningStateCreating', 'PartnerRegistrationProvisioningStateUpdating', 'PartnerRegistrationProvisioningStateDeleting', 'PartnerRegistrationProvisioningStateSucceeded', 'PartnerRegistrationProvisioningStateCanceled', 'PartnerRegistrationProvisioningStateFailed' + ProvisioningState PartnerRegistrationProvisioningState `json:"provisioningState,omitempty"` + // PartnerName - Official name of the partner name. For example: "Contoso". + PartnerName *string `json:"partnerName,omitempty"` + // PartnerResourceTypeName - Name of the partner resource type. + PartnerResourceTypeName *string `json:"partnerResourceTypeName,omitempty"` + // PartnerResourceTypeDisplayName - Display name of the partner resource type. + PartnerResourceTypeDisplayName *string `json:"partnerResourceTypeDisplayName,omitempty"` + // PartnerResourceTypeDescription - Description of the partner resource type. + PartnerResourceTypeDescription *string `json:"partnerResourceTypeDescription,omitempty"` + // SetupURI - URI of the partner website that can be used by Azure customers to setup Event Grid + // integration on an event source. + SetupURI *string `json:"setupUri,omitempty"` + // LogoURI - URI of the logo. + LogoURI *string `json:"logoUri,omitempty"` + // VisibilityState - Visibility state of the partner registration. Possible values include: 'Hidden', 'PublicPreview', 'GenerallyAvailable' + VisibilityState PartnerRegistrationVisibilityState `json:"visibilityState,omitempty"` + // AuthorizedAzureSubscriptionIds - List of Azure subscription Ids that are authorized to create a partner namespace + // associated with this partner registration. This is an optional property. Creating + // partner namespaces is always permitted under the same Azure subscription as the one used + // for creating the partner registration. + AuthorizedAzureSubscriptionIds *[]string `json:"authorizedAzureSubscriptionIds,omitempty"` +} + +// PartnerRegistrationsListResult result of the List Partner Registrations operation. +type PartnerRegistrationsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of partner registrations. + Value *[]PartnerRegistration `json:"value,omitempty"` + // NextLink - A link for the next page of partner registrations. + NextLink *string `json:"nextLink,omitempty"` +} + +// PartnerRegistrationsListResultIterator provides access to a complete listing of PartnerRegistration +// values. +type PartnerRegistrationsListResultIterator struct { + i int + page PartnerRegistrationsListResultPage +} + +// 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 *PartnerRegistrationsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsListResultIterator.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 *PartnerRegistrationsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PartnerRegistrationsListResultIterator) 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 PartnerRegistrationsListResultIterator) Response() PartnerRegistrationsListResult { + 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 PartnerRegistrationsListResultIterator) Value() PartnerRegistration { + if !iter.page.NotDone() { + return PartnerRegistration{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the PartnerRegistrationsListResultIterator type. +func NewPartnerRegistrationsListResultIterator(page PartnerRegistrationsListResultPage) PartnerRegistrationsListResultIterator { + return PartnerRegistrationsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (prlr PartnerRegistrationsListResult) IsEmpty() bool { + return prlr.Value == nil || len(*prlr.Value) == 0 +} + +// partnerRegistrationsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (prlr PartnerRegistrationsListResult) partnerRegistrationsListResultPreparer(ctx context.Context) (*http.Request, error) { + if prlr.NextLink == nil || len(to.String(prlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(prlr.NextLink))) +} + +// PartnerRegistrationsListResultPage contains a page of PartnerRegistration values. +type PartnerRegistrationsListResultPage struct { + fn func(context.Context, PartnerRegistrationsListResult) (PartnerRegistrationsListResult, error) + prlr PartnerRegistrationsListResult +} + +// 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 *PartnerRegistrationsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsListResultPage.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.prlr) + if err != nil { + return err + } + page.prlr = 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 *PartnerRegistrationsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PartnerRegistrationsListResultPage) NotDone() bool { + return !page.prlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PartnerRegistrationsListResultPage) Response() PartnerRegistrationsListResult { + return page.prlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PartnerRegistrationsListResultPage) Values() []PartnerRegistration { + if page.prlr.IsEmpty() { + return nil + } + return *page.prlr.Value +} + +// Creates a new instance of the PartnerRegistrationsListResultPage type. +func NewPartnerRegistrationsListResultPage(getNextPage func(context.Context, PartnerRegistrationsListResult) (PartnerRegistrationsListResult, error)) PartnerRegistrationsListResultPage { + return PartnerRegistrationsListResultPage{fn: getNextPage} +} + +// PartnerRegistrationUpdateParameters properties of the Partner Registration update. +type PartnerRegistrationUpdateParameters struct { + // Tags - Tags of the partner registration resource. + Tags map[string]*string `json:"tags"` + // PartnerTopicTypeName - Name of the partner topic type. + PartnerTopicTypeName *string `json:"partnerTopicTypeName,omitempty"` + // PartnerTopicTypeDisplayName - Display name of the partner topic type. + PartnerTopicTypeDisplayName *string `json:"partnerTopicTypeDisplayName,omitempty"` + // PartnerTopicTypeDescription - Description of the partner topic type. + PartnerTopicTypeDescription *string `json:"partnerTopicTypeDescription,omitempty"` + // SetupURI - URI of the partner website that can be used by Azure customers to setup Event Grid + // integration on an event source. + SetupURI *string `json:"setupUri,omitempty"` + // LogoURI - URI of the partner logo. + LogoURI *string `json:"logoUri,omitempty"` + // AuthorizedAzureSubscriptionIds - List of IDs of Azure AD applications that are authorized to create a partner namespace + // associated with this partner registration. This is an optional property. Creating + // partner namespaces is always permitted under the same Azure subscription as the one used + // for creating the partner registration. + AuthorizedAzureSubscriptionIds *[]string `json:"authorizedAzureSubscriptionIds,omitempty"` +} + +// MarshalJSON is the custom marshaler for PartnerRegistrationUpdateParameters. +func (prup PartnerRegistrationUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if prup.Tags != nil { + objectMap["tags"] = prup.Tags + } + if prup.PartnerTopicTypeName != nil { + objectMap["partnerTopicTypeName"] = prup.PartnerTopicTypeName + } + if prup.PartnerTopicTypeDisplayName != nil { + objectMap["partnerTopicTypeDisplayName"] = prup.PartnerTopicTypeDisplayName + } + if prup.PartnerTopicTypeDescription != nil { + objectMap["partnerTopicTypeDescription"] = prup.PartnerTopicTypeDescription + } + if prup.SetupURI != nil { + objectMap["setupUri"] = prup.SetupURI + } + if prup.LogoURI != nil { + objectMap["logoUri"] = prup.LogoURI + } + if prup.AuthorizedAzureSubscriptionIds != nil { + objectMap["authorizedAzureSubscriptionIds"] = prup.AuthorizedAzureSubscriptionIds + } + return json.Marshal(objectMap) +} + +// PartnerTopic eventGrid Partner Topic. +type PartnerTopic struct { + autorest.Response `json:"-"` + // PartnerTopicProperties - Properties of the partner topic. + *PartnerTopicProperties `json:"properties,omitempty"` + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PartnerTopic. +func (pt PartnerTopic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pt.PartnerTopicProperties != nil { + objectMap["properties"] = pt.PartnerTopicProperties + } + if pt.Location != nil { + objectMap["location"] = pt.Location + } + if pt.Tags != nil { + objectMap["tags"] = pt.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PartnerTopic struct. +func (pt *PartnerTopic) 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 partnerTopicProperties PartnerTopicProperties + err = json.Unmarshal(*v, &partnerTopicProperties) + if err != nil { + return err + } + pt.PartnerTopicProperties = &partnerTopicProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + pt.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + pt.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + pt.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + pt.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + pt.Type = &typeVar + } + } + } + + return nil +} + +// PartnerTopicEventSubscriptionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the +// results of a long-running operation. +type PartnerTopicEventSubscriptionsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerTopicEventSubscriptionsCreateOrUpdateFuture) Result(client PartnerTopicEventSubscriptionsClient) (es EventSubscription, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerTopicEventSubscriptionsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { + es, err = client.CreateOrUpdateResponder(es.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsCreateOrUpdateFuture", "Result", es.Response.Response, "Failure responding to request") + } + } + return +} + +// PartnerTopicEventSubscriptionsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type PartnerTopicEventSubscriptionsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerTopicEventSubscriptionsDeleteFuture) Result(client PartnerTopicEventSubscriptionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerTopicEventSubscriptionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PartnerTopicEventSubscriptionsUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type PartnerTopicEventSubscriptionsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerTopicEventSubscriptionsUpdateFuture) Result(client PartnerTopicEventSubscriptionsClient) (es EventSubscription, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerTopicEventSubscriptionsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { + es, err = client.UpdateResponder(es.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsUpdateFuture", "Result", es.Response.Response, "Failure responding to request") + } + } + return +} + +// PartnerTopicProperties properties of the Partner Topic. +type PartnerTopicProperties struct { + // Source - Source associated with this partner topic. This represents a unique partner resource. + Source *string `json:"source,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the partner topic. Possible values include: 'PartnerTopicProvisioningStateCreating', 'PartnerTopicProvisioningStateUpdating', 'PartnerTopicProvisioningStateDeleting', 'PartnerTopicProvisioningStateSucceeded', 'PartnerTopicProvisioningStateCanceled', 'PartnerTopicProvisioningStateFailed' + ProvisioningState PartnerTopicProvisioningState `json:"provisioningState,omitempty"` + // ActivationState - Activation state of the partner topic. Possible values include: 'NeverActivated', 'Activated', 'Deactivated' + ActivationState PartnerTopicActivationState `json:"activationState,omitempty"` +} + +// PartnerTopicsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type PartnerTopicsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PartnerTopicsDeleteFuture) Result(client PartnerTopicsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PartnerTopicsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PartnerTopicsListResult result of the List Partner Topics operation. +type PartnerTopicsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of partner topics. + Value *[]PartnerTopic `json:"value,omitempty"` + // NextLink - A link for the next page of partner topics. + NextLink *string `json:"nextLink,omitempty"` +} + +// PartnerTopicsListResultIterator provides access to a complete listing of PartnerTopic values. +type PartnerTopicsListResultIterator struct { + i int + page PartnerTopicsListResultPage +} + +// 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 *PartnerTopicsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsListResultIterator.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 *PartnerTopicsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PartnerTopicsListResultIterator) 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 PartnerTopicsListResultIterator) Response() PartnerTopicsListResult { + 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 PartnerTopicsListResultIterator) Value() PartnerTopic { + if !iter.page.NotDone() { + return PartnerTopic{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the PartnerTopicsListResultIterator type. +func NewPartnerTopicsListResultIterator(page PartnerTopicsListResultPage) PartnerTopicsListResultIterator { + return PartnerTopicsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ptlr PartnerTopicsListResult) IsEmpty() bool { + return ptlr.Value == nil || len(*ptlr.Value) == 0 +} + +// partnerTopicsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ptlr PartnerTopicsListResult) partnerTopicsListResultPreparer(ctx context.Context) (*http.Request, error) { + if ptlr.NextLink == nil || len(to.String(ptlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ptlr.NextLink))) +} + +// PartnerTopicsListResultPage contains a page of PartnerTopic values. +type PartnerTopicsListResultPage struct { + fn func(context.Context, PartnerTopicsListResult) (PartnerTopicsListResult, error) + ptlr PartnerTopicsListResult +} + +// 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 *PartnerTopicsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsListResultPage.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.ptlr) + if err != nil { + return err + } + page.ptlr = 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 *PartnerTopicsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PartnerTopicsListResultPage) NotDone() bool { + return !page.ptlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PartnerTopicsListResultPage) Response() PartnerTopicsListResult { + return page.ptlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PartnerTopicsListResultPage) Values() []PartnerTopic { + if page.ptlr.IsEmpty() { + return nil + } + return *page.ptlr.Value +} + +// Creates a new instance of the PartnerTopicsListResultPage type. +func NewPartnerTopicsListResultPage(getNextPage func(context.Context, PartnerTopicsListResult) (PartnerTopicsListResult, error)) PartnerTopicsListResultPage { + return PartnerTopicsListResultPage{fn: getNextPage} +} + +// PartnerTopicType properties of a partner topic type. +type PartnerTopicType struct { + // PartnerTopicTypeProperties - Properties of the partner topic type. + *PartnerTopicTypeProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PartnerTopicType. +func (ptt PartnerTopicType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ptt.PartnerTopicTypeProperties != nil { + objectMap["properties"] = ptt.PartnerTopicTypeProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PartnerTopicType struct. +func (ptt *PartnerTopicType) 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 partnerTopicTypeProperties PartnerTopicTypeProperties + err = json.Unmarshal(*v, &partnerTopicTypeProperties) + if err != nil { + return err + } + ptt.PartnerTopicTypeProperties = &partnerTopicTypeProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ptt.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ptt.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ptt.Type = &typeVar + } + } + } + + return nil +} + +// PartnerTopicTypeProperties properties of a partner topic type. +type PartnerTopicTypeProperties struct { + // PartnerName - Official name of the partner. + PartnerName *string `json:"partnerName,omitempty"` + // TopicTypeName - Name of the partner topic type. This name should be unique among all partner topic types names. + TopicTypeName *string `json:"topicTypeName,omitempty"` + // DisplayName - Display Name for the partner topic type. + DisplayName *string `json:"displayName,omitempty"` + // Description - Description of the partner topic type. + Description *string `json:"description,omitempty"` + // SetupURI - URI of the partner website that can be used by Azure customers to setup Event Grid + // integration on an event source. + SetupURI *string `json:"setupUri,omitempty"` + // AuthorizationState - Status of whether the customer has authorized a partner to create partner topics + // in the customer's subscription. Possible values include: 'NotApplicable', 'NotAuthorized', 'Authorized' + AuthorizationState PartnerTopicTypeAuthorizationState `json:"authorizationState,omitempty"` +} + +// PartnerTopicTypesListResult result of the List Partner Topic Types operation. +type PartnerTopicTypesListResult struct { + // Value - A collection of partner topic types. + Value *[]PartnerTopicType `json:"value,omitempty"` +} + +// PartnerTopicUpdateParameters properties of the Partner Topic update. +type PartnerTopicUpdateParameters struct { + // Tags - Tags of the partner topic. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for PartnerTopicUpdateParameters. +func (ptup PartnerTopicUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ptup.Tags != nil { + objectMap["tags"] = ptup.Tags + } + return json.Marshal(objectMap) +} + +// PrivateEndpoint privateEndpoint information. +type PrivateEndpoint struct { + // ID - The ARM identifier for Private Endpoint. + ID *string `json:"id,omitempty"` +} + +// PrivateEndpointConnection ... +type PrivateEndpointConnection struct { + autorest.Response `json:"-"` + // PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnection. + *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateEndpointConnection. +func (pec PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pec.PrivateEndpointConnectionProperties != nil { + objectMap["properties"] = pec.PrivateEndpointConnectionProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PrivateEndpointConnection struct. +func (pec *PrivateEndpointConnection) 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 privateEndpointConnectionProperties PrivateEndpointConnectionProperties + err = json.Unmarshal(*v, &privateEndpointConnectionProperties) + if err != nil { + return err + } + pec.PrivateEndpointConnectionProperties = &privateEndpointConnectionProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + pec.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + pec.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + pec.Type = &typeVar + } + } + } + + return nil +} + +// PrivateEndpointConnectionListResult result of the list of all private endpoint connections operation. +type PrivateEndpointConnectionListResult struct { + autorest.Response `json:"-"` + // Value - A collection of private endpoint connection resources. + Value *[]PrivateEndpointConnection `json:"value,omitempty"` + // NextLink - A link for the next page of private endpoint connection resources. + NextLink *string `json:"nextLink,omitempty"` +} + +// PrivateEndpointConnectionListResultIterator provides access to a complete listing of +// PrivateEndpointConnection values. +type PrivateEndpointConnectionListResultIterator struct { + i int + page PrivateEndpointConnectionListResultPage +} + +// 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 *PrivateEndpointConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultIterator.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 *PrivateEndpointConnectionListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PrivateEndpointConnectionListResultIterator) 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 PrivateEndpointConnectionListResultIterator) Response() PrivateEndpointConnectionListResult { + 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 PrivateEndpointConnectionListResultIterator) Value() PrivateEndpointConnection { + if !iter.page.NotDone() { + return PrivateEndpointConnection{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the PrivateEndpointConnectionListResultIterator type. +func NewPrivateEndpointConnectionListResultIterator(page PrivateEndpointConnectionListResultPage) PrivateEndpointConnectionListResultIterator { + return PrivateEndpointConnectionListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (peclr PrivateEndpointConnectionListResult) IsEmpty() bool { + return peclr.Value == nil || len(*peclr.Value) == 0 +} + +// privateEndpointConnectionListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (peclr PrivateEndpointConnectionListResult) privateEndpointConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { + if peclr.NextLink == nil || len(to.String(peclr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(peclr.NextLink))) +} + +// PrivateEndpointConnectionListResultPage contains a page of PrivateEndpointConnection values. +type PrivateEndpointConnectionListResultPage struct { + fn func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error) + peclr PrivateEndpointConnectionListResult +} + +// 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 *PrivateEndpointConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultPage.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.peclr) + if err != nil { + return err + } + page.peclr = 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 *PrivateEndpointConnectionListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PrivateEndpointConnectionListResultPage) NotDone() bool { + return !page.peclr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PrivateEndpointConnectionListResultPage) Response() PrivateEndpointConnectionListResult { + return page.peclr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PrivateEndpointConnectionListResultPage) Values() []PrivateEndpointConnection { + if page.peclr.IsEmpty() { + return nil + } + return *page.peclr.Value +} + +// Creates a new instance of the PrivateEndpointConnectionListResultPage type. +func NewPrivateEndpointConnectionListResultPage(getNextPage func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error)) PrivateEndpointConnectionListResultPage { + return PrivateEndpointConnectionListResultPage{fn: getNextPage} +} + +// PrivateEndpointConnectionProperties properties of the private endpoint connection resource. +type PrivateEndpointConnectionProperties struct { + // PrivateEndpoint - The Private Endpoint resource for this Connection. + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + // GroupIds - GroupIds from the private link service resource. + GroupIds *[]string `json:"groupIds,omitempty"` + // PrivateLinkServiceConnectionState - Details about the state of the connection. + PrivateLinkServiceConnectionState *ConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + // ProvisioningState - Provisioning state of the Private Endpoint Connection. Possible values include: 'ResourceProvisioningStateCreating', 'ResourceProvisioningStateUpdating', 'ResourceProvisioningStateDeleting', 'ResourceProvisioningStateSucceeded', 'ResourceProvisioningStateCanceled', 'ResourceProvisioningStateFailed' + ProvisioningState ResourceProvisioningState `json:"provisioningState,omitempty"` +} + +// PrivateEndpointConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type PrivateEndpointConnectionsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PrivateEndpointConnectionsDeleteFuture) Result(client PrivateEndpointConnectionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PrivateEndpointConnectionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PrivateEndpointConnectionsUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type PrivateEndpointConnectionsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PrivateEndpointConnectionsUpdateFuture) Result(client PrivateEndpointConnectionsClient) (pec PrivateEndpointConnection, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.PrivateEndpointConnectionsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if pec.Response.Response, err = future.GetResult(sender); err == nil && pec.Response.Response.StatusCode != http.StatusNoContent { + pec, err = client.UpdateResponder(pec.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsUpdateFuture", "Result", pec.Response.Response, "Failure responding to request") + } + } + return +} + +// PrivateLinkResource information of the private link resource. +type PrivateLinkResource struct { + autorest.Response `json:"-"` + // PrivateLinkResourceProperties - Properties of the private link resource. + *PrivateLinkResourceProperties `json:"properties,omitempty"` + // ID - Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - Name of the resource + Name *string `json:"name,omitempty"` + // Type - Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PrivateLinkResource. +func (plr PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if plr.PrivateLinkResourceProperties != nil { + objectMap["properties"] = plr.PrivateLinkResourceProperties + } + if plr.ID != nil { + objectMap["id"] = plr.ID + } + if plr.Name != nil { + objectMap["name"] = plr.Name + } + if plr.Type != nil { + objectMap["type"] = plr.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PrivateLinkResource struct. +func (plr *PrivateLinkResource) 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 privateLinkResourceProperties PrivateLinkResourceProperties + err = json.Unmarshal(*v, &privateLinkResourceProperties) + if err != nil { + return err + } + plr.PrivateLinkResourceProperties = &privateLinkResourceProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + plr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + plr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + plr.Type = &typeVar + } + } + } + + return nil +} + +// PrivateLinkResourceProperties ... +type PrivateLinkResourceProperties struct { + GroupID *string `json:"groupId,omitempty"` + DisplayName *string `json:"displayName,omitempty"` + RequiredMembers *[]string `json:"requiredMembers,omitempty"` + RequiredZoneNames *[]string `json:"requiredZoneNames,omitempty"` +} + +// PrivateLinkResourcesListResult result of the List private link resources operation. +type PrivateLinkResourcesListResult struct { + autorest.Response `json:"-"` + // Value - A collection of private link resources + Value *[]PrivateLinkResource `json:"value,omitempty"` + // NextLink - A link for the next page of private link resources. + NextLink *string `json:"nextLink,omitempty"` +} + +// PrivateLinkResourcesListResultIterator provides access to a complete listing of PrivateLinkResource +// values. +type PrivateLinkResourcesListResultIterator struct { + i int + page PrivateLinkResourcesListResultPage +} + +// 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 *PrivateLinkResourcesListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesListResultIterator.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 *PrivateLinkResourcesListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PrivateLinkResourcesListResultIterator) 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 PrivateLinkResourcesListResultIterator) Response() PrivateLinkResourcesListResult { + 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 PrivateLinkResourcesListResultIterator) Value() PrivateLinkResource { + if !iter.page.NotDone() { + return PrivateLinkResource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the PrivateLinkResourcesListResultIterator type. +func NewPrivateLinkResourcesListResultIterator(page PrivateLinkResourcesListResultPage) PrivateLinkResourcesListResultIterator { + return PrivateLinkResourcesListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (plrlr PrivateLinkResourcesListResult) IsEmpty() bool { + return plrlr.Value == nil || len(*plrlr.Value) == 0 +} + +// privateLinkResourcesListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (plrlr PrivateLinkResourcesListResult) privateLinkResourcesListResultPreparer(ctx context.Context) (*http.Request, error) { + if plrlr.NextLink == nil || len(to.String(plrlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(plrlr.NextLink))) +} + +// PrivateLinkResourcesListResultPage contains a page of PrivateLinkResource values. +type PrivateLinkResourcesListResultPage struct { + fn func(context.Context, PrivateLinkResourcesListResult) (PrivateLinkResourcesListResult, error) + plrlr PrivateLinkResourcesListResult +} + +// 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 *PrivateLinkResourcesListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesListResultPage.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.plrlr) + if err != nil { + return err + } + page.plrlr = 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 *PrivateLinkResourcesListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PrivateLinkResourcesListResultPage) NotDone() bool { + return !page.plrlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PrivateLinkResourcesListResultPage) Response() PrivateLinkResourcesListResult { + return page.plrlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PrivateLinkResourcesListResultPage) Values() []PrivateLinkResource { + if page.plrlr.IsEmpty() { + return nil + } + return *page.plrlr.Value +} + +// Creates a new instance of the PrivateLinkResourcesListResultPage type. +func NewPrivateLinkResourcesListResultPage(getNextPage func(context.Context, PrivateLinkResourcesListResult) (PrivateLinkResourcesListResult, error)) PrivateLinkResourcesListResultPage { + return PrivateLinkResourcesListResultPage{fn: getNextPage} +} + +// Resource definition of a Resource +type Resource struct { + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// ResourceSku describes an EventGrid Resource Sku. +type ResourceSku struct { + // Name - the Sku name of the resource. + // the possible values: Basic; Premium. Possible values include: 'Basic', 'Premium' + Name Sku `json:"name,omitempty"` +} + +// RetryPolicy information about the retry policy for an event subscription. +type RetryPolicy struct { + // MaxDeliveryAttempts - Maximum number of delivery retry attempts for events. + MaxDeliveryAttempts *int32 `json:"maxDeliveryAttempts,omitempty"` + // EventTimeToLiveInMinutes - Time To Live (in minutes) for events. + EventTimeToLiveInMinutes *int32 `json:"eventTimeToLiveInMinutes,omitempty"` +} + +// ServiceBusQueueEventSubscriptionDestination information about the service bus destination for an event +// subscription. +type ServiceBusQueueEventSubscriptionDestination struct { + // ServiceBusQueueEventSubscriptionDestinationProperties - Service Bus Properties of the event subscription destination. + *ServiceBusQueueEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + sbqesd.EndpointType = EndpointTypeServiceBusQueue + objectMap := make(map[string]interface{}) + if sbqesd.ServiceBusQueueEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = sbqesd.ServiceBusQueueEventSubscriptionDestinationProperties + } + if sbqesd.EndpointType != "" { + objectMap["endpointType"] = sbqesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return &sbqesd, true +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusQueueEventSubscriptionDestination. +func (sbqesd ServiceBusQueueEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &sbqesd, true +} + +// UnmarshalJSON is the custom unmarshaler for ServiceBusQueueEventSubscriptionDestination struct. +func (sbqesd *ServiceBusQueueEventSubscriptionDestination) 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 serviceBusQueueEventSubscriptionDestinationProperties ServiceBusQueueEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &serviceBusQueueEventSubscriptionDestinationProperties) + if err != nil { + return err + } + sbqesd.ServiceBusQueueEventSubscriptionDestinationProperties = &serviceBusQueueEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + sbqesd.EndpointType = endpointType + } + } + } + + return nil +} + +// ServiceBusQueueEventSubscriptionDestinationProperties the properties that represent the Service Bus +// destination of an event subscription. +type ServiceBusQueueEventSubscriptionDestinationProperties struct { + // ResourceID - The Azure Resource Id that represents the endpoint of the Service Bus destination of an event subscription. + ResourceID *string `json:"resourceId,omitempty"` +} + +// ServiceBusTopicEventSubscriptionDestination information about the service bus topic destination for an +// event subscription. +type ServiceBusTopicEventSubscriptionDestination struct { + // ServiceBusTopicEventSubscriptionDestinationProperties - Service Bus Topic Properties of the event subscription destination. + *ServiceBusTopicEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + sbtesd.EndpointType = EndpointTypeServiceBusTopic + objectMap := make(map[string]interface{}) + if sbtesd.ServiceBusTopicEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = sbtesd.ServiceBusTopicEventSubscriptionDestinationProperties + } + if sbtesd.EndpointType != "" { + objectMap["endpointType"] = sbtesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return &sbtesd, true +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for ServiceBusTopicEventSubscriptionDestination. +func (sbtesd ServiceBusTopicEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &sbtesd, true +} + +// UnmarshalJSON is the custom unmarshaler for ServiceBusTopicEventSubscriptionDestination struct. +func (sbtesd *ServiceBusTopicEventSubscriptionDestination) 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 serviceBusTopicEventSubscriptionDestinationProperties ServiceBusTopicEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &serviceBusTopicEventSubscriptionDestinationProperties) + if err != nil { + return err + } + sbtesd.ServiceBusTopicEventSubscriptionDestinationProperties = &serviceBusTopicEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + sbtesd.EndpointType = endpointType + } + } + } + + return nil +} + +// ServiceBusTopicEventSubscriptionDestinationProperties the properties that represent the Service Bus +// Topic destination of an event subscription. +type ServiceBusTopicEventSubscriptionDestinationProperties struct { + // ResourceID - The Azure Resource Id that represents the endpoint of the Service Bus Topic destination of an event subscription. + ResourceID *string `json:"resourceId,omitempty"` +} + +// StorageBlobDeadLetterDestination information about the storage blob based dead letter destination. +type StorageBlobDeadLetterDestination struct { + // StorageBlobDeadLetterDestinationProperties - The properties of the Storage Blob based deadletter destination + *StorageBlobDeadLetterDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeDeadLetterDestination', 'EndpointTypeStorageBlob' + EndpointType EndpointTypeBasicDeadLetterDestination `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StorageBlobDeadLetterDestination. +func (sbdld StorageBlobDeadLetterDestination) MarshalJSON() ([]byte, error) { + sbdld.EndpointType = EndpointTypeStorageBlob + objectMap := make(map[string]interface{}) + if sbdld.StorageBlobDeadLetterDestinationProperties != nil { + objectMap["properties"] = sbdld.StorageBlobDeadLetterDestinationProperties + } + if sbdld.EndpointType != "" { + objectMap["endpointType"] = sbdld.EndpointType + } + return json.Marshal(objectMap) +} + +// AsStorageBlobDeadLetterDestination is the BasicDeadLetterDestination implementation for StorageBlobDeadLetterDestination. +func (sbdld StorageBlobDeadLetterDestination) AsStorageBlobDeadLetterDestination() (*StorageBlobDeadLetterDestination, bool) { + return &sbdld, true +} + +// AsDeadLetterDestination is the BasicDeadLetterDestination implementation for StorageBlobDeadLetterDestination. +func (sbdld StorageBlobDeadLetterDestination) AsDeadLetterDestination() (*DeadLetterDestination, bool) { + return nil, false +} + +// AsBasicDeadLetterDestination is the BasicDeadLetterDestination implementation for StorageBlobDeadLetterDestination. +func (sbdld StorageBlobDeadLetterDestination) AsBasicDeadLetterDestination() (BasicDeadLetterDestination, bool) { + return &sbdld, true +} + +// UnmarshalJSON is the custom unmarshaler for StorageBlobDeadLetterDestination struct. +func (sbdld *StorageBlobDeadLetterDestination) 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 storageBlobDeadLetterDestinationProperties StorageBlobDeadLetterDestinationProperties + err = json.Unmarshal(*v, &storageBlobDeadLetterDestinationProperties) + if err != nil { + return err + } + sbdld.StorageBlobDeadLetterDestinationProperties = &storageBlobDeadLetterDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointTypeBasicDeadLetterDestination + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + sbdld.EndpointType = endpointType + } + } + } + + return nil +} + +// StorageBlobDeadLetterDestinationProperties properties of the storage blob based dead letter destination. +type StorageBlobDeadLetterDestinationProperties struct { + // ResourceID - The Azure Resource ID of the storage account that is the destination of the deadletter events + ResourceID *string `json:"resourceId,omitempty"` + // BlobContainerName - The name of the Storage blob container that is the destination of the deadletter events + BlobContainerName *string `json:"blobContainerName,omitempty"` +} + +// StorageQueueEventSubscriptionDestination information about the storage queue destination for an event +// subscription. +type StorageQueueEventSubscriptionDestination struct { + // StorageQueueEventSubscriptionDestinationProperties - Storage Queue Properties of the event subscription destination. + *StorageQueueEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + sqesd.EndpointType = EndpointTypeStorageQueue + objectMap := make(map[string]interface{}) + if sqesd.StorageQueueEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = sqesd.StorageQueueEventSubscriptionDestinationProperties + } + if sqesd.EndpointType != "" { + objectMap["endpointType"] = sqesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return &sqesd, true +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for StorageQueueEventSubscriptionDestination. +func (sqesd StorageQueueEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &sqesd, true +} + +// UnmarshalJSON is the custom unmarshaler for StorageQueueEventSubscriptionDestination struct. +func (sqesd *StorageQueueEventSubscriptionDestination) 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 storageQueueEventSubscriptionDestinationProperties StorageQueueEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &storageQueueEventSubscriptionDestinationProperties) + if err != nil { + return err + } + sqesd.StorageQueueEventSubscriptionDestinationProperties = &storageQueueEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + sqesd.EndpointType = endpointType + } + } + } + + return nil +} + +// StorageQueueEventSubscriptionDestinationProperties the properties for a storage queue destination. +type StorageQueueEventSubscriptionDestinationProperties struct { + // ResourceID - The Azure Resource ID of the storage account that contains the queue that is the destination of an event subscription. + ResourceID *string `json:"resourceId,omitempty"` + // QueueName - The name of the Storage queue under a storage account that is the destination of an event subscription. + QueueName *string `json:"queueName,omitempty"` +} + +// StringBeginsWithAdvancedFilter stringBeginsWith Advanced Filter. +type StringBeginsWithAdvancedFilter struct { + // Values - The set of filter values. + Values *[]string `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) MarshalJSON() ([]byte, error) { + sbwaf.OperatorType = OperatorTypeStringBeginsWith + objectMap := make(map[string]interface{}) + if sbwaf.Values != nil { + objectMap["values"] = sbwaf.Values + } + if sbwaf.Key != nil { + objectMap["key"] = sbwaf.Key + } + if sbwaf.OperatorType != "" { + objectMap["operatorType"] = sbwaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return &sbwaf, true +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringBeginsWithAdvancedFilter. +func (sbwaf StringBeginsWithAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &sbwaf, true +} + +// StringContainsAdvancedFilter stringContains Advanced Filter. +type StringContainsAdvancedFilter struct { + // Values - The set of filter values. + Values *[]string `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) MarshalJSON() ([]byte, error) { + scaf.OperatorType = OperatorTypeStringContains + objectMap := make(map[string]interface{}) + if scaf.Values != nil { + objectMap["values"] = scaf.Values + } + if scaf.Key != nil { + objectMap["key"] = scaf.Key + } + if scaf.OperatorType != "" { + objectMap["operatorType"] = scaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return &scaf, true +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringContainsAdvancedFilter. +func (scaf StringContainsAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &scaf, true +} + +// StringEndsWithAdvancedFilter stringEndsWith Advanced Filter. +type StringEndsWithAdvancedFilter struct { + // Values - The set of filter values. + Values *[]string `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) MarshalJSON() ([]byte, error) { + sewaf.OperatorType = OperatorTypeStringEndsWith + objectMap := make(map[string]interface{}) + if sewaf.Values != nil { + objectMap["values"] = sewaf.Values + } + if sewaf.Key != nil { + objectMap["key"] = sewaf.Key + } + if sewaf.OperatorType != "" { + objectMap["operatorType"] = sewaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return &sewaf, true +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringEndsWithAdvancedFilter. +func (sewaf StringEndsWithAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &sewaf, true +} + +// StringInAdvancedFilter stringIn Advanced Filter. +type StringInAdvancedFilter struct { + // Values - The set of filter values. + Values *[]string `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) MarshalJSON() ([]byte, error) { + siaf.OperatorType = OperatorTypeStringIn + objectMap := make(map[string]interface{}) + if siaf.Values != nil { + objectMap["values"] = siaf.Values + } + if siaf.Key != nil { + objectMap["key"] = siaf.Key + } + if siaf.OperatorType != "" { + objectMap["operatorType"] = siaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return &siaf, true +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return nil, false +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringInAdvancedFilter. +func (siaf StringInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &siaf, true +} + +// StringNotInAdvancedFilter stringNotIn Advanced Filter. +type StringNotInAdvancedFilter struct { + // Values - The set of filter values. + Values *[]string `json:"values,omitempty"` + // Key - The field/property in the event based on which you want to filter. + Key *string `json:"key,omitempty"` + // OperatorType - Possible values include: 'OperatorTypeAdvancedFilter', 'OperatorTypeNumberIn', 'OperatorTypeNumberNotIn', 'OperatorTypeNumberLessThan', 'OperatorTypeNumberGreaterThan', 'OperatorTypeNumberLessThanOrEquals', 'OperatorTypeNumberGreaterThanOrEquals', 'OperatorTypeBoolEquals', 'OperatorTypeStringIn', 'OperatorTypeStringNotIn', 'OperatorTypeStringBeginsWith', 'OperatorTypeStringEndsWith', 'OperatorTypeStringContains' + OperatorType OperatorType `json:"operatorType,omitempty"` +} + +// MarshalJSON is the custom marshaler for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) MarshalJSON() ([]byte, error) { + sniaf.OperatorType = OperatorTypeStringNotIn + objectMap := make(map[string]interface{}) + if sniaf.Values != nil { + objectMap["values"] = sniaf.Values + } + if sniaf.Key != nil { + objectMap["key"] = sniaf.Key + } + if sniaf.OperatorType != "" { + objectMap["operatorType"] = sniaf.OperatorType + } + return json.Marshal(objectMap) +} + +// AsNumberInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsNumberInAdvancedFilter() (*NumberInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsNumberNotInAdvancedFilter() (*NumberNotInAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsNumberLessThanAdvancedFilter() (*NumberLessThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsNumberGreaterThanAdvancedFilter() (*NumberGreaterThanAdvancedFilter, bool) { + return nil, false +} + +// AsNumberLessThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsNumberLessThanOrEqualsAdvancedFilter() (*NumberLessThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsNumberGreaterThanOrEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsNumberGreaterThanOrEqualsAdvancedFilter() (*NumberGreaterThanOrEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsBoolEqualsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsBoolEqualsAdvancedFilter() (*BoolEqualsAdvancedFilter, bool) { + return nil, false +} + +// AsStringInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsStringInAdvancedFilter() (*StringInAdvancedFilter, bool) { + return nil, false +} + +// AsStringNotInAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsStringNotInAdvancedFilter() (*StringNotInAdvancedFilter, bool) { + return &sniaf, true +} + +// AsStringBeginsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsStringBeginsWithAdvancedFilter() (*StringBeginsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringEndsWithAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsStringEndsWithAdvancedFilter() (*StringEndsWithAdvancedFilter, bool) { + return nil, false +} + +// AsStringContainsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsStringContainsAdvancedFilter() (*StringContainsAdvancedFilter, bool) { + return nil, false +} + +// AsAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsAdvancedFilter() (*AdvancedFilter, bool) { + return nil, false +} + +// AsBasicAdvancedFilter is the BasicAdvancedFilter implementation for StringNotInAdvancedFilter. +func (sniaf StringNotInAdvancedFilter) AsBasicAdvancedFilter() (BasicAdvancedFilter, bool) { + return &sniaf, true +} + +// SystemTopic eventGrid System Topic. +type SystemTopic struct { + autorest.Response `json:"-"` + // SystemTopicProperties - Properties of the system topic. + *SystemTopicProperties `json:"properties,omitempty"` + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SystemTopic. +func (st SystemTopic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if st.SystemTopicProperties != nil { + objectMap["properties"] = st.SystemTopicProperties + } + if st.Location != nil { + objectMap["location"] = st.Location + } + if st.Tags != nil { + objectMap["tags"] = st.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SystemTopic struct. +func (st *SystemTopic) 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 systemTopicProperties SystemTopicProperties + err = json.Unmarshal(*v, &systemTopicProperties) + if err != nil { + return err + } + st.SystemTopicProperties = &systemTopicProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + st.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + st.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + st.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + st.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + st.Type = &typeVar + } + } + } + + return nil +} + +// SystemTopicEventSubscriptionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the +// results of a long-running operation. +type SystemTopicEventSubscriptionsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SystemTopicEventSubscriptionsCreateOrUpdateFuture) Result(client SystemTopicEventSubscriptionsClient) (es EventSubscription, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.SystemTopicEventSubscriptionsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { + es, err = client.CreateOrUpdateResponder(es.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsCreateOrUpdateFuture", "Result", es.Response.Response, "Failure responding to request") + } + } + return +} + +// SystemTopicEventSubscriptionsDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type SystemTopicEventSubscriptionsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SystemTopicEventSubscriptionsDeleteFuture) Result(client SystemTopicEventSubscriptionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.SystemTopicEventSubscriptionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// SystemTopicEventSubscriptionsUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type SystemTopicEventSubscriptionsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SystemTopicEventSubscriptionsUpdateFuture) Result(client SystemTopicEventSubscriptionsClient) (es EventSubscription, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.SystemTopicEventSubscriptionsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if es.Response.Response, err = future.GetResult(sender); err == nil && es.Response.Response.StatusCode != http.StatusNoContent { + es, err = client.UpdateResponder(es.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsUpdateFuture", "Result", es.Response.Response, "Failure responding to request") + } + } + return +} + +// SystemTopicProperties properties of the System Topic. +type SystemTopicProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state of the system topic. Possible values include: 'ResourceProvisioningStateCreating', 'ResourceProvisioningStateUpdating', 'ResourceProvisioningStateDeleting', 'ResourceProvisioningStateSucceeded', 'ResourceProvisioningStateCanceled', 'ResourceProvisioningStateFailed' + ProvisioningState ResourceProvisioningState `json:"provisioningState,omitempty"` + // Source - Source for the system topic. + Source *string `json:"source,omitempty"` + // TopicType - TopicType for the system topic. + TopicType *string `json:"topicType,omitempty"` + // MetricResourceID - READ-ONLY; Metric resource id for the system topic. + MetricResourceID *string `json:"metricResourceId,omitempty"` +} + +// SystemTopicsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type SystemTopicsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SystemTopicsCreateOrUpdateFuture) Result(client SystemTopicsClient) (st SystemTopic, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.SystemTopicsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if st.Response.Response, err = future.GetResult(sender); err == nil && st.Response.Response.StatusCode != http.StatusNoContent { + st, err = client.CreateOrUpdateResponder(st.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsCreateOrUpdateFuture", "Result", st.Response.Response, "Failure responding to request") + } + } + return +} + +// SystemTopicsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type SystemTopicsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SystemTopicsDeleteFuture) Result(client SystemTopicsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.SystemTopicsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// SystemTopicsListResult result of the List System topics operation. +type SystemTopicsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of system Topics. + Value *[]SystemTopic `json:"value,omitempty"` + // NextLink - A link for the next page of topics. + NextLink *string `json:"nextLink,omitempty"` +} + +// SystemTopicsListResultIterator provides access to a complete listing of SystemTopic values. +type SystemTopicsListResultIterator struct { + i int + page SystemTopicsListResultPage +} + +// 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 *SystemTopicsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsListResultIterator.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 *SystemTopicsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SystemTopicsListResultIterator) 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 SystemTopicsListResultIterator) Response() SystemTopicsListResult { + 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 SystemTopicsListResultIterator) Value() SystemTopic { + if !iter.page.NotDone() { + return SystemTopic{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the SystemTopicsListResultIterator type. +func NewSystemTopicsListResultIterator(page SystemTopicsListResultPage) SystemTopicsListResultIterator { + return SystemTopicsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (stlr SystemTopicsListResult) IsEmpty() bool { + return stlr.Value == nil || len(*stlr.Value) == 0 +} + +// systemTopicsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (stlr SystemTopicsListResult) systemTopicsListResultPreparer(ctx context.Context) (*http.Request, error) { + if stlr.NextLink == nil || len(to.String(stlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(stlr.NextLink))) +} + +// SystemTopicsListResultPage contains a page of SystemTopic values. +type SystemTopicsListResultPage struct { + fn func(context.Context, SystemTopicsListResult) (SystemTopicsListResult, error) + stlr SystemTopicsListResult +} + +// 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 *SystemTopicsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsListResultPage.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.stlr) + if err != nil { + return err + } + page.stlr = 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 *SystemTopicsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SystemTopicsListResultPage) NotDone() bool { + return !page.stlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SystemTopicsListResultPage) Response() SystemTopicsListResult { + return page.stlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SystemTopicsListResultPage) Values() []SystemTopic { + if page.stlr.IsEmpty() { + return nil + } + return *page.stlr.Value +} + +// Creates a new instance of the SystemTopicsListResultPage type. +func NewSystemTopicsListResultPage(getNextPage func(context.Context, SystemTopicsListResult) (SystemTopicsListResult, error)) SystemTopicsListResultPage { + return SystemTopicsListResultPage{fn: getNextPage} +} + +// SystemTopicsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type SystemTopicsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SystemTopicsUpdateFuture) Result(client SystemTopicsClient) (st SystemTopic, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.SystemTopicsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if st.Response.Response, err = future.GetResult(sender); err == nil && st.Response.Response.StatusCode != http.StatusNoContent { + st, err = client.UpdateResponder(st.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsUpdateFuture", "Result", st.Response.Response, "Failure responding to request") + } + } + return +} + +// SystemTopicUpdateParameters properties of the System Topic update. +type SystemTopicUpdateParameters struct { + // Tags - Tags of the system topic. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for SystemTopicUpdateParameters. +func (stup SystemTopicUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if stup.Tags != nil { + objectMap["tags"] = stup.Tags + } + return json.Marshal(objectMap) +} + +// Topic eventGrid Topic +type Topic struct { + autorest.Response `json:"-"` + // TopicProperties - Properties of the topic. + *TopicProperties `json:"properties,omitempty"` + // Sku - The Sku pricing tier for the topic. + Sku *ResourceSku `json:"sku,omitempty"` + // Identity - Identity information for the resource. + Identity *IdentityInfo `json:"identity,omitempty"` + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Topic. +func (t Topic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if t.TopicProperties != nil { + objectMap["properties"] = t.TopicProperties + } + if t.Sku != nil { + objectMap["sku"] = t.Sku + } + if t.Identity != nil { + objectMap["identity"] = t.Identity + } + if t.Location != nil { + objectMap["location"] = t.Location + } + if t.Tags != nil { + objectMap["tags"] = t.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Topic struct. +func (t *Topic) 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 topicProperties TopicProperties + err = json.Unmarshal(*v, &topicProperties) + if err != nil { + return err + } + t.TopicProperties = &topicProperties + } + case "sku": + if v != nil { + var sku ResourceSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + t.Sku = &sku + } + case "identity": + if v != nil { + var identity IdentityInfo + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + t.Identity = &identity + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + t.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + t.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + t.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + t.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + t.Type = &typeVar + } + } + } + + return nil +} + +// TopicProperties properties of the Topic +type TopicProperties struct { + PrivateEndpointConnections *[]PrivateEndpointConnection `json:"privateEndpointConnections,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state of the topic. Possible values include: 'TopicProvisioningStateCreating', 'TopicProvisioningStateUpdating', 'TopicProvisioningStateDeleting', 'TopicProvisioningStateSucceeded', 'TopicProvisioningStateCanceled', 'TopicProvisioningStateFailed' + ProvisioningState TopicProvisioningState `json:"provisioningState,omitempty"` + // Endpoint - READ-ONLY; Endpoint for the topic. + Endpoint *string `json:"endpoint,omitempty"` + // InputSchema - This determines the format that Event Grid should expect for incoming events published to the topic. Possible values include: 'InputSchemaEventGridSchema', 'InputSchemaCustomEventSchema', 'InputSchemaCloudEventSchemaV10' + InputSchema InputSchema `json:"inputSchema,omitempty"` + // InputSchemaMapping - This enables publishing using custom event schemas. An InputSchemaMapping can be specified to map various properties of a source schema to various required properties of the EventGridEvent schema. + InputSchemaMapping BasicInputSchemaMapping `json:"inputSchemaMapping,omitempty"` + // MetricResourceID - READ-ONLY; Metric resource id for the topic. + MetricResourceID *string `json:"metricResourceId,omitempty"` + // PublicNetworkAccess - This determines if traffic is allowed over public network. By default it is enabled. + // You can further restrict to specific IPs by configuring . Possible values include: 'Enabled', 'Disabled' + PublicNetworkAccess PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + // InboundIPRules - This can be used to restrict traffic from specific IPs instead of all IPs. Note: These are considered only if PublicNetworkAccess is enabled. + InboundIPRules *[]InboundIPRule `json:"inboundIpRules,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for TopicProperties struct. +func (tp *TopicProperties) 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 "privateEndpointConnections": + if v != nil { + var privateEndpointConnections []PrivateEndpointConnection + err = json.Unmarshal(*v, &privateEndpointConnections) + if err != nil { + return err + } + tp.PrivateEndpointConnections = &privateEndpointConnections + } + case "provisioningState": + if v != nil { + var provisioningState TopicProvisioningState + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + tp.ProvisioningState = provisioningState + } + case "endpoint": + if v != nil { + var endpoint string + err = json.Unmarshal(*v, &endpoint) + if err != nil { + return err + } + tp.Endpoint = &endpoint + } + case "inputSchema": + if v != nil { + var inputSchema InputSchema + err = json.Unmarshal(*v, &inputSchema) + if err != nil { + return err + } + tp.InputSchema = inputSchema + } + case "inputSchemaMapping": + if v != nil { + inputSchemaMapping, err := unmarshalBasicInputSchemaMapping(*v) + if err != nil { + return err + } + tp.InputSchemaMapping = inputSchemaMapping + } + case "metricResourceId": + if v != nil { + var metricResourceID string + err = json.Unmarshal(*v, &metricResourceID) + if err != nil { + return err + } + tp.MetricResourceID = &metricResourceID + } + case "publicNetworkAccess": + if v != nil { + var publicNetworkAccess PublicNetworkAccess + err = json.Unmarshal(*v, &publicNetworkAccess) + if err != nil { + return err + } + tp.PublicNetworkAccess = publicNetworkAccess + } + case "inboundIpRules": + if v != nil { + var inboundIPRules []InboundIPRule + err = json.Unmarshal(*v, &inboundIPRules) + if err != nil { + return err + } + tp.InboundIPRules = &inboundIPRules + } + } + } + + return nil +} + +// TopicRegenerateKeyRequest topic regenerate share access key request +type TopicRegenerateKeyRequest struct { + // KeyName - Key name to regenerate key1 or key2 + KeyName *string `json:"keyName,omitempty"` +} + +// TopicsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type TopicsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *TopicsCreateOrUpdateFuture) Result(client TopicsClient) (t Topic, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.TopicsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if t.Response.Response, err = future.GetResult(sender); err == nil && t.Response.Response.StatusCode != http.StatusNoContent { + t, err = client.CreateOrUpdateResponder(t.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsCreateOrUpdateFuture", "Result", t.Response.Response, "Failure responding to request") + } + } + return +} + +// TopicsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type TopicsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *TopicsDeleteFuture) Result(client TopicsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.TopicsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// TopicSharedAccessKeys shared access keys of the Topic +type TopicSharedAccessKeys struct { + autorest.Response `json:"-"` + // Key1 - Shared access key1 for the topic. + Key1 *string `json:"key1,omitempty"` + // Key2 - Shared access key2 for the topic. + Key2 *string `json:"key2,omitempty"` +} + +// TopicsListResult result of the List Topics operation +type TopicsListResult struct { + autorest.Response `json:"-"` + // Value - A collection of Topics + Value *[]Topic `json:"value,omitempty"` + // NextLink - A link for the next page of topics + NextLink *string `json:"nextLink,omitempty"` +} + +// TopicsListResultIterator provides access to a complete listing of Topic values. +type TopicsListResultIterator struct { + i int + page TopicsListResultPage +} + +// 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 *TopicsListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TopicsListResultIterator.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 *TopicsListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter TopicsListResultIterator) 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 TopicsListResultIterator) Response() TopicsListResult { + 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 TopicsListResultIterator) Value() Topic { + if !iter.page.NotDone() { + return Topic{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the TopicsListResultIterator type. +func NewTopicsListResultIterator(page TopicsListResultPage) TopicsListResultIterator { + return TopicsListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (tlr TopicsListResult) IsEmpty() bool { + return tlr.Value == nil || len(*tlr.Value) == 0 +} + +// topicsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (tlr TopicsListResult) topicsListResultPreparer(ctx context.Context) (*http.Request, error) { + if tlr.NextLink == nil || len(to.String(tlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(tlr.NextLink))) +} + +// TopicsListResultPage contains a page of Topic values. +type TopicsListResultPage struct { + fn func(context.Context, TopicsListResult) (TopicsListResult, error) + tlr TopicsListResult +} + +// 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 *TopicsListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TopicsListResultPage.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.tlr) + if err != nil { + return err + } + page.tlr = 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 *TopicsListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page TopicsListResultPage) NotDone() bool { + return !page.tlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page TopicsListResultPage) Response() TopicsListResult { + return page.tlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page TopicsListResultPage) Values() []Topic { + if page.tlr.IsEmpty() { + return nil + } + return *page.tlr.Value +} + +// Creates a new instance of the TopicsListResultPage type. +func NewTopicsListResultPage(getNextPage func(context.Context, TopicsListResult) (TopicsListResult, error)) TopicsListResultPage { + return TopicsListResultPage{fn: getNextPage} +} + +// TopicsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type TopicsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *TopicsUpdateFuture) Result(client TopicsClient) (t Topic, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("eventgrid.TopicsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if t.Response.Response, err = future.GetResult(sender); err == nil && t.Response.Response.StatusCode != http.StatusNoContent { + t, err = client.UpdateResponder(t.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsUpdateFuture", "Result", t.Response.Response, "Failure responding to request") + } + } + return +} + +// TopicTypeInfo properties of a topic type info. +type TopicTypeInfo struct { + autorest.Response `json:"-"` + // TopicTypeProperties - Properties of the topic type info + *TopicTypeProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TopicTypeInfo. +func (tti TopicTypeInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tti.TopicTypeProperties != nil { + objectMap["properties"] = tti.TopicTypeProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for TopicTypeInfo struct. +func (tti *TopicTypeInfo) 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 topicTypeProperties TopicTypeProperties + err = json.Unmarshal(*v, &topicTypeProperties) + if err != nil { + return err + } + tti.TopicTypeProperties = &topicTypeProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + tti.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + tti.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + tti.Type = &typeVar + } + } + } + + return nil +} + +// TopicTypeProperties properties of a topic type. +type TopicTypeProperties struct { + // Provider - Namespace of the provider of the topic type. + Provider *string `json:"provider,omitempty"` + // DisplayName - Display Name for the topic type. + DisplayName *string `json:"displayName,omitempty"` + // Description - Description of the topic type. + Description *string `json:"description,omitempty"` + // ResourceRegionType - Region type of the resource. Possible values include: 'RegionalResource', 'GlobalResource' + ResourceRegionType ResourceRegionType `json:"resourceRegionType,omitempty"` + // ProvisioningState - Provisioning state of the topic type. Possible values include: 'TopicTypeProvisioningStateCreating', 'TopicTypeProvisioningStateUpdating', 'TopicTypeProvisioningStateDeleting', 'TopicTypeProvisioningStateSucceeded', 'TopicTypeProvisioningStateCanceled', 'TopicTypeProvisioningStateFailed' + ProvisioningState TopicTypeProvisioningState `json:"provisioningState,omitempty"` + // SupportedLocations - List of locations supported by this topic type. + SupportedLocations *[]string `json:"supportedLocations,omitempty"` + // SourceResourceFormat - Source resource format. + SourceResourceFormat *string `json:"sourceResourceFormat,omitempty"` +} + +// TopicTypesListResult result of the List Topic Types operation +type TopicTypesListResult struct { + autorest.Response `json:"-"` + // Value - A collection of topic types + Value *[]TopicTypeInfo `json:"value,omitempty"` +} + +// TopicUpdateParameterProperties information of topic update parameter properties. +type TopicUpdateParameterProperties struct { + // PublicNetworkAccess - This determines if traffic is allowed over public network. By default it is enabled. + // You can further restrict to specific IPs by configuring . Possible values include: 'Enabled', 'Disabled' + PublicNetworkAccess PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + // InboundIPRules - This can be used to restrict traffic from specific IPs instead of all IPs. Note: These are considered only if PublicNetworkAccess is enabled. + InboundIPRules *[]InboundIPRule `json:"inboundIpRules,omitempty"` +} + +// TopicUpdateParameters properties of the Topic update +type TopicUpdateParameters struct { + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // Identity - Resource identity information. + Identity *IdentityInfo `json:"identity,omitempty"` + // TopicUpdateParameterProperties - Properties of the resource. + *TopicUpdateParameterProperties `json:"properties,omitempty"` + // Sku - The Sku pricing tier for the topic. + Sku *ResourceSku `json:"sku,omitempty"` +} + +// MarshalJSON is the custom marshaler for TopicUpdateParameters. +func (tup TopicUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tup.Tags != nil { + objectMap["tags"] = tup.Tags + } + if tup.Identity != nil { + objectMap["identity"] = tup.Identity + } + if tup.TopicUpdateParameterProperties != nil { + objectMap["properties"] = tup.TopicUpdateParameterProperties + } + if tup.Sku != nil { + objectMap["sku"] = tup.Sku + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for TopicUpdateParameters struct. +func (tup *TopicUpdateParameters) 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 "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + tup.Tags = tags + } + case "identity": + if v != nil { + var identity IdentityInfo + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + tup.Identity = &identity + } + case "properties": + if v != nil { + var topicUpdateParameterProperties TopicUpdateParameterProperties + err = json.Unmarshal(*v, &topicUpdateParameterProperties) + if err != nil { + return err + } + tup.TopicUpdateParameterProperties = &topicUpdateParameterProperties + } + case "sku": + if v != nil { + var sku ResourceSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + tup.Sku = &sku + } + } + } + + return nil +} + +// TrackedResource definition of a Tracked Resource. +type TrackedResource struct { + // Location - Location of the resource. + Location *string `json:"location,omitempty"` + // Tags - Tags of the resource. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Fully qualified identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Name of the resource + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Type of the resource + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TrackedResource. +func (tr TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tr.Location != nil { + objectMap["location"] = tr.Location + } + if tr.Tags != nil { + objectMap["tags"] = tr.Tags + } + return json.Marshal(objectMap) +} + +// UserIdentityProperties the information about the user identity. +type UserIdentityProperties struct { + // PrincipalID - The principal id of user assigned identity. + PrincipalID *string `json:"principalId,omitempty"` + // ClientID - The client id of user assigned identity. + ClientID *string `json:"clientId,omitempty"` +} + +// WebHookEventSubscriptionDestination information about the webhook destination for an event subscription. +type WebHookEventSubscriptionDestination struct { + // WebHookEventSubscriptionDestinationProperties - WebHook Properties of the event subscription destination. + *WebHookEventSubscriptionDestinationProperties `json:"properties,omitempty"` + // EndpointType - Possible values include: 'EndpointTypeEventSubscriptionDestination', 'EndpointTypeWebHook', 'EndpointTypeEventHub', 'EndpointTypeStorageQueue', 'EndpointTypeHybridConnection', 'EndpointTypeServiceBusQueue', 'EndpointTypeServiceBusTopic', 'EndpointTypeAzureFunction' + EndpointType EndpointType `json:"endpointType,omitempty"` +} + +// MarshalJSON is the custom marshaler for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) MarshalJSON() ([]byte, error) { + whesd.EndpointType = EndpointTypeWebHook + objectMap := make(map[string]interface{}) + if whesd.WebHookEventSubscriptionDestinationProperties != nil { + objectMap["properties"] = whesd.WebHookEventSubscriptionDestinationProperties + } + if whesd.EndpointType != "" { + objectMap["endpointType"] = whesd.EndpointType + } + return json.Marshal(objectMap) +} + +// AsWebHookEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsWebHookEventSubscriptionDestination() (*WebHookEventSubscriptionDestination, bool) { + return &whesd, true +} + +// AsEventHubEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsEventHubEventSubscriptionDestination() (*EventHubEventSubscriptionDestination, bool) { + return nil, false +} + +// AsStorageQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsStorageQueueEventSubscriptionDestination() (*StorageQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsHybridConnectionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsHybridConnectionEventSubscriptionDestination() (*HybridConnectionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusQueueEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsServiceBusQueueEventSubscriptionDestination() (*ServiceBusQueueEventSubscriptionDestination, bool) { + return nil, false +} + +// AsServiceBusTopicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsServiceBusTopicEventSubscriptionDestination() (*ServiceBusTopicEventSubscriptionDestination, bool) { + return nil, false +} + +// AsAzureFunctionEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsAzureFunctionEventSubscriptionDestination() (*AzureFunctionEventSubscriptionDestination, bool) { + return nil, false +} + +// AsEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsEventSubscriptionDestination() (*EventSubscriptionDestination, bool) { + return nil, false +} + +// AsBasicEventSubscriptionDestination is the BasicEventSubscriptionDestination implementation for WebHookEventSubscriptionDestination. +func (whesd WebHookEventSubscriptionDestination) AsBasicEventSubscriptionDestination() (BasicEventSubscriptionDestination, bool) { + return &whesd, true +} + +// UnmarshalJSON is the custom unmarshaler for WebHookEventSubscriptionDestination struct. +func (whesd *WebHookEventSubscriptionDestination) 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 webHookEventSubscriptionDestinationProperties WebHookEventSubscriptionDestinationProperties + err = json.Unmarshal(*v, &webHookEventSubscriptionDestinationProperties) + if err != nil { + return err + } + whesd.WebHookEventSubscriptionDestinationProperties = &webHookEventSubscriptionDestinationProperties + } + case "endpointType": + if v != nil { + var endpointType EndpointType + err = json.Unmarshal(*v, &endpointType) + if err != nil { + return err + } + whesd.EndpointType = endpointType + } + } + } + + return nil +} + +// WebHookEventSubscriptionDestinationProperties information about the webhook destination properties for +// an event subscription. +type WebHookEventSubscriptionDestinationProperties struct { + // EndpointURL - The URL that represents the endpoint of the destination of an event subscription. + EndpointURL *string `json:"endpointUrl,omitempty"` + // EndpointBaseURL - READ-ONLY; The base URL that represents the endpoint of the destination of an event subscription. + EndpointBaseURL *string `json:"endpointBaseUrl,omitempty"` + // MaxEventsPerBatch - Maximum number of events per batch. + MaxEventsPerBatch *int32 `json:"maxEventsPerBatch,omitempty"` + // PreferredBatchSizeInKilobytes - Preferred batch size in Kilobytes. + PreferredBatchSizeInKilobytes *int32 `json:"preferredBatchSizeInKilobytes,omitempty"` + // AzureActiveDirectoryTenantID - The Azure Active Directory Tenant ID to get the access token that will be included as the bearer token in delivery requests. + AzureActiveDirectoryTenantID *string `json:"azureActiveDirectoryTenantId,omitempty"` + // AzureActiveDirectoryApplicationIDOrURI - The Azure Active Directory Application ID or URI to get the access token that will be included as the bearer token in delivery requests. + AzureActiveDirectoryApplicationIDOrURI *string `json:"azureActiveDirectoryApplicationIdOrUri,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/operations.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/operations.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/operations.go index 01730ff5f85bf..23de4c32a9caa 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/operations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/operations.go @@ -41,7 +41,7 @@ func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) Opera return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// List list the available operations supported by the Microsoft.EventGrid resource provider +// List list the available operations supported by the Microsoft.EventGrid resource provider. func (client OperationsClient) List(ctx context.Context) (result OperationsListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") @@ -76,7 +76,7 @@ func (client OperationsClient) List(ctx context.Context) (result OperationsListR // ListPreparer prepares the List request. func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnernamespaces.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnernamespaces.go new file mode 100644 index 0000000000000..bc2406c8b0413 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnernamespaces.go @@ -0,0 +1,764 @@ +package eventgrid + +// 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" +) + +// PartnerNamespacesClient is the azure EventGrid Management Client +type PartnerNamespacesClient struct { + BaseClient +} + +// NewPartnerNamespacesClient creates an instance of the PartnerNamespacesClient client. +func NewPartnerNamespacesClient(subscriptionID string) PartnerNamespacesClient { + return NewPartnerNamespacesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPartnerNamespacesClientWithBaseURI creates an instance of the PartnerNamespacesClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewPartnerNamespacesClientWithBaseURI(baseURI string, subscriptionID string) PartnerNamespacesClient { + return PartnerNamespacesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate asynchronously creates a new partner namespace with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// partnerNamespaceInfo - partnerNamespace information. +func (client PartnerNamespacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, partnerNamespaceName string, partnerNamespaceInfo PartnerNamespace) (result PartnerNamespacesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, partnerNamespaceName, partnerNamespaceInfo) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PartnerNamespacesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, partnerNamespaceInfo PartnerNamespace) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/partnerNamespaces/{partnerNamespaceName}", pathParameters), + autorest.WithJSON(partnerNamespaceInfo), + 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 PartnerNamespacesClient) CreateOrUpdateSender(req *http.Request) (future PartnerNamespacesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 PartnerNamespacesClient) CreateOrUpdateResponder(resp *http.Response) (result PartnerNamespace, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete existing partner namespace. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +func (client PartnerNamespacesClient) Delete(ctx context.Context, resourceGroupName string, partnerNamespaceName string) (result PartnerNamespacesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, partnerNamespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PartnerNamespacesClient) DeletePreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}", 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 PartnerNamespacesClient) DeleteSender(req *http.Request) (future PartnerNamespacesDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 PartnerNamespacesClient) 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 get properties of a partner namespace. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +func (client PartnerNamespacesClient) Get(ctx context.Context, resourceGroupName string, partnerNamespaceName string) (result PartnerNamespace, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, partnerNamespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PartnerNamespacesClient) GetPreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}", 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 PartnerNamespacesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PartnerNamespacesClient) GetResponder(resp *http.Response) (result PartnerNamespace, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup list all the partner namespaces under a resource group. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerNamespacesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result PartnerNamespacesListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.pnlr.Response.Response != nil { + sc = result.pnlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.pnlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.pnlr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client PartnerNamespacesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces", 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 PartnerNamespacesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client PartnerNamespacesClient) ListByResourceGroupResponder(resp *http.Response) (result PartnerNamespacesListResult, 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 PartnerNamespacesClient) listByResourceGroupNextResults(ctx context.Context, lastResults PartnerNamespacesListResult) (result PartnerNamespacesListResult, err error) { + req, err := lastResults.partnerNamespacesListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "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, "eventgrid.PartnerNamespacesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerNamespacesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result PartnerNamespacesListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.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, filter, top) + return +} + +// ListBySubscription list all the partner namespaces under an Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerNamespacesClient) ListBySubscription(ctx context.Context, filter string, top *int32) (result PartnerNamespacesListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.ListBySubscription") + defer func() { + sc := -1 + if result.pnlr.Response.Response != nil { + sc = result.pnlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.pnlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.pnlr, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client PartnerNamespacesClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.EventGrid/partnerNamespaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerNamespacesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client PartnerNamespacesClient) ListBySubscriptionResponder(resp *http.Response) (result PartnerNamespacesListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client PartnerNamespacesClient) listBySubscriptionNextResults(ctx context.Context, lastResults PartnerNamespacesListResult) (result PartnerNamespacesListResult, err error) { + req, err := lastResults.partnerNamespacesListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerNamespacesClient) ListBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result PartnerNamespacesListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.ListBySubscription") + 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.ListBySubscription(ctx, filter, top) + return +} + +// ListSharedAccessKeys list the two keys used to publish to a partner namespace. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +func (client PartnerNamespacesClient) ListSharedAccessKeys(ctx context.Context, resourceGroupName string, partnerNamespaceName string) (result PartnerNamespaceSharedAccessKeys, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.ListSharedAccessKeys") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListSharedAccessKeysPreparer(ctx, resourceGroupName, partnerNamespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListSharedAccessKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListSharedAccessKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListSharedAccessKeys", resp, "Failure sending request") + return + } + + result, err = client.ListSharedAccessKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "ListSharedAccessKeys", resp, "Failure responding to request") + } + + return +} + +// ListSharedAccessKeysPreparer prepares the ListSharedAccessKeys request. +func (client PartnerNamespacesClient) ListSharedAccessKeysPreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}/listKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSharedAccessKeysSender sends the ListSharedAccessKeys request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerNamespacesClient) ListSharedAccessKeysSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListSharedAccessKeysResponder handles the response to the ListSharedAccessKeys request. The method always +// closes the http.Response Body. +func (client PartnerNamespacesClient) ListSharedAccessKeysResponder(resp *http.Response) (result PartnerNamespaceSharedAccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateKey regenerate a shared access key for a partner namespace. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// regenerateKeyRequest - request body to regenerate key. +func (client PartnerNamespacesClient) RegenerateKey(ctx context.Context, resourceGroupName string, partnerNamespaceName string, regenerateKeyRequest PartnerNamespaceRegenerateKeyRequest) (result PartnerNamespaceSharedAccessKeys, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.RegenerateKey") + 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: regenerateKeyRequest, + Constraints: []validation.Constraint{{Target: "regenerateKeyRequest.KeyName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("eventgrid.PartnerNamespacesClient", "RegenerateKey", err.Error()) + } + + req, err := client.RegenerateKeyPreparer(ctx, resourceGroupName, partnerNamespaceName, regenerateKeyRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "RegenerateKey", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateKeySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "RegenerateKey", resp, "Failure sending request") + return + } + + result, err = client.RegenerateKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "RegenerateKey", resp, "Failure responding to request") + } + + return +} + +// RegenerateKeyPreparer prepares the RegenerateKey request. +func (client PartnerNamespacesClient) RegenerateKeyPreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, regenerateKeyRequest PartnerNamespaceRegenerateKeyRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/partnerNamespaces/{partnerNamespaceName}/regenerateKey", pathParameters), + autorest.WithJSON(regenerateKeyRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RegenerateKeySender sends the RegenerateKey request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerNamespacesClient) RegenerateKeySender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// RegenerateKeyResponder handles the response to the RegenerateKey request. The method always +// closes the http.Response Body. +func (client PartnerNamespacesClient) RegenerateKeyResponder(resp *http.Response) (result PartnerNamespaceSharedAccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update asynchronously updates a partner namespace with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerNamespaceName - name of the partner namespace. +// partnerNamespaceUpdateParameters - partner namespace update information. +func (client PartnerNamespacesClient) Update(ctx context.Context, resourceGroupName string, partnerNamespaceName string, partnerNamespaceUpdateParameters PartnerNamespaceUpdateParameters) (result PartnerNamespacesUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerNamespacesClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, partnerNamespaceName, partnerNamespaceUpdateParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerNamespacesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PartnerNamespacesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, partnerNamespaceName string, partnerNamespaceUpdateParameters PartnerNamespaceUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerNamespaceName": autorest.Encode("path", partnerNamespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerNamespaces/{partnerNamespaceName}", pathParameters), + autorest.WithJSON(partnerNamespaceUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerNamespacesClient) UpdateSender(req *http.Request) (future PartnerNamespacesUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PartnerNamespacesClient) UpdateResponder(resp *http.Response) (result PartnerNamespace, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnerregistrations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnerregistrations.go new file mode 100644 index 0000000000000..16b202f9eadfd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnerregistrations.go @@ -0,0 +1,669 @@ +package eventgrid + +// 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" +) + +// PartnerRegistrationsClient is the azure EventGrid Management Client +type PartnerRegistrationsClient struct { + BaseClient +} + +// NewPartnerRegistrationsClient creates an instance of the PartnerRegistrationsClient client. +func NewPartnerRegistrationsClient(subscriptionID string) PartnerRegistrationsClient { + return NewPartnerRegistrationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPartnerRegistrationsClientWithBaseURI creates an instance of the PartnerRegistrationsClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewPartnerRegistrationsClientWithBaseURI(baseURI string, subscriptionID string) PartnerRegistrationsClient { + return PartnerRegistrationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new partner registration with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerRegistrationName - name of the partner registration. +// partnerRegistrationInfo - partnerRegistration information. +func (client PartnerRegistrationsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, partnerRegistrationName string, partnerRegistrationInfo PartnerRegistration) (result PartnerRegistration, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, partnerRegistrationName, partnerRegistrationInfo) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PartnerRegistrationsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, partnerRegistrationName string, partnerRegistrationInfo PartnerRegistration) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerRegistrationName": autorest.Encode("path", partnerRegistrationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/partnerRegistrations/{partnerRegistrationName}", pathParameters), + autorest.WithJSON(partnerRegistrationInfo), + 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 PartnerRegistrationsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) CreateOrUpdateResponder(resp *http.Response) (result PartnerRegistration, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a partner registration with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerRegistrationName - name of the partner registration. +func (client PartnerRegistrationsClient) Delete(ctx context.Context, resourceGroupName string, partnerRegistrationName string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, partnerRegistrationName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PartnerRegistrationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, partnerRegistrationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerRegistrationName": autorest.Encode("path", partnerRegistrationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerRegistrations/{partnerRegistrationName}", 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 PartnerRegistrationsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) 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 partner registration with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerRegistrationName - name of the partner registration. +func (client PartnerRegistrationsClient) Get(ctx context.Context, resourceGroupName string, partnerRegistrationName string) (result PartnerRegistration, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, partnerRegistrationName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PartnerRegistrationsClient) GetPreparer(ctx context.Context, resourceGroupName string, partnerRegistrationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerRegistrationName": autorest.Encode("path", partnerRegistrationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerRegistrations/{partnerRegistrationName}", 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 PartnerRegistrationsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) GetResponder(resp *http.Response) (result PartnerRegistration, 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 list all partners registrations. +func (client PartnerRegistrationsClient) List(ctx context.Context) (result PartnerRegistrationsListResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.List") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client PartnerRegistrationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.EventGrid/partnerRegistrations"), + 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 PartnerRegistrationsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) ListResponder(resp *http.Response) (result PartnerRegistrationsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup list all the partner registrations under a resource group. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerRegistrationsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result PartnerRegistrationsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.prlr.Response.Response != nil { + sc = result.prlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.prlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.prlr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client PartnerRegistrationsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerRegistrations", 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 PartnerRegistrationsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) ListByResourceGroupResponder(resp *http.Response) (result PartnerRegistrationsListResult, 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 PartnerRegistrationsClient) listByResourceGroupNextResults(ctx context.Context, lastResults PartnerRegistrationsListResult) (result PartnerRegistrationsListResult, err error) { + req, err := lastResults.partnerRegistrationsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "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, "eventgrid.PartnerRegistrationsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerRegistrationsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result PartnerRegistrationsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.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, filter, top) + return +} + +// ListBySubscription list all the partner registrations under an Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerRegistrationsClient) ListBySubscription(ctx context.Context, filter string, top *int32) (result PartnerRegistrationsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.ListBySubscription") + defer func() { + sc := -1 + if result.prlr.Response.Response != nil { + sc = result.prlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.prlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.prlr, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client PartnerRegistrationsClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.EventGrid/partnerRegistrations", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerRegistrationsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) ListBySubscriptionResponder(resp *http.Response) (result PartnerRegistrationsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client PartnerRegistrationsClient) listBySubscriptionNextResults(ctx context.Context, lastResults PartnerRegistrationsListResult) (result PartnerRegistrationsListResult, err error) { + req, err := lastResults.partnerRegistrationsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerRegistrationsClient) ListBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result PartnerRegistrationsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.ListBySubscription") + 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.ListBySubscription(ctx, filter, top) + return +} + +// Update updates a partner registration with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerRegistrationName - name of the partner registration. +// partnerRegistrationUpdateParameters - partner registration update information. +func (client PartnerRegistrationsClient) Update(ctx context.Context, resourceGroupName string, partnerRegistrationName string, partnerRegistrationUpdateParameters PartnerRegistrationUpdateParameters) (result PartnerRegistration, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerRegistrationsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, partnerRegistrationName, partnerRegistrationUpdateParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerRegistrationsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PartnerRegistrationsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, partnerRegistrationName string, partnerRegistrationUpdateParameters PartnerRegistrationUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerRegistrationName": autorest.Encode("path", partnerRegistrationName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerRegistrations/{partnerRegistrationName}", pathParameters), + autorest.WithJSON(partnerRegistrationUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerRegistrationsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PartnerRegistrationsClient) UpdateResponder(resp *http.Response) (result PartnerRegistration, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopiceventsubscriptions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopiceventsubscriptions.go new file mode 100644 index 0000000000000..e671270460ec0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopiceventsubscriptions.go @@ -0,0 +1,572 @@ +package eventgrid + +// 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" +) + +// PartnerTopicEventSubscriptionsClient is the azure EventGrid Management Client +type PartnerTopicEventSubscriptionsClient struct { + BaseClient +} + +// NewPartnerTopicEventSubscriptionsClient creates an instance of the PartnerTopicEventSubscriptionsClient client. +func NewPartnerTopicEventSubscriptionsClient(subscriptionID string) PartnerTopicEventSubscriptionsClient { + return NewPartnerTopicEventSubscriptionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPartnerTopicEventSubscriptionsClientWithBaseURI creates an instance of the PartnerTopicEventSubscriptionsClient +// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI +// (sovereign clouds, Azure stack). +func NewPartnerTopicEventSubscriptionsClientWithBaseURI(baseURI string, subscriptionID string) PartnerTopicEventSubscriptionsClient { + return PartnerTopicEventSubscriptionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate asynchronously creates or updates an event subscription of a partner topic with the specified +// parameters. Existing event subscriptions will be updated with this API. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +// eventSubscriptionInfo - event subscription properties containing the destination and filter information. +func (client PartnerTopicEventSubscriptionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string, eventSubscriptionInfo EventSubscription) (result PartnerTopicEventSubscriptionsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, partnerTopicName, eventSubscriptionName, eventSubscriptionInfo) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PartnerTopicEventSubscriptionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string, eventSubscriptionInfo EventSubscription) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/partnerTopics/{partnerTopicName}/eventSubscriptions/{eventSubscriptionName}", pathParameters), + autorest.WithJSON(eventSubscriptionInfo), + 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 PartnerTopicEventSubscriptionsClient) CreateOrUpdateSender(req *http.Request) (future PartnerTopicEventSubscriptionsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 PartnerTopicEventSubscriptionsClient) CreateOrUpdateResponder(resp *http.Response) (result EventSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete an event subscription of a partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +func (client PartnerTopicEventSubscriptionsClient) Delete(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string) (result PartnerTopicEventSubscriptionsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, partnerTopicName, eventSubscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PartnerTopicEventSubscriptionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/eventSubscriptions/{eventSubscriptionName}", 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 PartnerTopicEventSubscriptionsClient) DeleteSender(req *http.Request) (future PartnerTopicEventSubscriptionsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 PartnerTopicEventSubscriptionsClient) 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 get an event subscription of a partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// eventSubscriptionName - name of the event subscription to be found. Event subscription names must be between +// 3 and 100 characters in length and use alphanumeric letters only. +func (client PartnerTopicEventSubscriptionsClient) Get(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string) (result EventSubscription, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, partnerTopicName, eventSubscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PartnerTopicEventSubscriptionsClient) GetPreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/eventSubscriptions/{eventSubscriptionName}", 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 PartnerTopicEventSubscriptionsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PartnerTopicEventSubscriptionsClient) GetResponder(resp *http.Response) (result EventSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetFullURL get the full endpoint URL for an event subscription of a partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +func (client PartnerTopicEventSubscriptionsClient) GetFullURL(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string) (result EventSubscriptionFullURL, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.GetFullURL") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetFullURLPreparer(ctx, resourceGroupName, partnerTopicName, eventSubscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "GetFullURL", nil, "Failure preparing request") + return + } + + resp, err := client.GetFullURLSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "GetFullURL", resp, "Failure sending request") + return + } + + result, err = client.GetFullURLResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "GetFullURL", resp, "Failure responding to request") + } + + return +} + +// GetFullURLPreparer prepares the GetFullURL request. +func (client PartnerTopicEventSubscriptionsClient) GetFullURLPreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/eventSubscriptions/{eventSubscriptionName}/getFullUrl", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetFullURLSender sends the GetFullURL request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicEventSubscriptionsClient) GetFullURLSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetFullURLResponder handles the response to the GetFullURL request. The method always +// closes the http.Response Body. +func (client PartnerTopicEventSubscriptionsClient) GetFullURLResponder(resp *http.Response) (result EventSubscriptionFullURL, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByPartnerTopic list event subscriptions that belong to a specific partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerTopicEventSubscriptionsClient) ListByPartnerTopic(ctx context.Context, resourceGroupName string, partnerTopicName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.ListByPartnerTopic") + defer func() { + sc := -1 + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByPartnerTopicNextResults + req, err := client.ListByPartnerTopicPreparer(ctx, resourceGroupName, partnerTopicName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "ListByPartnerTopic", nil, "Failure preparing request") + return + } + + resp, err := client.ListByPartnerTopicSender(req) + if err != nil { + result.eslr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "ListByPartnerTopic", resp, "Failure sending request") + return + } + + result.eslr, err = client.ListByPartnerTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "ListByPartnerTopic", resp, "Failure responding to request") + } + + return +} + +// ListByPartnerTopicPreparer prepares the ListByPartnerTopic request. +func (client PartnerTopicEventSubscriptionsClient) ListByPartnerTopicPreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/eventSubscriptions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByPartnerTopicSender sends the ListByPartnerTopic request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicEventSubscriptionsClient) ListByPartnerTopicSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByPartnerTopicResponder handles the response to the ListByPartnerTopic request. The method always +// closes the http.Response Body. +func (client PartnerTopicEventSubscriptionsClient) ListByPartnerTopicResponder(resp *http.Response) (result EventSubscriptionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByPartnerTopicNextResults retrieves the next set of results, if any. +func (client PartnerTopicEventSubscriptionsClient) listByPartnerTopicNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "listByPartnerTopicNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByPartnerTopicSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "listByPartnerTopicNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByPartnerTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "listByPartnerTopicNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByPartnerTopicComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerTopicEventSubscriptionsClient) ListByPartnerTopicComplete(ctx context.Context, resourceGroupName string, partnerTopicName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.ListByPartnerTopic") + 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.ListByPartnerTopic(ctx, resourceGroupName, partnerTopicName, filter, top) + return +} + +// Update update event subscription of a partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +// eventSubscriptionUpdateParameters - updated event subscription information. +func (client PartnerTopicEventSubscriptionsClient) Update(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string, eventSubscriptionUpdateParameters EventSubscriptionUpdateParameters) (result PartnerTopicEventSubscriptionsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicEventSubscriptionsClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, partnerTopicName, eventSubscriptionName, eventSubscriptionUpdateParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicEventSubscriptionsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PartnerTopicEventSubscriptionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, eventSubscriptionName string, eventSubscriptionUpdateParameters EventSubscriptionUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/eventSubscriptions/{eventSubscriptionName}", pathParameters), + autorest.WithJSON(eventSubscriptionUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicEventSubscriptionsClient) UpdateSender(req *http.Request) (future PartnerTopicEventSubscriptionsUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PartnerTopicEventSubscriptionsClient) UpdateResponder(resp *http.Response) (result EventSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopics.go new file mode 100644 index 0000000000000..ebeb31ae4742d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/partnertopics.go @@ -0,0 +1,674 @@ +package eventgrid + +// 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" +) + +// PartnerTopicsClient is the azure EventGrid Management Client +type PartnerTopicsClient struct { + BaseClient +} + +// NewPartnerTopicsClient creates an instance of the PartnerTopicsClient client. +func NewPartnerTopicsClient(subscriptionID string) PartnerTopicsClient { + return NewPartnerTopicsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPartnerTopicsClientWithBaseURI creates an instance of the PartnerTopicsClient client using a custom endpoint. +// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewPartnerTopicsClientWithBaseURI(baseURI string, subscriptionID string) PartnerTopicsClient { + return PartnerTopicsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Activate activate a newly created partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +func (client PartnerTopicsClient) Activate(ctx context.Context, resourceGroupName string, partnerTopicName string) (result PartnerTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.Activate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ActivatePreparer(ctx, resourceGroupName, partnerTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Activate", nil, "Failure preparing request") + return + } + + resp, err := client.ActivateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Activate", resp, "Failure sending request") + return + } + + result, err = client.ActivateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Activate", resp, "Failure responding to request") + } + + return +} + +// ActivatePreparer prepares the Activate request. +func (client PartnerTopicsClient) ActivatePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/activate", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ActivateSender sends the Activate request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicsClient) ActivateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ActivateResponder handles the response to the Activate request. The method always +// closes the http.Response Body. +func (client PartnerTopicsClient) ActivateResponder(resp *http.Response) (result PartnerTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Deactivate deactivate specific partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +func (client PartnerTopicsClient) Deactivate(ctx context.Context, resourceGroupName string, partnerTopicName string) (result PartnerTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.Deactivate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeactivatePreparer(ctx, resourceGroupName, partnerTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Deactivate", nil, "Failure preparing request") + return + } + + resp, err := client.DeactivateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Deactivate", resp, "Failure sending request") + return + } + + result, err = client.DeactivateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Deactivate", resp, "Failure responding to request") + } + + return +} + +// DeactivatePreparer prepares the Deactivate request. +func (client PartnerTopicsClient) DeactivatePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}/deactivate", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeactivateSender sends the Deactivate request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicsClient) DeactivateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// DeactivateResponder handles the response to the Deactivate request. The method always +// closes the http.Response Body. +func (client PartnerTopicsClient) DeactivateResponder(resp *http.Response) (result PartnerTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete existing partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +func (client PartnerTopicsClient) Delete(ctx context.Context, resourceGroupName string, partnerTopicName string) (result PartnerTopicsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, partnerTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PartnerTopicsClient) DeletePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}", 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 PartnerTopicsClient) DeleteSender(req *http.Request) (future PartnerTopicsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 PartnerTopicsClient) 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 get properties of a partner topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +func (client PartnerTopicsClient) Get(ctx context.Context, resourceGroupName string, partnerTopicName string) (result PartnerTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, partnerTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PartnerTopicsClient) GetPreparer(ctx context.Context, resourceGroupName string, partnerTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}", 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 PartnerTopicsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PartnerTopicsClient) GetResponder(resp *http.Response) (result PartnerTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup list all the partner topics under a resource group. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerTopicsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result PartnerTopicsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.ptlr.Response.Response != nil { + sc = result.ptlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.ptlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.ptlr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client PartnerTopicsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics", 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 PartnerTopicsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client PartnerTopicsClient) ListByResourceGroupResponder(resp *http.Response) (result PartnerTopicsListResult, 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 PartnerTopicsClient) listByResourceGroupNextResults(ctx context.Context, lastResults PartnerTopicsListResult) (result PartnerTopicsListResult, err error) { + req, err := lastResults.partnerTopicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "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, "eventgrid.PartnerTopicsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerTopicsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result PartnerTopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.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, filter, top) + return +} + +// ListBySubscription list all the partner topics under an Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PartnerTopicsClient) ListBySubscription(ctx context.Context, filter string, top *int32) (result PartnerTopicsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.ListBySubscription") + defer func() { + sc := -1 + if result.ptlr.Response.Response != nil { + sc = result.ptlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.ptlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.ptlr, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client PartnerTopicsClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.EventGrid/partnerTopics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client PartnerTopicsClient) ListBySubscriptionResponder(resp *http.Response) (result PartnerTopicsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client PartnerTopicsClient) listBySubscriptionNextResults(ctx context.Context, lastResults PartnerTopicsListResult) (result PartnerTopicsListResult, err error) { + req, err := lastResults.partnerTopicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client PartnerTopicsClient) ListBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result PartnerTopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.ListBySubscription") + 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.ListBySubscription(ctx, filter, top) + return +} + +// Update asynchronously updates a partner topic with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// partnerTopicName - name of the partner topic. +// partnerTopicUpdateParameters - partnerTopic update information. +func (client PartnerTopicsClient) Update(ctx context.Context, resourceGroupName string, partnerTopicName string, partnerTopicUpdateParameters PartnerTopicUpdateParameters) (result PartnerTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PartnerTopicsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, partnerTopicName, partnerTopicUpdateParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PartnerTopicsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PartnerTopicsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, partnerTopicName string, partnerTopicUpdateParameters PartnerTopicUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "partnerTopicName": autorest.Encode("path", partnerTopicName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/partnerTopics/{partnerTopicName}", pathParameters), + autorest.WithJSON(partnerTopicUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client PartnerTopicsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PartnerTopicsClient) UpdateResponder(resp *http.Response) (result PartnerTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/privateendpointconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/privateendpointconnections.go new file mode 100644 index 0000000000000..f9912cc250b9f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/privateendpointconnections.go @@ -0,0 +1,415 @@ +package eventgrid + +// 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" +) + +// PrivateEndpointConnectionsClient is the azure EventGrid Management Client +type PrivateEndpointConnectionsClient struct { + BaseClient +} + +// NewPrivateEndpointConnectionsClient creates an instance of the PrivateEndpointConnectionsClient client. +func NewPrivateEndpointConnectionsClient(subscriptionID string) PrivateEndpointConnectionsClient { + return NewPrivateEndpointConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPrivateEndpointConnectionsClientWithBaseURI creates an instance of the PrivateEndpointConnectionsClient client +// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign +// clouds, Azure stack). +func NewPrivateEndpointConnectionsClientWithBaseURI(baseURI string, subscriptionID string) PrivateEndpointConnectionsClient { + return PrivateEndpointConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Delete delete a specific private endpoint connection under a topic or domain. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// parentType - the type of the parent resource. This can be either \'topics\' or \'domains\'. +// parentName - the name of the parent resource (namely, either, the topic name or domain name). +// privateEndpointConnectionName - the name of the private endpoint connection connection. +func (client PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateEndpointConnectionName string) (result PrivateEndpointConnectionsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, parentType, parentName, privateEndpointConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PrivateEndpointConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateEndpointConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "parentName": autorest.Encode("path", parentName), + "parentType": autorest.Encode("path", parentType), + "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/{parentType}/{parentName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) DeleteSender(req *http.Request) (future PrivateEndpointConnectionsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 PrivateEndpointConnectionsClient) 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 get a specific private endpoint connection under a topic or domain. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// parentType - the type of the parent resource. This can be either \'topics\' or \'domains\'. +// parentName - the name of the parent resource (namely, either, the topic name or domain name). +// privateEndpointConnectionName - the name of the private endpoint connection connection. +func (client PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateEndpointConnectionName string) (result PrivateEndpointConnection, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, parentType, parentName, privateEndpointConnectionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PrivateEndpointConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateEndpointConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "parentName": autorest.Encode("path", parentName), + "parentType": autorest.Encode("path", parentType), + "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/{parentType}/{parentName}/privateEndpointConnections/{privateEndpointConnectionName}", 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 PrivateEndpointConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) GetResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResource get all private endpoint connections under a topic or domain. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// parentType - the type of the parent resource. This can be either \'topics\' or \'domains\'. +// parentName - the name of the parent resource (namely, either, the topic name or domain name). +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PrivateEndpointConnectionsClient) ListByResource(ctx context.Context, resourceGroupName string, parentType string, parentName string, filter string, top *int32) (result PrivateEndpointConnectionListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.ListByResource") + defer func() { + sc := -1 + if result.peclr.Response.Response != nil { + sc = result.peclr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceNextResults + req, err := client.ListByResourcePreparer(ctx, resourceGroupName, parentType, parentName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "ListByResource", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceSender(req) + if err != nil { + result.peclr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "ListByResource", resp, "Failure sending request") + return + } + + result.peclr, err = client.ListByResourceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "ListByResource", resp, "Failure responding to request") + } + + return +} + +// ListByResourcePreparer prepares the ListByResource request. +func (client PrivateEndpointConnectionsClient) ListByResourcePreparer(ctx context.Context, resourceGroupName string, parentType string, parentName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "parentName": autorest.Encode("path", parentName), + "parentType": autorest.Encode("path", parentType), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/{parentType}/{parentName}/privateEndpointConnections", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceSender sends the ListByResource request. The method will close the +// http.Response Body if it receives an error. +func (client PrivateEndpointConnectionsClient) ListByResourceSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceResponder handles the response to the ListByResource request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) ListByResourceResponder(resp *http.Response) (result PrivateEndpointConnectionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceNextResults retrieves the next set of results, if any. +func (client PrivateEndpointConnectionsClient) listByResourceNextResults(ctx context.Context, lastResults PrivateEndpointConnectionListResult) (result PrivateEndpointConnectionListResult, err error) { + req, err := lastResults.privateEndpointConnectionListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "listByResourceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "listByResourceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "listByResourceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceComplete enumerates all values, automatically crossing page boundaries as required. +func (client PrivateEndpointConnectionsClient) ListByResourceComplete(ctx context.Context, resourceGroupName string, parentType string, parentName string, filter string, top *int32) (result PrivateEndpointConnectionListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.ListByResource") + 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.ListByResource(ctx, resourceGroupName, parentType, parentName, filter, top) + return +} + +// Update update a specific private endpoint connection under a topic or domain. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// parentType - the type of the parent resource. This can be either \'topics\' or \'domains\'. +// parentName - the name of the parent resource (namely, either, the topic name or domain name). +// privateEndpointConnectionName - the name of the private endpoint connection connection. +// privateEndpointConnection - the private endpoint connection object to update. +func (client PrivateEndpointConnectionsClient) Update(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection) (result PrivateEndpointConnectionsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionsClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, parentType, parentName, privateEndpointConnectionName, privateEndpointConnection) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateEndpointConnectionsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PrivateEndpointConnectionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "parentName": autorest.Encode("path", parentName), + "parentType": autorest.Encode("path", parentType), + "privateEndpointConnectionName": autorest.Encode("path", privateEndpointConnectionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/{parentType}/{parentName}/privateEndpointConnections/{privateEndpointConnectionName}", pathParameters), + autorest.WithJSON(privateEndpointConnection), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client PrivateEndpointConnectionsClient) UpdateSender(req *http.Request) (future PrivateEndpointConnectionsUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PrivateEndpointConnectionsClient) UpdateResponder(resp *http.Response) (result PrivateEndpointConnection, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/privatelinkresources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/privatelinkresources.go new file mode 100644 index 0000000000000..a4e22f335a7af --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/privatelinkresources.go @@ -0,0 +1,253 @@ +package eventgrid + +// 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" +) + +// PrivateLinkResourcesClient is the azure EventGrid Management Client +type PrivateLinkResourcesClient struct { + BaseClient +} + +// NewPrivateLinkResourcesClient creates an instance of the PrivateLinkResourcesClient client. +func NewPrivateLinkResourcesClient(subscriptionID string) PrivateLinkResourcesClient { + return NewPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPrivateLinkResourcesClientWithBaseURI creates an instance of the PrivateLinkResourcesClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkResourcesClient { + return PrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get properties of a private link resource. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// parentType - the type of the parent resource. This can be either \'topics\' or \'domains\'. +// parentName - the name of the parent resource (namely, either, the topic name or domain name). +// privateLinkResourceName - the name of private link resource. +func (client PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateLinkResourceName string) (result PrivateLinkResource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, parentType, parentName, privateLinkResourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PrivateLinkResourcesClient) GetPreparer(ctx context.Context, resourceGroupName string, parentType string, parentName string, privateLinkResourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "parentName": autorest.Encode("path", parentName), + "parentType": autorest.Encode("path", parentType), + "privateLinkResourceName": autorest.Encode("path", privateLinkResourceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/{parentType}/{parentName}/privateLinkResources/{privateLinkResourceName}", 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 PrivateLinkResourcesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PrivateLinkResourcesClient) GetResponder(resp *http.Response) (result PrivateLinkResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResource list all the private link resources under a topic or domain. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// parentType - the type of the parent resource. This can be either \'topics\' or \'domains\'. +// parentName - the name of the parent resource (namely, either, the topic name or domain name). +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client PrivateLinkResourcesClient) ListByResource(ctx context.Context, resourceGroupName string, parentType string, parentName string, filter string, top *int32) (result PrivateLinkResourcesListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.ListByResource") + defer func() { + sc := -1 + if result.plrlr.Response.Response != nil { + sc = result.plrlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceNextResults + req, err := client.ListByResourcePreparer(ctx, resourceGroupName, parentType, parentName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "ListByResource", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceSender(req) + if err != nil { + result.plrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "ListByResource", resp, "Failure sending request") + return + } + + result.plrlr, err = client.ListByResourceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "ListByResource", resp, "Failure responding to request") + } + + return +} + +// ListByResourcePreparer prepares the ListByResource request. +func (client PrivateLinkResourcesClient) ListByResourcePreparer(ctx context.Context, resourceGroupName string, parentType string, parentName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "parentName": autorest.Encode("path", parentName), + "parentType": autorest.Encode("path", parentType), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/{parentType}/{parentName}/privateLinkResources", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceSender sends the ListByResource request. The method will close the +// http.Response Body if it receives an error. +func (client PrivateLinkResourcesClient) ListByResourceSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceResponder handles the response to the ListByResource request. The method always +// closes the http.Response Body. +func (client PrivateLinkResourcesClient) ListByResourceResponder(resp *http.Response) (result PrivateLinkResourcesListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceNextResults retrieves the next set of results, if any. +func (client PrivateLinkResourcesClient) listByResourceNextResults(ctx context.Context, lastResults PrivateLinkResourcesListResult) (result PrivateLinkResourcesListResult, err error) { + req, err := lastResults.privateLinkResourcesListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "listByResourceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "listByResourceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.PrivateLinkResourcesClient", "listByResourceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceComplete enumerates all values, automatically crossing page boundaries as required. +func (client PrivateLinkResourcesClient) ListByResourceComplete(ctx context.Context, resourceGroupName string, parentType string, parentName string, filter string, top *int32) (result PrivateLinkResourcesListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.ListByResource") + 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.ListByResource(ctx, resourceGroupName, parentType, parentName, filter, top) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopiceventsubscriptions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopiceventsubscriptions.go new file mode 100644 index 0000000000000..810b0c0c5c6ca --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopiceventsubscriptions.go @@ -0,0 +1,572 @@ +package eventgrid + +// 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" +) + +// SystemTopicEventSubscriptionsClient is the azure EventGrid Management Client +type SystemTopicEventSubscriptionsClient struct { + BaseClient +} + +// NewSystemTopicEventSubscriptionsClient creates an instance of the SystemTopicEventSubscriptionsClient client. +func NewSystemTopicEventSubscriptionsClient(subscriptionID string) SystemTopicEventSubscriptionsClient { + return NewSystemTopicEventSubscriptionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSystemTopicEventSubscriptionsClientWithBaseURI creates an instance of the SystemTopicEventSubscriptionsClient +// client using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI +// (sovereign clouds, Azure stack). +func NewSystemTopicEventSubscriptionsClientWithBaseURI(baseURI string, subscriptionID string) SystemTopicEventSubscriptionsClient { + return SystemTopicEventSubscriptionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate asynchronously creates or updates an event subscription with the specified parameters. Existing event +// subscriptions will be updated with this API. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +// eventSubscriptionInfo - event subscription properties containing the destination and filter information. +func (client SystemTopicEventSubscriptionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string, eventSubscriptionInfo EventSubscription) (result SystemTopicEventSubscriptionsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, systemTopicName, eventSubscriptionName, eventSubscriptionInfo) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SystemTopicEventSubscriptionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string, eventSubscriptionInfo EventSubscription) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/systemTopics/{systemTopicName}/eventSubscriptions/{eventSubscriptionName}", pathParameters), + autorest.WithJSON(eventSubscriptionInfo), + 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 SystemTopicEventSubscriptionsClient) CreateOrUpdateSender(req *http.Request) (future SystemTopicEventSubscriptionsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 SystemTopicEventSubscriptionsClient) CreateOrUpdateResponder(resp *http.Response) (result EventSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete an event subscription of a system topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +func (client SystemTopicEventSubscriptionsClient) Delete(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string) (result SystemTopicEventSubscriptionsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, systemTopicName, eventSubscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SystemTopicEventSubscriptionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}/eventSubscriptions/{eventSubscriptionName}", 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 SystemTopicEventSubscriptionsClient) DeleteSender(req *http.Request) (future SystemTopicEventSubscriptionsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 SystemTopicEventSubscriptionsClient) 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 get an event subscription. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +func (client SystemTopicEventSubscriptionsClient) Get(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string) (result EventSubscription, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, systemTopicName, eventSubscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SystemTopicEventSubscriptionsClient) GetPreparer(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}/eventSubscriptions/{eventSubscriptionName}", 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 SystemTopicEventSubscriptionsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SystemTopicEventSubscriptionsClient) GetResponder(resp *http.Response) (result EventSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetFullURL get the full endpoint URL for an event subscription of a system topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +func (client SystemTopicEventSubscriptionsClient) GetFullURL(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string) (result EventSubscriptionFullURL, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.GetFullURL") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetFullURLPreparer(ctx, resourceGroupName, systemTopicName, eventSubscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "GetFullURL", nil, "Failure preparing request") + return + } + + resp, err := client.GetFullURLSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "GetFullURL", resp, "Failure sending request") + return + } + + result, err = client.GetFullURLResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "GetFullURL", resp, "Failure responding to request") + } + + return +} + +// GetFullURLPreparer prepares the GetFullURL request. +func (client SystemTopicEventSubscriptionsClient) GetFullURLPreparer(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}/eventSubscriptions/{eventSubscriptionName}/getFullUrl", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetFullURLSender sends the GetFullURL request. The method will close the +// http.Response Body if it receives an error. +func (client SystemTopicEventSubscriptionsClient) GetFullURLSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetFullURLResponder handles the response to the GetFullURL request. The method always +// closes the http.Response Body. +func (client SystemTopicEventSubscriptionsClient) GetFullURLResponder(resp *http.Response) (result EventSubscriptionFullURL, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListBySystemTopic list event subscriptions that belong to a specific system topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client SystemTopicEventSubscriptionsClient) ListBySystemTopic(ctx context.Context, resourceGroupName string, systemTopicName string, filter string, top *int32) (result EventSubscriptionsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.ListBySystemTopic") + defer func() { + sc := -1 + if result.eslr.Response.Response != nil { + sc = result.eslr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySystemTopicNextResults + req, err := client.ListBySystemTopicPreparer(ctx, resourceGroupName, systemTopicName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "ListBySystemTopic", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySystemTopicSender(req) + if err != nil { + result.eslr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "ListBySystemTopic", resp, "Failure sending request") + return + } + + result.eslr, err = client.ListBySystemTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "ListBySystemTopic", resp, "Failure responding to request") + } + + return +} + +// ListBySystemTopicPreparer prepares the ListBySystemTopic request. +func (client SystemTopicEventSubscriptionsClient) ListBySystemTopicPreparer(ctx context.Context, resourceGroupName string, systemTopicName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}/eventSubscriptions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySystemTopicSender sends the ListBySystemTopic request. The method will close the +// http.Response Body if it receives an error. +func (client SystemTopicEventSubscriptionsClient) ListBySystemTopicSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySystemTopicResponder handles the response to the ListBySystemTopic request. The method always +// closes the http.Response Body. +func (client SystemTopicEventSubscriptionsClient) ListBySystemTopicResponder(resp *http.Response) (result EventSubscriptionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySystemTopicNextResults retrieves the next set of results, if any. +func (client SystemTopicEventSubscriptionsClient) listBySystemTopicNextResults(ctx context.Context, lastResults EventSubscriptionsListResult) (result EventSubscriptionsListResult, err error) { + req, err := lastResults.eventSubscriptionsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "listBySystemTopicNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySystemTopicSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "listBySystemTopicNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySystemTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "listBySystemTopicNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySystemTopicComplete enumerates all values, automatically crossing page boundaries as required. +func (client SystemTopicEventSubscriptionsClient) ListBySystemTopicComplete(ctx context.Context, resourceGroupName string, systemTopicName string, filter string, top *int32) (result EventSubscriptionsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.ListBySystemTopic") + 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.ListBySystemTopic(ctx, resourceGroupName, systemTopicName, filter, top) + return +} + +// Update update event subscription of a system topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// eventSubscriptionName - name of the event subscription to be created. Event subscription names must be +// between 3 and 100 characters in length and use alphanumeric letters only. +// eventSubscriptionUpdateParameters - updated event subscription information. +func (client SystemTopicEventSubscriptionsClient) Update(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string, eventSubscriptionUpdateParameters EventSubscriptionUpdateParameters) (result SystemTopicEventSubscriptionsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicEventSubscriptionsClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, systemTopicName, eventSubscriptionName, eventSubscriptionUpdateParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicEventSubscriptionsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client SystemTopicEventSubscriptionsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, systemTopicName string, eventSubscriptionName string, eventSubscriptionUpdateParameters EventSubscriptionUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventSubscriptionName": autorest.Encode("path", eventSubscriptionName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}/eventSubscriptions/{eventSubscriptionName}", pathParameters), + autorest.WithJSON(eventSubscriptionUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client SystemTopicEventSubscriptionsClient) UpdateSender(req *http.Request) (future SystemTopicEventSubscriptionsUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client SystemTopicEventSubscriptionsClient) UpdateResponder(resp *http.Response) (result EventSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopics.go new file mode 100644 index 0000000000000..3600438026c44 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/systemtopics.go @@ -0,0 +1,601 @@ +package eventgrid + +// 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" +) + +// SystemTopicsClient is the azure EventGrid Management Client +type SystemTopicsClient struct { + BaseClient +} + +// NewSystemTopicsClient creates an instance of the SystemTopicsClient client. +func NewSystemTopicsClient(subscriptionID string) SystemTopicsClient { + return NewSystemTopicsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSystemTopicsClientWithBaseURI creates an instance of the SystemTopicsClient client using a custom endpoint. Use +// this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewSystemTopicsClientWithBaseURI(baseURI string, subscriptionID string) SystemTopicsClient { + return SystemTopicsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate asynchronously creates a new system topic with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// systemTopicInfo - system Topic information. +func (client SystemTopicsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, systemTopicName string, systemTopicInfo SystemTopic) (result SystemTopicsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, systemTopicName, systemTopicInfo) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SystemTopicsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, systemTopicName string, systemTopicInfo SystemTopic) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + 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.EventGrid/systemTopics/{systemTopicName}", pathParameters), + autorest.WithJSON(systemTopicInfo), + 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 SystemTopicsClient) CreateOrUpdateSender(req *http.Request) (future SystemTopicsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 SystemTopicsClient) CreateOrUpdateResponder(resp *http.Response) (result SystemTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete existing system topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +func (client SystemTopicsClient) Delete(ctx context.Context, resourceGroupName string, systemTopicName string) (result SystemTopicsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, systemTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SystemTopicsClient) DeletePreparer(ctx context.Context, resourceGroupName string, systemTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}", 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 SystemTopicsClient) DeleteSender(req *http.Request) (future SystemTopicsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(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 SystemTopicsClient) 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 get properties of a system topic. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +func (client SystemTopicsClient) Get(ctx context.Context, resourceGroupName string, systemTopicName string) (result SystemTopic, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, systemTopicName) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SystemTopicsClient) GetPreparer(ctx context.Context, resourceGroupName string, systemTopicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}", 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 SystemTopicsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SystemTopicsClient) GetResponder(resp *http.Response) (result SystemTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup list all the system topics under a resource group. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client SystemTopicsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result SystemTopicsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.stlr.Response.Response != nil { + sc = result.stlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.stlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.stlr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client SystemTopicsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics", 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 SystemTopicsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client SystemTopicsClient) ListByResourceGroupResponder(resp *http.Response) (result SystemTopicsListResult, 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 SystemTopicsClient) listByResourceGroupNextResults(ctx context.Context, lastResults SystemTopicsListResult) (result SystemTopicsListResult, err error) { + req, err := lastResults.systemTopicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "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, "eventgrid.SystemTopicsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client SystemTopicsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result SystemTopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.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, filter, top) + return +} + +// ListBySubscription list all the system topics under an Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client SystemTopicsClient) ListBySubscription(ctx context.Context, filter string, top *int32) (result SystemTopicsListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.ListBySubscription") + defer func() { + sc := -1 + if result.stlr.Response.Response != nil { + sc = result.stlr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, filter, top) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.stlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.stlr, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client SystemTopicsClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.EventGrid/systemTopics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client SystemTopicsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client SystemTopicsClient) ListBySubscriptionResponder(resp *http.Response) (result SystemTopicsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client SystemTopicsClient) listBySubscriptionNextResults(ctx context.Context, lastResults SystemTopicsListResult) (result SystemTopicsListResult, err error) { + req, err := lastResults.systemTopicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client SystemTopicsClient) ListBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result SystemTopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.ListBySubscription") + 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.ListBySubscription(ctx, filter, top) + return +} + +// Update asynchronously updates a system topic with the specified parameters. +// Parameters: +// resourceGroupName - the name of the resource group within the user's subscription. +// systemTopicName - name of the system topic. +// systemTopicUpdateParameters - systemTopic update information. +func (client SystemTopicsClient) Update(ctx context.Context, resourceGroupName string, systemTopicName string, systemTopicUpdateParameters SystemTopicUpdateParameters) (result SystemTopicsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SystemTopicsClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, systemTopicName, systemTopicUpdateParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.SystemTopicsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client SystemTopicsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, systemTopicName string, systemTopicUpdateParameters SystemTopicUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "systemTopicName": autorest.Encode("path", systemTopicName), + } + + const APIVersion = "2020-04-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}", pathParameters), + autorest.WithJSON(systemTopicUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client SystemTopicsClient) UpdateSender(req *http.Request) (future SystemTopicsUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client SystemTopicsClient) UpdateResponder(resp *http.Response) (result SystemTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + 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/eventgrid/mgmt/2018-09-15-preview/eventgrid/topics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/topics.go similarity index 79% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/topics.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/topics.go index 9991b5b815e76..9e92c66874a14 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/topics.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/topics.go @@ -45,8 +45,8 @@ func NewTopicsClientWithBaseURI(baseURI string, subscriptionID string) TopicsCli // CreateOrUpdate asynchronously creates a new topic with the specified parameters. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicName - name of the topic -// topicInfo - topic information +// topicName - name of the topic. +// topicInfo - topic information. func (client TopicsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, topicName string, topicInfo Topic) (result TopicsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.CreateOrUpdate") @@ -81,7 +81,7 @@ func (client TopicsClient) CreateOrUpdatePreparer(ctx context.Context, resourceG "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -121,10 +121,10 @@ func (client TopicsClient) CreateOrUpdateResponder(resp *http.Response) (result return } -// Delete delete existing topic +// Delete delete existing topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicName - name of the topic +// topicName - name of the topic. func (client TopicsClient) Delete(ctx context.Context, resourceGroupName string, topicName string) (result TopicsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.Delete") @@ -159,7 +159,7 @@ func (client TopicsClient) DeletePreparer(ctx context.Context, resourceGroupName "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -196,10 +196,10 @@ func (client TopicsClient) DeleteResponder(resp *http.Response) (result autorest return } -// Get get properties of a topic +// Get get properties of a topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicName - name of the topic +// topicName - name of the topic. func (client TopicsClient) Get(ctx context.Context, resourceGroupName string, topicName string) (result Topic, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.Get") @@ -240,7 +240,7 @@ func (client TopicsClient) GetPreparer(ctx context.Context, resourceGroupName st "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -272,21 +272,30 @@ func (client TopicsClient) GetResponder(resp *http.Response) (result Topic, err return } -// ListByResourceGroup list all the topics under a resource group +// ListByResourceGroup list all the topics under a resource group. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -func (client TopicsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result TopicsListResult, err error) { +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client TopicsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, filter string, top *int32) (result TopicsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListByResourceGroup") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.tlr.Response.Response != nil { + sc = result.tlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "ListByResourceGroup", nil, "Failure preparing request") return @@ -294,12 +303,12 @@ func (client TopicsClient) ListByResourceGroup(ctx context.Context, resourceGrou resp, err := client.ListByResourceGroupSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.tlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "ListByResourceGroup", resp, "Failure sending request") return } - result, err = client.ListByResourceGroupResponder(resp) + result.tlr, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "ListByResourceGroup", resp, "Failure responding to request") } @@ -308,16 +317,22 @@ func (client TopicsClient) ListByResourceGroup(ctx context.Context, resourceGrou } // ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client TopicsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { +func (client TopicsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -346,19 +361,66 @@ func (client TopicsClient) ListByResourceGroupResponder(resp *http.Response) (re return } -// ListBySubscription list all the topics under an Azure subscription -func (client TopicsClient) ListBySubscription(ctx context.Context) (result TopicsListResult, err error) { +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client TopicsClient) listByResourceGroupNextResults(ctx context.Context, lastResults TopicsListResult) (result TopicsListResult, err error) { + req, err := lastResults.topicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "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, "eventgrid.TopicsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client TopicsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, filter string, top *int32) (result TopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.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, filter, top) + return +} + +// ListBySubscription list all the topics under an Azure subscription. +// Parameters: +// filter - the query used to filter the search results using OData syntax. Filtering is permitted on the +// 'name' property only and with limited number of OData operations. These operations are: the 'contains' +// function as well as the following logical operations: not, and, or, eq (for equal), and ne (for not equal). +// No arithmetic operations are supported. The following is a valid filter example: $filter=contains(namE, +// 'PATTERN') and name ne 'PATTERN-1'. The following is not a valid filter example: $filter=location eq +// 'westus'. +// top - the number of results to return per page for the list operation. Valid range for top parameter is 1 to +// 100. If not specified, the default number of results to be returned is 20 items per page. +func (client TopicsClient) ListBySubscription(ctx context.Context, filter string, top *int32) (result TopicsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListBySubscription") defer func() { sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode + if result.tlr.Response.Response != nil { + sc = result.tlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } - req, err := client.ListBySubscriptionPreparer(ctx) + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, filter, top) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "ListBySubscription", nil, "Failure preparing request") return @@ -366,12 +428,12 @@ func (client TopicsClient) ListBySubscription(ctx context.Context) (result Topic resp, err := client.ListBySubscriptionSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} + result.tlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "ListBySubscription", resp, "Failure sending request") return } - result, err = client.ListBySubscriptionResponder(resp) + result.tlr, err = client.ListBySubscriptionResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "ListBySubscription", resp, "Failure responding to request") } @@ -380,15 +442,21 @@ func (client TopicsClient) ListBySubscription(ctx context.Context) (result Topic } // ListBySubscriptionPreparer prepares the ListBySubscription request. -func (client TopicsClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) { +func (client TopicsClient) ListBySubscriptionPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } preparer := autorest.CreatePreparer( autorest.AsGet(), @@ -417,12 +485,49 @@ func (client TopicsClient) ListBySubscriptionResponder(resp *http.Response) (res return } -// ListEventTypes list event types for a topic +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client TopicsClient) listBySubscriptionNextResults(ctx context.Context, lastResults TopicsListResult) (result TopicsListResult, err error) { + req, err := lastResults.topicsListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "eventgrid.TopicsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client TopicsClient) ListBySubscriptionComplete(ctx context.Context, filter string, top *int32) (result TopicsListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListBySubscription") + 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.ListBySubscription(ctx, filter, top) + return +} + +// ListEventTypes list event types for a topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// providerNamespace - namespace of the provider of the topic -// resourceTypeName - name of the topic type -// resourceName - name of the topic +// providerNamespace - namespace of the provider of the topic. +// resourceTypeName - name of the topic type. +// resourceName - name of the topic. func (client TopicsClient) ListEventTypes(ctx context.Context, resourceGroupName string, providerNamespace string, resourceTypeName string, resourceName string) (result EventTypesListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListEventTypes") @@ -465,7 +570,7 @@ func (client TopicsClient) ListEventTypesPreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -497,10 +602,10 @@ func (client TopicsClient) ListEventTypesResponder(resp *http.Response) (result return } -// ListSharedAccessKeys list the two keys used to publish to a topic +// ListSharedAccessKeys list the two keys used to publish to a topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicName - name of the topic +// topicName - name of the topic. func (client TopicsClient) ListSharedAccessKeys(ctx context.Context, resourceGroupName string, topicName string) (result TopicSharedAccessKeys, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.ListSharedAccessKeys") @@ -541,7 +646,7 @@ func (client TopicsClient) ListSharedAccessKeysPreparer(ctx context.Context, res "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -573,11 +678,11 @@ func (client TopicsClient) ListSharedAccessKeysResponder(resp *http.Response) (r return } -// RegenerateKey regenerate a shared access key for a topic +// RegenerateKey regenerate a shared access key for a topic. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicName - name of the topic -// regenerateKeyRequest - request body to regenerate key +// topicName - name of the topic. +// regenerateKeyRequest - request body to regenerate key. func (client TopicsClient) RegenerateKey(ctx context.Context, resourceGroupName string, topicName string, regenerateKeyRequest TopicRegenerateKeyRequest) (result TopicSharedAccessKeys, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.RegenerateKey") @@ -624,7 +729,7 @@ func (client TopicsClient) RegenerateKeyPreparer(ctx context.Context, resourceGr "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -661,8 +766,8 @@ func (client TopicsClient) RegenerateKeyResponder(resp *http.Response) (result T // Update asynchronously updates a topic with the specified parameters. // Parameters: // resourceGroupName - the name of the resource group within the user's subscription. -// topicName - name of the topic -// topicUpdateParameters - topic update information +// topicName - name of the topic. +// topicUpdateParameters - topic update information. func (client TopicsClient) Update(ctx context.Context, resourceGroupName string, topicName string, topicUpdateParameters TopicUpdateParameters) (result TopicsUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicsClient.Update") @@ -697,7 +802,7 @@ func (client TopicsClient) UpdatePreparer(ctx context.Context, resourceGroupName "topicName": autorest.Encode("path", topicName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/topictypes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/topictypes.go similarity index 96% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/topictypes.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/topictypes.go index 9a3ca4c7cc101..5241cee4ceece 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/topictypes.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/topictypes.go @@ -41,9 +41,9 @@ func NewTopicTypesClientWithBaseURI(baseURI string, subscriptionID string) Topic return TopicTypesClient{NewWithBaseURI(baseURI, subscriptionID)} } -// Get get information about a topic type +// Get get information about a topic type. // Parameters: -// topicTypeName - name of the topic type +// topicTypeName - name of the topic type. func (client TopicTypesClient) Get(ctx context.Context, topicTypeName string) (result TopicTypeInfo, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicTypesClient.Get") @@ -82,7 +82,7 @@ func (client TopicTypesClient) GetPreparer(ctx context.Context, topicTypeName st "topicTypeName": autorest.Encode("path", topicTypeName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -114,7 +114,7 @@ func (client TopicTypesClient) GetResponder(resp *http.Response) (result TopicTy return } -// List list all registered topic types +// List list all registered topic types. func (client TopicTypesClient) List(ctx context.Context) (result TopicTypesListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicTypesClient.List") @@ -149,7 +149,7 @@ func (client TopicTypesClient) List(ctx context.Context) (result TopicTypesListR // ListPreparer prepares the List request. func (client TopicTypesClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -181,9 +181,9 @@ func (client TopicTypesClient) ListResponder(resp *http.Response) (result TopicT return } -// ListEventTypes list event types for a topic type +// ListEventTypes list event types for a topic type. // Parameters: -// topicTypeName - name of the topic type +// topicTypeName - name of the topic type. func (client TopicTypesClient) ListEventTypes(ctx context.Context, topicTypeName string) (result EventTypesListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TopicTypesClient.ListEventTypes") @@ -222,7 +222,7 @@ func (client TopicTypesClient) ListEventTypesPreparer(ctx context.Context, topic "topicTypeName": autorest.Encode("path", topicTypeName), } - const APIVersion = "2018-09-15-preview" + const APIVersion = "2020-04-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/version.go similarity index 93% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/version.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/version.go index 8a5b18bcded6c..4f97ef4c465bc 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid/version.go @@ -21,7 +21,7 @@ import "github.com/Azure/azure-sdk-for-go/version" // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " eventgrid/2018-09-15-preview" + return "Azure-SDK-For-Go/" + version.Number + " eventgrid/2020-04-01-preview" } // Version returns the semantic version (see http://semver.org) of the client. diff --git a/vendor/modules.txt b/vendor/modules.txt index 013ce9b3f746f..e6673de87518d 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -57,7 +57,7 @@ github.com/Azure/azure-sdk-for-go/services/preview/appplatform/mgmt/2019-05-01-p github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-09-01-preview/authorization github.com/Azure/azure-sdk-for-go/services/preview/botservice/mgmt/2018-07-12/botservice github.com/Azure/azure-sdk-for-go/services/preview/customproviders/mgmt/2018-09-01-preview/customproviders -github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2018-09-15-preview/eventgrid +github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid github.com/Azure/azure-sdk-for-go/services/preview/hdinsight/mgmt/2018-06-01-preview/hdinsight github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices github.com/Azure/azure-sdk-for-go/services/preview/maintenance/mgmt/2018-06-01-preview/maintenance diff --git a/website/docs/r/eventgrid_domain.html.markdown b/website/docs/r/eventgrid_domain.html.markdown index 4b544c603547d..36df1c8a189d5 100644 --- a/website/docs/r/eventgrid_domain.html.markdown +++ b/website/docs/r/eventgrid_domain.html.markdown @@ -40,7 +40,7 @@ The following arguments are supported: * `location` - (Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. -* `input_schema` - (Optional) Specifies the schema in which incoming events will be published to this domain. Allowed values are `cloudeventv01schema`, `customeventschema`, or `eventgridschema`. Defaults to `eventgridschema`. Changing this forces a new resource to be created. +* `input_schema` - (Optional) Specifies the schema in which incoming events will be published to this domain. Allowed values are `CloudEventSchemaV1_0`, `CustomEventSchema`, or `EventGridSchema`. Defaults to `eventgridschema`. Changing this forces a new resource to be created. * `input_mapping_fields` - (Optional) A `input_mapping_fields` block as defined below. diff --git a/website/docs/r/eventgrid_event_subscription.html.markdown b/website/docs/r/eventgrid_event_subscription.html.markdown index 5a6b386c0b61c..935add8a35cb4 100644 --- a/website/docs/r/eventgrid_event_subscription.html.markdown +++ b/website/docs/r/eventgrid_event_subscription.html.markdown @@ -56,9 +56,7 @@ The following arguments are supported: * `scope` - (Required) Specifies the scope at which the EventGrid Event Subscription should be created. Changing this forces a new resource to be created. -* `event_delivery_schema` - (Optional) Specifies the event delivery schema for the event subscription. Possible values include: `EventGridSchema`, `CloudEventV01Schema`, `CustomInputSchema`. - -* `topic_name` - (Optional) Specifies the name of the topic to associate with the event subscription. +* `event_delivery_schema` - (Optional) Specifies the event delivery schema for the event subscription. Possible values include: `EventGridSchema`, `CloudEventSchemaV1_0`, `CustomInputSchema`. Defaults to `EventGridSchema`. Changing this forces a new resource to be created. * `storage_queue_endpoint` - (Optional) A `storage_queue_endpoint` block as defined below. @@ -100,6 +98,8 @@ A `hybrid_connection_endpoint` supports the following: * `hybrid_connection_id` - (Required) Specifies the id of the hybrid connection where the Event Subscription will receive events. +--- + A `webhook_endpoint` supports the following: * `url` - (Required) Specifies the url of the webhook where the Event Subscription will receive events. @@ -136,9 +136,9 @@ The following attributes are exported: * `id` - The ID of the EventGrid Event Subscription. -## Timeouts - +* `topic_name` - (Optional) Specifies the name of the topic to associate with the event subscription. +## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: From 4fc0bc95171f26ba8941e0fb49d39fd75aef98ae Mon Sep 17 00:00:00 2001 From: kt Date: Mon, 11 May 2020 12:59:03 -0700 Subject: [PATCH 029/104] update CHANGELOG.md to include #6837 --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8181fec658711..e19d11cd09750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## 2.10.0 (Unreleased) +DEPENDENCIES: + +* updating `eventgrid` to `2020-04-01-preview` [GH-6837] + FEATURES: * **New Data Source:** `azurerm_eventhub` [GH-6841] @@ -99,7 +103,7 @@ FEATURES: * **New Resource:** `azurerm_servicebus_namespace_network_rule_set` ([#6379](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6379)) * **New Resource:** `azurerm_spring_cloud_app` ([#6384](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6384)) -DEPENDENCIES: +DEPENDENCIES: * updating `apimanagement` to `2019-12-01` ([#6479](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6479)) * updating the fork of `github.com/Azure/go-autorest` ([#6509](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6509)) From 25c5e7f9913d2f04a99299f0d75f1a1f3b751e43 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Mon, 11 May 2020 14:35:15 -0700 Subject: [PATCH 030/104] Fix crash --- .../internal/services/apimanagement/api_management_resource.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/internal/services/apimanagement/api_management_resource.go b/azurerm/internal/services/apimanagement/api_management_resource.go index e01857116ccbf..1b0e624117ecb 100644 --- a/azurerm/internal/services/apimanagement/api_management_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_resource.go @@ -1226,7 +1226,7 @@ func flattenApiManagementSignUpSettings(input apimanagement.PortalSignupSettings } func expandApiManagementPolicies(input []interface{}) (*apimanagement.PolicyContract, error) { - if len(input) == 0 { + if len(input) == 0 || input[0] == nil{ return nil, nil } From c5aa6c61a6bb53251b17b64133ca04632d51a35c Mon Sep 17 00:00:00 2001 From: Mark Lewis <56076038+ml4@users.noreply.github.com> Date: Mon, 11 May 2020 22:49:43 +0100 Subject: [PATCH 031/104] Fix typo in terraform state mv command (#6856) --- website/docs/guides/migrating-to-azuread.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/guides/migrating-to-azuread.html.markdown b/website/docs/guides/migrating-to-azuread.html.markdown index c126ce9b42e16..5800c0002d0a5 100644 --- a/website/docs/guides/migrating-to-azuread.html.markdown +++ b/website/docs/guides/migrating-to-azuread.html.markdown @@ -110,7 +110,7 @@ azurerm_azuread_service_principal_password.example As the Terraform Configuration has been updated - we can move each of the resources in the state using the `terraform state mv` command, for example: ```shell -$ terraform state mv azurerm_azuread_application.exampleazuread_application.example +$ terraform state mv azurerm_azuread_application.example azuread_application.example Moved azurerm_azuread_application.example to azuread_application.example ``` From 318d41000cde5581b7b0a480e6c2e10fa314c947 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Mon, 11 May 2020 15:44:58 -0700 Subject: [PATCH 032/104] fmt --- .../internal/services/apimanagement/api_management_resource.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/internal/services/apimanagement/api_management_resource.go b/azurerm/internal/services/apimanagement/api_management_resource.go index 1b0e624117ecb..930ecd86ec92d 100644 --- a/azurerm/internal/services/apimanagement/api_management_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_resource.go @@ -1226,7 +1226,7 @@ func flattenApiManagementSignUpSettings(input apimanagement.PortalSignupSettings } func expandApiManagementPolicies(input []interface{}) (*apimanagement.PolicyContract, error) { - if len(input) == 0 || input[0] == nil{ + if len(input) == 0 || input[0] == nil { return nil, nil } From c1faa6672f6bd57538577e1b030b95e75ee1a583 Mon Sep 17 00:00:00 2001 From: Henry Buckle Date: Mon, 11 May 2020 23:49:29 +0100 Subject: [PATCH 033/104] `azurerm_application_insights` - `retention_in_days` defaults to 90 #6851 --- .../applicationinsights/application_insights_resource.go | 1 + website/docs/r/application_insights.html.markdown | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/azurerm/internal/services/applicationinsights/application_insights_resource.go b/azurerm/internal/services/applicationinsights/application_insights_resource.go index 7bc4a04b0de4a..d595590506bec 100644 --- a/azurerm/internal/services/applicationinsights/application_insights_resource.go +++ b/azurerm/internal/services/applicationinsights/application_insights_resource.go @@ -64,6 +64,7 @@ func resourceArmApplicationInsights() *schema.Resource { "retention_in_days": { Type: schema.TypeInt, Optional: true, + Default: 90, ValidateFunc: validation.IntInSlice([]int{ 30, 60, diff --git a/website/docs/r/application_insights.html.markdown b/website/docs/r/application_insights.html.markdown index 8bdbd71033476..87903dd273fdd 100644 --- a/website/docs/r/application_insights.html.markdown +++ b/website/docs/r/application_insights.html.markdown @@ -52,7 +52,7 @@ The following arguments are supported: * `daily_data_cap_notifications_disabled` - (Optional) Specifies if a notification email will be send when the daily data volume cap is met. -* `retention_in_days` - (Optional) Specifies the retention period in days. Possible values are `30`, `60`, `90`, `120`, `180`, `270`, `365`, `550` or `730`. +* `retention_in_days` - (Optional) Specifies the retention period in days. Possible values are `30`, `60`, `90`, `120`, `180`, `270`, `365`, `550` or `730`. Defaults to `90`. * `sampling_percentage` - (Optional) Specifies the percentage of the data produced by the monitored application that is sampled for Application Insights telemetry. From 54f49c5d8b3726615a4452ed7b5115d3dea6a1ad Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Mon, 11 May 2020 15:50:13 -0700 Subject: [PATCH 034/104] Update changelog for #6851 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e19d11cd09750..8d0cbaf0089bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ IMPROVEMENTS: BUG FIXES: +* `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] ## 2.9.0 (May 07, 2020) From 482bc67e06d80b243f96de2cc97c34c24c113013 Mon Sep 17 00:00:00 2001 From: Arcturus Date: Tue, 12 May 2020 07:18:40 +0800 Subject: [PATCH 035/104] `azurerm_windows_virtual_machine` - Allow update of OS disk encryption settings (#6846) Fixes #6737 This applies the changes in PR #6230 to windows virtual machine which only fixes the problem in linux virtual machine despite its title says linux|windows. --- .../compute/linux_virtual_machine_resource.go | 2 +- ...s_virtual_machine_resource_disk_os_test.go | 76 ++++++++++++++++--- .../windows_virtual_machine_resource.go | 31 ++++++++ 3 files changed, 98 insertions(+), 11 deletions(-) diff --git a/azurerm/internal/services/compute/linux_virtual_machine_resource.go b/azurerm/internal/services/compute/linux_virtual_machine_resource.go index 5c155ca2c4f2a..deef305808a4a 100644 --- a/azurerm/internal/services/compute/linux_virtual_machine_resource.go +++ b/azurerm/internal/services/compute/linux_virtual_machine_resource.go @@ -887,7 +887,7 @@ func resourceLinuxVirtualMachineUpdate(d *schema.ResourceData, meta interface{}) } if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting to update encryption settings of of OS Disk %q for Linux Virtual Machine %q (Resource Group %q): %+v", diskName, id.Name, id.ResourceGroup, err) + return fmt.Errorf("Error waiting to update encryption settings of OS Disk %q for Linux Virtual Machine %q (Resource Group %q): %+v", diskName, id.Name, id.ResourceGroup, err) } log.Printf("[DEBUG] Updating encryption settings of OS Disk %q for Linux Virtual Machine %q (Resource Group %q) to %q.", diskName, id.Name, id.ResourceGroup, diskEncryptionSetId) diff --git a/azurerm/internal/services/compute/tests/windows_virtual_machine_resource_disk_os_test.go b/azurerm/internal/services/compute/tests/windows_virtual_machine_resource_disk_os_test.go index 4558419c2f96b..cee4758a1a927 100644 --- a/azurerm/internal/services/compute/tests/windows_virtual_machine_resource_disk_os_test.go +++ b/azurerm/internal/services/compute/tests/windows_virtual_machine_resource_disk_os_test.go @@ -149,24 +149,38 @@ func TestAccWindowsVirtualMachine_diskOSDiskEncryptionSet(t *testing.T) { CheckDestroy: checkWindowsVirtualMachineIsDestroyed, Steps: []resource.TestStep{ { - // TODO: After applying soft-delete and purge-protection in keyVault, this extra step can be removed. - Config: testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetDependencies(data), + Config: testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetEncrypted(data), Check: resource.ComposeTestCheckFunc( - enableSoftDeleteAndPurgeProtectionForKeyVault("azurerm_key_vault.test"), + checkWindowsVirtualMachineExists(data.ResourceName), ), }, + data.ImportStep("admin_password"), + }, + }) +} + +func TestAccWindowsVirtualMachine_diskOSDiskEncryptionSetUpdate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: checkWindowsVirtualMachineIsDestroyed, + Steps: []resource.TestStep{ { - Config: testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetResource(data), + Config: testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetUnencrypted(data), + Check: resource.ComposeTestCheckFunc( + checkWindowsVirtualMachineExists(data.ResourceName), + ), }, + data.ImportStep("admin_password"), { - Config: testWindowsVirtualMachine_diskOSDiskDiskEncryptionSet(data), + Config: testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetEncrypted(data), Check: resource.ComposeTestCheckFunc( checkWindowsVirtualMachineExists(data.ResourceName), ), }, - data.ImportStep( - "admin_password", - ), + data.ImportStep("admin_password"), }, }) } @@ -479,6 +493,10 @@ func testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetDependencies(data acce location := "westus2" return fmt.Sprintf(` +provider "azurerm" { + features {} +} + # note: whilst these aren't used in all tests, it saves us redefining these everywhere locals { vm_name = "acctestvm%s" @@ -497,6 +515,8 @@ resource "azurerm_key_vault" "test" { resource_group_name = azurerm_resource_group.test.name tenant_id = data.azurerm_client_config.current.tenant_id sku_name = "premium" + soft_delete_enabled = true + purge_protection_enabled = true enabled_for_disk_encryption = true } @@ -602,7 +622,43 @@ resource "azurerm_role_assignment" "disk-encryption-read-keyvault" { `, template, data.RandomInteger) } -func testWindowsVirtualMachine_diskOSDiskDiskEncryptionSet(data acceptance.TestData) string { +func testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetUnencrypted(data acceptance.TestData) string { + template := testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetResource(data) + return fmt.Sprintf(` +%s + +resource "azurerm_windows_virtual_machine" "test" { + name = local.vm_name + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + size = "Standard_F2" + admin_username = "adminuser" + admin_password = "P@$$w0rd1234!" + network_interface_ids = [ + azurerm_network_interface.test.id, + ] + + os_disk { + caching = "ReadWrite" + storage_account_type = "Standard_LRS" + } + + source_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2016-Datacenter" + version = "latest" + } + + depends_on = [ + "azurerm_role_assignment.disk-encryption-read-keyvault", + "azurerm_key_vault_access_policy.disk-encryption", + ] +} +`, template) +} + +func testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetEncrypted(data acceptance.TestData) string { template := testWindowsVirtualMachine_diskOSDiskDiskEncryptionSetResource(data) return fmt.Sprintf(` %s @@ -620,8 +676,8 @@ resource "azurerm_windows_virtual_machine" "test" { os_disk { caching = "ReadWrite" - disk_encryption_set_id = azurerm_disk_encryption_set.test.id storage_account_type = "Standard_LRS" + disk_encryption_set_id = azurerm_disk_encryption_set.test.id } source_image_reference { diff --git a/azurerm/internal/services/compute/windows_virtual_machine_resource.go b/azurerm/internal/services/compute/windows_virtual_machine_resource.go index 58012d741865b..53b1348144f99 100644 --- a/azurerm/internal/services/compute/windows_virtual_machine_resource.go +++ b/azurerm/internal/services/compute/windows_virtual_machine_resource.go @@ -891,6 +891,37 @@ func resourceWindowsVirtualMachineUpdate(d *schema.ResourceData, meta interface{ log.Printf("[DEBUG] Resized OS Disk %q for Windows Virtual Machine %q (Resource Group %q) to %dGB.", diskName, id.Name, id.ResourceGroup, newSize) } + if d.HasChange("os_disk.0.disk_encryption_set_id") { + if diskEncryptionSetId := d.Get("os_disk.0.disk_encryption_set_id").(string); diskEncryptionSetId != "" { + diskName := d.Get("os_disk.0.name").(string) + log.Printf("[DEBUG] Updating encryption settings of OS Disk %q for Windows Virtual Machine %q (Resource Group %q) to %q..", diskName, id.Name, id.ResourceGroup, diskEncryptionSetId) + + disksClient := meta.(*clients.Client).Compute.DisksClient + + update := compute.DiskUpdate{ + DiskUpdateProperties: &compute.DiskUpdateProperties{ + Encryption: &compute.Encryption{ + Type: compute.EncryptionAtRestWithCustomerKey, + DiskEncryptionSetID: utils.String(diskEncryptionSetId), + }, + }, + } + + future, err := disksClient.Update(ctx, id.ResourceGroup, diskName, update) + if err != nil { + return fmt.Errorf("Error updating encryption settings of OS Disk %q for Windows Virtual Machine %q (Resource Group %q): %+v", diskName, id.Name, id.ResourceGroup, err) + } + + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Error waiting to update encryption settings of OS Disk %q for Windows Virtual Machine %q (Resource Group %q): %+v", diskName, id.Name, id.ResourceGroup, err) + } + + log.Printf("[DEBUG] Updating encryption settings of OS Disk %q for Windows Virtual Machine %q (Resource Group %q) to %q.", diskName, id.Name, id.ResourceGroup, diskEncryptionSetId) + } else { + return fmt.Errorf("Once a customer-managed key is used, you can’t change the selection back to a platform-managed key") + } + } + if shouldUpdate { log.Printf("[DEBUG] Updating Windows Virtual Machine %q (Resource Group %q)..", id.Name, id.ResourceGroup) future, err := client.Update(ctx, id.ResourceGroup, id.Name, update) From d949028f768f3bf2970193a909d628e49ca318d9 Mon Sep 17 00:00:00 2001 From: kt Date: Mon, 11 May 2020 16:21:39 -0700 Subject: [PATCH 036/104] update CHANGELOG.md to include #6846 --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d0cbaf0089bc..97e4f08301c77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,8 @@ FEATURES: IMPROVEMENTS: * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] -* `azurerm_mssql_server` - Add support for `azuread_administrator` [GH-6822] +* `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] +* `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] BUG FIXES: From c950786c7712e24caef91842f26fc18ef0428e1b Mon Sep 17 00:00:00 2001 From: magodo Date: Tue, 12 May 2020 07:50:01 +0800 Subject: [PATCH 037/104] `SchemaResourceGroupNameForDataSource` Add `ValidateFunc` --- azurerm/helpers/azure/resource_group.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/azurerm/helpers/azure/resource_group.go b/azurerm/helpers/azure/resource_group.go index a1dc5dc522ca9..9a15422613a7a 100644 --- a/azurerm/helpers/azure/resource_group.go +++ b/azurerm/helpers/azure/resource_group.go @@ -30,8 +30,9 @@ func SchemaResourceGroupNameDiffSuppress() *schema.Schema { func SchemaResourceGroupNameForDataSource() *schema.Schema { return &schema.Schema{ - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validateResourceGroupName, } } From a06cce695aa4bc190128f5afacdb5fc984f71673 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Tue, 12 May 2020 13:30:57 +0800 Subject: [PATCH 038/104] Update doc for traffic manager endpoint --- website/docs/r/traffic_manager_endpoint.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/r/traffic_manager_endpoint.html.markdown b/website/docs/r/traffic_manager_endpoint.html.markdown index d568bddd816d7..96b1a199275b3 100644 --- a/website/docs/r/traffic_manager_endpoint.html.markdown +++ b/website/docs/r/traffic_manager_endpoint.html.markdown @@ -156,3 +156,5 @@ Traffic Manager Endpoints can be imported using the `resource id`, e.g. ```shell terraform import azurerm_traffic_manager_endpoint.exampleEndpoints /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/trafficManagerProfiles/mytrafficmanagerprofile1/azureEndpoints/mytrafficmanagerendpoint ``` + +-> **NOTE:** `azureEndpoints` in the above shell command should be replaced with `externalEndpoints` or `nestedEndpoints` while using other endpoint types. From 7819850232a0f667f5c3e4b6e1b7a358045775f8 Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Tue, 12 May 2020 09:22:38 +0200 Subject: [PATCH 039/104] updating to include #6864 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97e4f08301c77..bbb8d8e2f173f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ FEATURES: IMPROVEMENTS: +* All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] From e35f17bb684c418bf89bf2b7ce56299a00a80a6b Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Tue, 12 May 2020 10:36:31 +0200 Subject: [PATCH 040/104] updating to include #6862 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbb8d8e2f173f..6e93b1916985e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ IMPROVEMENTS: BUG FIXES: +* `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] From 49b206606f775e5dbf07f6d6f1e8d7e1ecee8534 Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Tue, 12 May 2020 10:36:44 +0200 Subject: [PATCH 041/104] ordering --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e93b1916985e..076cdf93ec250 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,9 +17,9 @@ IMPROVEMENTS: BUG FIXES: +* Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] -* Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] ## 2.9.0 (May 07, 2020) From 10cc0fd33897468ea34e20f10725fff197864b64 Mon Sep 17 00:00:00 2001 From: magodo Date: Tue, 12 May 2020 17:06:49 +0800 Subject: [PATCH 042/104] Update per review [Link](https://github.com/terraform-providers/terraform-provider-azurerm/pull/6821#pullrequestreview-409203935) --- azurerm/helpers/azure/resource_group.go | 2 +- .../internal/services/web/app_service_environment_resource.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/azurerm/helpers/azure/resource_group.go b/azurerm/helpers/azure/resource_group.go index aba7f5909a727..ac643bd5bf2aa 100644 --- a/azurerm/helpers/azure/resource_group.go +++ b/azurerm/helpers/azure/resource_group.go @@ -35,7 +35,7 @@ func SchemaResourceGroupNameForDataSource() *schema.Schema { } } -func SchemaResourceGroupNameOC() *schema.Schema { +func SchemaResourceGroupNameOptionalComputed() *schema.Schema { return &schema.Schema{ Type: schema.TypeString, ForceNew: true, diff --git a/azurerm/internal/services/web/app_service_environment_resource.go b/azurerm/internal/services/web/app_service_environment_resource.go index 20205c54eef67..21650652e52ad 100644 --- a/azurerm/internal/services/web/app_service_environment_resource.go +++ b/azurerm/internal/services/web/app_service_environment_resource.go @@ -86,8 +86,8 @@ func resourceArmAppServiceEnvironment() *schema.Resource { }, false), }, - // TODO: Make it "Required" in next major release - "resource_group_name": azure.SchemaResourceGroupNameOC(), + // TODO in 3.0 Make it "Required" + "resource_group_name": azure.SchemaResourceGroupNameOptionalComputed(), "tags": tags.ForceNewSchema(), From 0c2f2d9bf70272cb8c5654709a5d827e6bd0c10c Mon Sep 17 00:00:00 2001 From: Sam Debruyn Date: Tue, 12 May 2020 11:23:55 +0200 Subject: [PATCH 043/104] add type PipelineReference in trigger res When the type is omitted, the trigger cannot be activated. This fixes #6869 --- .../datafactory/data_factory_trigger_schedule_resource.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/internal/services/datafactory/data_factory_trigger_schedule_resource.go b/azurerm/internal/services/datafactory/data_factory_trigger_schedule_resource.go index 38a3d91aa6377..bc17654f10622 100644 --- a/azurerm/internal/services/datafactory/data_factory_trigger_schedule_resource.go +++ b/azurerm/internal/services/datafactory/data_factory_trigger_schedule_resource.go @@ -166,6 +166,7 @@ func resourceArmDataFactoryTriggerScheduleCreateUpdate(d *schema.ResourceData, m reference := &datafactory.PipelineReference{ ReferenceName: utils.String(d.Get("pipeline_name").(string)), + Type: utils.String("PipelineReference"), } scheduleProps := &datafactory.ScheduleTrigger{ From fccba0463d741b35d19dd1bda6dce5334d725f03 Mon Sep 17 00:00:00 2001 From: Dapeng Zhang Date: Tue, 12 May 2020 17:35:34 +0800 Subject: [PATCH 044/104] Fix #6830 --- ...inux_virtual_machine_scale_set_resource.go | 5 ++ ...l_machine_scale_set_other_resource_test.go | 47 +++++++++++++++++-- ...l_machine_scale_set_other_resource_test.go | 47 +++++++++++++++++-- ...dows_virtual_machine_scale_set_resource.go | 5 ++ 4 files changed, 96 insertions(+), 8 deletions(-) diff --git a/azurerm/internal/services/compute/linux_virtual_machine_scale_set_resource.go b/azurerm/internal/services/compute/linux_virtual_machine_scale_set_resource.go index 7b938fff16ed0..7d5abf9d8de1e 100644 --- a/azurerm/internal/services/compute/linux_virtual_machine_scale_set_resource.go +++ b/azurerm/internal/services/compute/linux_virtual_machine_scale_set_resource.go @@ -677,6 +677,11 @@ func resourceArmLinuxVirtualMachineScaleSetUpdate(d *schema.ResourceData, meta i updateProps.VirtualMachineProfile.DiagnosticsProfile = expandBootDiagnostics(bootDiagnosticsRaw) } + if d.HasChange("do_not_run_extensions_on_overprovisioned_machines") { + v := d.Get("do_not_run_extensions_on_overprovisioned_machines").(bool) + updateProps.DoNotRunExtensionsOnOverprovisionedVMs = utils.Bool(v) + } + if d.HasChange("scale_in_policy") { scaleInPolicy := d.Get("scale_in_policy").(string) updateProps.ScaleInPolicy = &compute.ScaleInPolicy{ diff --git a/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go b/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go index 9481d9b3b6c3a..390a5fd377987 100644 --- a/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go +++ b/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go @@ -140,7 +140,46 @@ func TestAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProv CheckDestroy: testCheckAzureRMLinuxVirtualMachineScaleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data), + Config: testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, true), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLinuxVirtualMachineScaleSetExists(data.ResourceName), + ), + }, + data.ImportStep( + "admin_password", + ), + }, + }) +} + +func TestAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachinesUpdate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_linux_virtual_machine_scale_set", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMLinuxVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, false), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLinuxVirtualMachineScaleSetExists(data.ResourceName), + ), + }, + data.ImportStep( + "admin_password", + ), + { + Config: testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, true), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLinuxVirtualMachineScaleSetExists(data.ResourceName), + ), + }, + data.ImportStep( + "admin_password", + ), + { + Config: testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, false), Check: resource.ComposeTestCheckFunc( testCheckAzureRMLinuxVirtualMachineScaleSetExists(data.ResourceName), ), @@ -761,7 +800,7 @@ resource "azurerm_linux_virtual_machine_scale_set" "test" { `, template, data.RandomInteger, customData) } -func testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data acceptance.TestData) string { +func testAccAzureRMLinuxVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data acceptance.TestData, enabled bool) string { template := testAccAzureRMLinuxVirtualMachineScaleSet_template(data) return fmt.Sprintf(` %s @@ -777,7 +816,7 @@ resource "azurerm_linux_virtual_machine_scale_set" "test" { overprovision = true disable_password_authentication = false - do_not_run_extensions_on_overprovisioned_machines = true + do_not_run_extensions_on_overprovisioned_machines = %v source_image_reference { publisher = "Canonical" @@ -802,7 +841,7 @@ resource "azurerm_linux_virtual_machine_scale_set" "test" { } } } -`, template, data.RandomInteger) +`, template, data.RandomInteger, enabled) } func testAccAzureRMLinuxVirtualMachineScaleSet_otherPrioritySpot(data acceptance.TestData, evictionPolicy string) string { diff --git a/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go b/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go index 725a0b6c08c90..02e09b0d80bd3 100644 --- a/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go +++ b/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go @@ -162,7 +162,46 @@ func TestAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverPr CheckDestroy: testCheckAzureRMWindowsVirtualMachineScaleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data), + Config: testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, true), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMWindowsVirtualMachineScaleSetExists(data.ResourceName), + ), + }, + data.ImportStep( + "admin_password", + ), + }, + }) +} + +func TestAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachinesUpdate(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_windows_virtual_machine_scale_set", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMWindowsVirtualMachineScaleSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, false), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMWindowsVirtualMachineScaleSetExists(data.ResourceName), + ), + }, + data.ImportStep( + "admin_password", + ), + { + Config: testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, true), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMWindowsVirtualMachineScaleSetExists(data.ResourceName), + ), + }, + data.ImportStep( + "admin_password", + ), + { + Config: testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data, false), Check: resource.ComposeTestCheckFunc( testCheckAzureRMWindowsVirtualMachineScaleSetExists(data.ResourceName), ), @@ -921,7 +960,7 @@ resource "azurerm_windows_virtual_machine_scale_set" "test" { `, template, customData) } -func testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data acceptance.TestData) string { +func testAccAzureRMWindowsVirtualMachineScaleSet_otherDoNotRunExtensionsOnOverProvisionedMachines(data acceptance.TestData, enabled bool) string { template := testAccAzureRMWindowsVirtualMachineScaleSet_template(data) return fmt.Sprintf(` %s @@ -936,7 +975,7 @@ resource "azurerm_windows_virtual_machine_scale_set" "test" { admin_password = "P@ssword1234!" overprovision = true - do_not_run_extensions_on_overprovisioned_machines = true + do_not_run_extensions_on_overprovisioned_machines = %v source_image_reference { publisher = "MicrosoftWindowsServer" @@ -961,7 +1000,7 @@ resource "azurerm_windows_virtual_machine_scale_set" "test" { } } } -`, template) +`, template, enabled) } func testAccAzureRMWindowsVirtualMachineScaleSet_otherEnableAutomaticUpdatesDisabled(data acceptance.TestData) string { diff --git a/azurerm/internal/services/compute/windows_virtual_machine_scale_set_resource.go b/azurerm/internal/services/compute/windows_virtual_machine_scale_set_resource.go index a35c91173a5e0..ee3b8fc9e3eb1 100644 --- a/azurerm/internal/services/compute/windows_virtual_machine_scale_set_resource.go +++ b/azurerm/internal/services/compute/windows_virtual_machine_scale_set_resource.go @@ -707,6 +707,11 @@ func resourceArmWindowsVirtualMachineScaleSetUpdate(d *schema.ResourceData, meta updateProps.VirtualMachineProfile.DiagnosticsProfile = expandBootDiagnostics(bootDiagnosticsRaw) } + if d.HasChange("do_not_run_extensions_on_overprovisioned_machines") { + v := d.Get("do_not_run_extensions_on_overprovisioned_machines").(bool) + updateProps.DoNotRunExtensionsOnOverprovisionedVMs = utils.Bool(v) + } + if d.HasChange("scale_in_policy") { scaleInPolicy := d.Get("scale_in_policy").(string) updateProps.ScaleInPolicy = &compute.ScaleInPolicy{ From 215526d56684a4ad29ce0c5c9f0cb5133ae2b905 Mon Sep 17 00:00:00 2001 From: Dapeng Zhang Date: Tue, 12 May 2020 17:43:43 +0800 Subject: [PATCH 045/104] Fix fmt flag --- .../linux_virtual_machine_scale_set_other_resource_test.go | 2 +- .../windows_virtual_machine_scale_set_other_resource_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go b/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go index 390a5fd377987..3772ea5aec93b 100644 --- a/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go +++ b/azurerm/internal/services/compute/tests/linux_virtual_machine_scale_set_other_resource_test.go @@ -816,7 +816,7 @@ resource "azurerm_linux_virtual_machine_scale_set" "test" { overprovision = true disable_password_authentication = false - do_not_run_extensions_on_overprovisioned_machines = %v + do_not_run_extensions_on_overprovisioned_machines = %t source_image_reference { publisher = "Canonical" diff --git a/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go b/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go index 02e09b0d80bd3..47442f7150cd0 100644 --- a/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go +++ b/azurerm/internal/services/compute/tests/windows_virtual_machine_scale_set_other_resource_test.go @@ -975,7 +975,7 @@ resource "azurerm_windows_virtual_machine_scale_set" "test" { admin_password = "P@ssword1234!" overprovision = true - do_not_run_extensions_on_overprovisioned_machines = %v + do_not_run_extensions_on_overprovisioned_machines = %t source_image_reference { publisher = "MicrosoftWindowsServer" From d9f4c76f4abd414dc4d1108a383ec540a26733e6 Mon Sep 17 00:00:00 2001 From: Michael Guirao Date: Tue, 12 May 2020 13:47:41 +0200 Subject: [PATCH 046/104] update --- .../internal/services/iothub/client/client.go | 2 +- .../services/iothub/iothub_dps_resource.go | 2 +- .../iothub_endpoint_eventhub_resource.go | 2 +- ...thub_endpoint_servicebus_queue_resource.go | 2 +- ...thub_endpoint_servicebus_topic_resource.go | 2 +- ...hub_endpoint_storage_container_resource.go | 2 +- .../iothub/iothub_fallback_route_resource.go | 2 +- .../services/iothub/iothub_resource.go | 2 +- .../services/iothub/iothub_route_resource.go | 2 +- .../iothub_shared_access_policy_resource.go | 2 +- .../devices/certificates.go | 12 +- .../devices/client.go | 2 +- .../mgmt/2019-03-22-preview/devices/iothub.go | 127 ++++++++++++++++++ .../devices/iothubresource.go | 46 +++---- .../devices/models.go | 49 ++++++- .../devices/operations.go | 2 +- .../devices/resourceprovidercommon.go | 2 +- .../devices/version.go | 2 +- vendor/modules.txt | 2 +- 19 files changed, 215 insertions(+), 49 deletions(-) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/certificates.go (98%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/client.go (98%) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothub.go rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/iothubresource.go (99%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/models.go (98%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/operations.go (99%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/resourceprovidercommon.go (99%) rename vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/{2018-12-01-preview => 2019-03-22-preview}/devices/version.go (93%) diff --git a/azurerm/internal/services/iothub/client/client.go b/azurerm/internal/services/iothub/client/client.go index 282521be3fb4e..ce5ae154b27d2 100644 --- a/azurerm/internal/services/iothub/client/client.go +++ b/azurerm/internal/services/iothub/client/client.go @@ -1,7 +1,7 @@ package client import ( - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/Azure/azure-sdk-for-go/services/provisioningservices/mgmt/2018-01-22/iothub" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/common" ) diff --git a/azurerm/internal/services/iothub/iothub_dps_resource.go b/azurerm/internal/services/iothub/iothub_dps_resource.go index e8b60604cd322..697db89cfdd29 100644 --- a/azurerm/internal/services/iothub/iothub_dps_resource.go +++ b/azurerm/internal/services/iothub/iothub_dps_resource.go @@ -8,7 +8,7 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/Azure/azure-sdk-for-go/services/provisioningservices/mgmt/2018-01-22/iothub" "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" diff --git a/azurerm/internal/services/iothub/iothub_endpoint_eventhub_resource.go b/azurerm/internal/services/iothub/iothub_endpoint_eventhub_resource.go index 4418204d86ac8..dc0ba88ac9e2d 100644 --- a/azurerm/internal/services/iothub/iothub_endpoint_eventhub_resource.go +++ b/azurerm/internal/services/iothub/iothub_endpoint_eventhub_resource.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" diff --git a/azurerm/internal/services/iothub/iothub_endpoint_servicebus_queue_resource.go b/azurerm/internal/services/iothub/iothub_endpoint_servicebus_queue_resource.go index 9f63cf3703928..d9aae7cebedd1 100644 --- a/azurerm/internal/services/iothub/iothub_endpoint_servicebus_queue_resource.go +++ b/azurerm/internal/services/iothub/iothub_endpoint_servicebus_queue_resource.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" diff --git a/azurerm/internal/services/iothub/iothub_endpoint_servicebus_topic_resource.go b/azurerm/internal/services/iothub/iothub_endpoint_servicebus_topic_resource.go index ecd2a8d750baf..b24d1f86d4de8 100644 --- a/azurerm/internal/services/iothub/iothub_endpoint_servicebus_topic_resource.go +++ b/azurerm/internal/services/iothub/iothub_endpoint_servicebus_topic_resource.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" diff --git a/azurerm/internal/services/iothub/iothub_endpoint_storage_container_resource.go b/azurerm/internal/services/iothub/iothub_endpoint_storage_container_resource.go index b25ab7f4c5585..197cc5c22b7e4 100644 --- a/azurerm/internal/services/iothub/iothub_endpoint_storage_container_resource.go +++ b/azurerm/internal/services/iothub/iothub_endpoint_storage_container_resource.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" diff --git a/azurerm/internal/services/iothub/iothub_fallback_route_resource.go b/azurerm/internal/services/iothub/iothub_fallback_route_resource.go index d40021cdece11..d2ec714e96b81 100644 --- a/azurerm/internal/services/iothub/iothub_fallback_route_resource.go +++ b/azurerm/internal/services/iothub/iothub_fallback_route_resource.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" diff --git a/azurerm/internal/services/iothub/iothub_resource.go b/azurerm/internal/services/iothub/iothub_resource.go index 585366b53ccb6..1fe9ed38f4c7c 100644 --- a/azurerm/internal/services/iothub/iothub_resource.go +++ b/azurerm/internal/services/iothub/iothub_resource.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" diff --git a/azurerm/internal/services/iothub/iothub_route_resource.go b/azurerm/internal/services/iothub/iothub_route_resource.go index 3d58a87d57a56..2262174361b3e 100644 --- a/azurerm/internal/services/iothub/iothub_route_resource.go +++ b/azurerm/internal/services/iothub/iothub_route_resource.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" diff --git a/azurerm/internal/services/iothub/iothub_shared_access_policy_resource.go b/azurerm/internal/services/iothub/iothub_shared_access_policy_resource.go index e3c69a0c613c5..fe394e6196c42 100644 --- a/azurerm/internal/services/iothub/iothub_shared_access_policy_resource.go +++ b/azurerm/internal/services/iothub/iothub_shared_access_policy_resource.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" + "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/certificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/certificates.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/certificates.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/certificates.go index b0bd8d409b5c2..5baffe3f78eb2 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/certificates.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/certificates.go @@ -97,7 +97,7 @@ func (client CertificatesClient) CreateOrUpdatePreparer(ctx context.Context, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -188,7 +188,7 @@ func (client CertificatesClient) DeletePreparer(ctx context.Context, resourceGro "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -274,7 +274,7 @@ func (client CertificatesClient) GenerateVerificationCodePreparer(ctx context.Co "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -359,7 +359,7 @@ func (client CertificatesClient) GetPreparer(ctx context.Context, resourceGroupN "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -435,7 +435,7 @@ func (client CertificatesClient) ListByIotHubPreparer(ctx context.Context, resou "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -522,7 +522,7 @@ func (client CertificatesClient) VerifyPreparer(ctx context.Context, resourceGro "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/client.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/client.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/client.go index 2b0ba4681f800..283637031c71f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/client.go @@ -1,4 +1,4 @@ -// Package devices implements the Azure ARM Devices service API version 2018-12-01-preview. +// Package devices implements the Azure ARM Devices service API version 2019-03-22-preview. // // Use this API to manage the IoT hubs in your Azure subscription. package devices diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothub.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothub.go new file mode 100644 index 0000000000000..54bf19953b4f9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothub.go @@ -0,0 +1,127 @@ +package devices + +// 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" +) + +// IotHubClient is the use this API to manage the IoT hubs in your Azure subscription. +type IotHubClient struct { + BaseClient +} + +// NewIotHubClient creates an instance of the IotHubClient client. +func NewIotHubClient(subscriptionID string) IotHubClient { + return NewIotHubClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewIotHubClientWithBaseURI creates an instance of the IotHubClient client using a custom endpoint. Use this when +// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewIotHubClientWithBaseURI(baseURI string, subscriptionID string) IotHubClient { + return IotHubClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ManualFailover perform manual fail over of given hub +// Parameters: +// iotHubName - iotHub to fail over +// failoverInput - region to failover to. Must be a azure DR pair +// resourceGroupName - resource group which Iot Hub belongs to +func (client IotHubClient) ManualFailover(ctx context.Context, iotHubName string, failoverInput FailoverInput, resourceGroupName string) (result IotHubManualFailoverFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/IotHubClient.ManualFailover") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: failoverInput, + Constraints: []validation.Constraint{{Target: "failoverInput.FailoverRegion", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("devices.IotHubClient", "ManualFailover", err.Error()) + } + + req, err := client.ManualFailoverPreparer(ctx, iotHubName, failoverInput, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubClient", "ManualFailover", nil, "Failure preparing request") + return + } + + result, err = client.ManualFailoverSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubClient", "ManualFailover", result.Response(), "Failure sending request") + return + } + + return +} + +// ManualFailoverPreparer prepares the ManualFailover request. +func (client IotHubClient) ManualFailoverPreparer(ctx context.Context, iotHubName string, failoverInput FailoverInput, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "iotHubName": autorest.Encode("path", iotHubName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2019-03-22-preview" + 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.Devices/IotHubs/{iotHubName}/failover", pathParameters), + autorest.WithJSON(failoverInput), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ManualFailoverSender sends the ManualFailover request. The method will close the +// http.Response Body if it receives an error. +func (client IotHubClient) ManualFailoverSender(req *http.Request) (future IotHubManualFailoverFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ManualFailoverResponder handles the response to the ManualFailover request. The method always +// closes the http.Response Body. +func (client IotHubClient) ManualFailoverResponder(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/iothub/mgmt/2018-12-01-preview/devices/iothubresource.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothubresource.go similarity index 99% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/iothubresource.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothubresource.go index 2751b363a5fb1..a258ee19d50d5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/iothubresource.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/iothubresource.go @@ -90,7 +90,7 @@ func (client IotHubResourceClient) CheckNameAvailabilityPreparer(ctx context.Con "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -172,7 +172,7 @@ func (client IotHubResourceClient) CreateEventHubConsumerGroupPreparer(ctx conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -277,7 +277,7 @@ func (client IotHubResourceClient) CreateOrUpdatePreparer(ctx context.Context, r "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -359,7 +359,7 @@ func (client IotHubResourceClient) DeletePreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -445,7 +445,7 @@ func (client IotHubResourceClient) DeleteEventHubConsumerGroupPreparer(ctx conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -530,7 +530,7 @@ func (client IotHubResourceClient) ExportDevicesPreparer(ctx context.Context, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -608,7 +608,7 @@ func (client IotHubResourceClient) GetPreparer(ctx context.Context, resourceGrou "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -682,7 +682,7 @@ func (client IotHubResourceClient) GetEndpointHealthPreparer(ctx context.Context "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -799,7 +799,7 @@ func (client IotHubResourceClient) GetEventHubConsumerGroupPreparer(ctx context. "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -878,7 +878,7 @@ func (client IotHubResourceClient) GetJobPreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -957,7 +957,7 @@ func (client IotHubResourceClient) GetKeysForKeyNamePreparer(ctx context.Context "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1034,7 +1034,7 @@ func (client IotHubResourceClient) GetQuotaMetricsPreparer(ctx context.Context, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1147,7 +1147,7 @@ func (client IotHubResourceClient) GetStatsPreparer(ctx context.Context, resourc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1224,7 +1224,7 @@ func (client IotHubResourceClient) GetValidSkusPreparer(ctx context.Context, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1347,7 +1347,7 @@ func (client IotHubResourceClient) ImportDevicesPreparer(ctx context.Context, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1424,7 +1424,7 @@ func (client IotHubResourceClient) ListByResourceGroupPreparer(ctx context.Conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1533,7 +1533,7 @@ func (client IotHubResourceClient) ListBySubscriptionPreparer(ctx context.Contex "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1650,7 +1650,7 @@ func (client IotHubResourceClient) ListEventHubConsumerGroupsPreparer(ctx contex "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1765,7 +1765,7 @@ func (client IotHubResourceClient) ListJobsPreparer(ctx context.Context, resourc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1880,7 +1880,7 @@ func (client IotHubResourceClient) ListKeysPreparer(ctx context.Context, resourc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1994,7 +1994,7 @@ func (client IotHubResourceClient) TestAllRoutesPreparer(ctx context.Context, in "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -2087,7 +2087,7 @@ func (client IotHubResourceClient) TestRoutePreparer(ctx context.Context, input "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -2160,7 +2160,7 @@ func (client IotHubResourceClient) UpdatePreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/models.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/models.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/models.go index d145f92a56af6..23e4345ab2b45 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/models.go @@ -29,7 +29,7 @@ import ( ) // The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices" +const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices" // AccessRights enumerates the values for access rights. type AccessRights string @@ -583,6 +583,17 @@ func NewEndpointHealthDataListResultPage(getNextPage func(context.Context, Endpo return EndpointHealthDataListResultPage{fn: getNextPage} } +// EnrichmentProperties the properties of an enrichment that your IoT hub applies to messages delivered to +// endpoints. +type EnrichmentProperties struct { + // Key - The key or name for the enrichment property. + Key *string `json:"key,omitempty"` + // Value - The value for the enrichment property. + Value *string `json:"value,omitempty"` + // EndpointNames - The list of endpoints for which the enrichment is applied to the message. + EndpointNames *[]string `json:"endpointNames,omitempty"` +} + // ErrorDetails error details. type ErrorDetails struct { // Code - READ-ONLY; The error code. @@ -789,6 +800,12 @@ type ExportDevicesRequest struct { ExcludeKeys *bool `json:"excludeKeys,omitempty"` } +// FailoverInput use to provide failover region when requesting manual Failover for a hub. +type FailoverInput struct { + // FailoverRegion - Region the hub will be failed over to + FailoverRegion *string `json:"failoverRegion,omitempty"` +} + // FallbackRouteProperties the properties of the fallback route. IoT Hub uses these properties when it // routes messages to the fallback endpoint. type FallbackRouteProperties struct { @@ -1030,6 +1047,29 @@ type IotHubLocationDescription struct { Role IotHubReplicaRoleType `json:"role,omitempty"` } +// IotHubManualFailoverFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type IotHubManualFailoverFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *IotHubManualFailoverFuture) Result(client IotHubClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubManualFailoverFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("devices.IotHubManualFailoverFuture") + return + } + ar.Response = future.Response() + return +} + // IotHubNameAvailabilityInfo the properties indicating whether a given IoT hub name is available. type IotHubNameAvailabilityInfo struct { autorest.Response `json:"-"` @@ -1069,7 +1109,7 @@ type IotHubProperties struct { DeviceStreams *IotHubPropertiesDeviceStreams `json:"deviceStreams,omitempty"` // Features - The capabilities and features enabled for the IoT hub. Possible values include: 'None', 'DeviceManagement' Features Capabilities `json:"features,omitempty"` - // Locations - Primary and secondary location for iot hub + // Locations - READ-ONLY; Primary and secondary location for iot hub Locations *[]IotHubLocationDescription `json:"locations,omitempty"` } @@ -1109,9 +1149,6 @@ func (ihp IotHubProperties) MarshalJSON() ([]byte, error) { if ihp.Features != "" { objectMap["features"] = ihp.Features } - if ihp.Locations != nil { - objectMap["locations"] = ihp.Locations - } return json.Marshal(objectMap) } @@ -2044,6 +2081,8 @@ type RoutingProperties struct { Routes *[]RouteProperties `json:"routes,omitempty"` // FallbackRoute - The properties of the route that is used as a fall-back route when none of the conditions specified in the 'routes' section are met. This is an optional parameter. When this property is not set, the messages which do not meet any of the conditions specified in the 'routes' section get routed to the built-in eventhub endpoint. FallbackRoute *FallbackRouteProperties `json:"fallbackRoute,omitempty"` + // Enrichments - The list of user-provided enrichments that the IoT hub applies to messages to be delivered to built-in and custom endpoints. See: https://aka.ms/iotmsgenrich + Enrichments *[]EnrichmentProperties `json:"enrichments,omitempty"` } // RoutingServiceBusQueueEndpointProperties the properties related to service bus queue endpoint types. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/operations.go similarity index 99% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/operations.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/operations.go index be9b87ae38970..94dfbf8113422 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/operations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/operations.go @@ -77,7 +77,7 @@ func (client OperationsClient) List(ctx context.Context) (result OperationListRe // ListPreparer prepares the List request. func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/resourceprovidercommon.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/resourceprovidercommon.go similarity index 99% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/resourceprovidercommon.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/resourceprovidercommon.go index 763192349649f..dbad7f570d877 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/resourceprovidercommon.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/resourceprovidercommon.go @@ -81,7 +81,7 @@ func (client ResourceProviderCommonClient) GetSubscriptionQuotaPreparer(ctx cont "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2018-12-01-preview" + const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go similarity index 93% rename from vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/version.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go index 39ec68069ce7c..43e7aa0be520f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go @@ -21,7 +21,7 @@ import "github.com/Azure/azure-sdk-for-go/version" // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " devices/2018-12-01-preview" + return "Azure-SDK-For-Go/" + Version() + " devices/2019-03-22-preview" } // Version returns the semantic version (see http://semver.org) of the client. diff --git a/vendor/modules.txt b/vendor/modules.txt index e6673de87518d..52e98d8f5ce75 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -59,7 +59,7 @@ github.com/Azure/azure-sdk-for-go/services/preview/botservice/mgmt/2018-07-12/bo github.com/Azure/azure-sdk-for-go/services/preview/customproviders/mgmt/2018-09-01-preview/customproviders github.com/Azure/azure-sdk-for-go/services/preview/eventgrid/mgmt/2020-04-01-preview/eventgrid github.com/Azure/azure-sdk-for-go/services/preview/hdinsight/mgmt/2018-06-01-preview/hdinsight -github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices +github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices github.com/Azure/azure-sdk-for-go/services/preview/maintenance/mgmt/2018-06-01-preview/maintenance github.com/Azure/azure-sdk-for-go/services/preview/mixedreality/mgmt/2019-02-28/mixedreality github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights From f130a21bb8fc8bf7c52a1cceac4999abc9aaaad1 Mon Sep 17 00:00:00 2001 From: Michael Guirao Date: Tue, 12 May 2020 15:00:36 +0200 Subject: [PATCH 047/104] align on versin 41.2 of SDK --- .../preview/iothub/mgmt/2019-03-22-preview/devices/version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go index 43e7aa0be520f..5d1ff15181c54 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/version.go @@ -21,7 +21,7 @@ import "github.com/Azure/azure-sdk-for-go/version" // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/" + Version() + " devices/2019-03-22-preview" + return "Azure-SDK-For-Go/" + version.Number + " devices/2019-03-22-preview" } // Version returns the semantic version (see http://semver.org) of the client. From 1dfca0f7b7cfbe31d1c158fc6d1655e2617bdc1f Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Tue, 12 May 2020 15:27:05 +0200 Subject: [PATCH 048/104] updating to include #6871 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 076cdf93ec250..0244977d8394d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ BUG FIXES: * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] +* `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] ## 2.9.0 (May 07, 2020) From 15ccefb43130b7b03535e496e23cac0b4515d257 Mon Sep 17 00:00:00 2001 From: Jack Morris Date: Tue, 12 May 2020 15:00:26 +0100 Subject: [PATCH 049/104] Fix case on AuthorizationRules to match Azure API The resource ID for authorization rule specifies the rule name parameter `authorizationRules` with the first letter capitalized: `AuthorizationRules`. When trying to import an authorization rule using the resource ID shown in the docs, you'll get the following error: ``` Error: Error making Read request on Azure EventHub Authorization Rule : eventhub.NamespacesClient#GetAuthorizationRule: Invalid input: autorest/validation: validation failed: parameter=authorizationRuleName constraint=MinLength value="" details: value length must be greater than or equal to 1 ``` --- .../docs/r/eventhub_namespace_authorization_rule.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/eventhub_namespace_authorization_rule.html.markdown b/website/docs/r/eventhub_namespace_authorization_rule.html.markdown index 850691cc355cc..67b7995992c4f 100644 --- a/website/docs/r/eventhub_namespace_authorization_rule.html.markdown +++ b/website/docs/r/eventhub_namespace_authorization_rule.html.markdown @@ -93,5 +93,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d EventHub Namespace Authorization Rules can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_eventhub_namespace_authorization_rule.rule1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.EventHub/namespaces/namespace1/authorizationRules/rule1 +terraform import azurerm_eventhub_namespace_authorization_rule.rule1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.EventHub/namespaces/namespace1/AuthorizationRules/rule1 ``` From 769d5ae5b3961e0922397ebe0eb1d15ad3a05220 Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Tue, 12 May 2020 16:19:03 +0200 Subject: [PATCH 050/104] updating to include #6875 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0244977d8394d..a96b93bf02e46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ DEPENDENCIES: * updating `eventgrid` to `2020-04-01-preview` [GH-6837] +* updating `iothub` to `2019-03-22-preview` [GH-6875] FEATURES: From c8c4e0e2d233f2ad3b1185d6846cef04bd92cf71 Mon Sep 17 00:00:00 2001 From: aristosvo <8375124+aristosvo@users.noreply.github.com> Date: Tue, 12 May 2020 20:20:49 +0200 Subject: [PATCH 051/104] Bug: azurerm_kubernetes_cluster errors out with InvalidLoadbalancerProfile on changes (#6534) Fixes #6525 --- .../services/containers/kubernetes_cluster_resource.go | 9 +++++++-- .../tests/kubernetes_cluster_scaling_resource_test.go | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/azurerm/internal/services/containers/kubernetes_cluster_resource.go b/azurerm/internal/services/containers/kubernetes_cluster_resource.go index bf1b4312903f7..8d297911c2912 100644 --- a/azurerm/internal/services/containers/kubernetes_cluster_resource.go +++ b/azurerm/internal/services/containers/kubernetes_cluster_resource.go @@ -575,7 +575,7 @@ func resourceArmKubernetesClusterCreate(d *schema.ResourceData, meta interface{} } networkProfileRaw := d.Get("network_profile").([]interface{}) - networkProfile, err := expandKubernetesClusterNetworkProfile(networkProfileRaw, true, true, true) + networkProfile, err := expandKubernetesClusterNetworkProfile(networkProfileRaw, false, false, false) if err != nil { return err } @@ -1266,7 +1266,7 @@ func expandKubernetesClusterNetworkProfile(input []interface{}, changeManagedIps return &networkProfile, nil } -func expandLoadBalancerProfile(d []interface{}, loadBalancerType string, allowToSetIpCount bool, allowToSetIpPrefixes bool, allowToSetOutboundIp bool) (*containerservice.ManagedClusterLoadBalancerProfile, error) { +func expandLoadBalancerProfile(d []interface{}, loadBalancerType string, ipCountChanges bool, ipPrefixesChanges bool, outboundIpChanges bool) (*containerservice.ManagedClusterLoadBalancerProfile, error) { if len(d) == 0 || d[0] == nil { return nil, nil } @@ -1281,6 +1281,11 @@ func expandLoadBalancerProfile(d []interface{}, loadBalancerType string, allowTo var outboundIpPrefixes *containerservice.ManagedClusterLoadBalancerProfileOutboundIPPrefixes var outboundIps *containerservice.ManagedClusterLoadBalancerProfileOutboundIPs + noChangesForLoadBalancerIps := !ipCountChanges && !ipPrefixesChanges && !outboundIpChanges + allowToSetIpCount := ipCountChanges || noChangesForLoadBalancerIps + allowToSetIpPrefixes := ipPrefixesChanges || noChangesForLoadBalancerIps + allowToSetOutboundIp := outboundIpChanges || noChangesForLoadBalancerIps + if ipCount := config["managed_outbound_ip_count"]; ipCount != nil && allowToSetIpCount { if c := int32(ipCount.(int)); c > 0 { managedOutboundIps = &containerservice.ManagedClusterLoadBalancerProfileManagedOutboundIPs{Count: &c} diff --git a/azurerm/internal/services/containers/tests/kubernetes_cluster_scaling_resource_test.go b/azurerm/internal/services/containers/tests/kubernetes_cluster_scaling_resource_test.go index 0969b174dc760..fac4362605260 100644 --- a/azurerm/internal/services/containers/tests/kubernetes_cluster_scaling_resource_test.go +++ b/azurerm/internal/services/containers/tests/kubernetes_cluster_scaling_resource_test.go @@ -212,6 +212,11 @@ resource "azurerm_kubernetes_cluster" "test" { identity { type = "SystemAssigned" } + + network_profile { + network_plugin = "kubenet" + load_balancer_sku = "standard" + } } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, numberOfAgents) } From 796f2d0f7abd629645bef6a29ed793a042f828ce Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 12 May 2020 11:22:07 -0700 Subject: [PATCH 052/104] update CHANGELOG.md to include #6534 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a96b93bf02e46..b8063c17b4ced 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ BUG FIXES: * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] +* `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] ## 2.9.0 (May 07, 2020) From a99bfcb0e8131a7df8421a76b25fa457ffdaf5a3 Mon Sep 17 00:00:00 2001 From: magodo Date: Wed, 13 May 2020 04:43:02 +0800 Subject: [PATCH 053/104] `azurerm_log_analytics_workspace` - Support `rentention_in_days` for Free Tier (#6844) --- .../log_analytics_workspace_resource.go | 2 +- .../log_analytics_workspace_resource_test.go | 40 +++++++++++++++++++ .../r/log_analytics_workspace.html.markdown | 2 +- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/azurerm/internal/services/loganalytics/log_analytics_workspace_resource.go b/azurerm/internal/services/loganalytics/log_analytics_workspace_resource.go index f790515a4c551..537a06b2110c9 100644 --- a/azurerm/internal/services/loganalytics/log_analytics_workspace_resource.go +++ b/azurerm/internal/services/loganalytics/log_analytics_workspace_resource.go @@ -69,7 +69,7 @@ func resourceArmLogAnalyticsWorkspace() *schema.Resource { Type: schema.TypeInt, Optional: true, Computed: true, - ValidateFunc: validation.IntBetween(30, 730), + ValidateFunc: validation.Any(validation.IntBetween(30, 730), validation.IntInSlice([]int{7})), }, "workspace_id": { diff --git a/azurerm/internal/services/loganalytics/tests/log_analytics_workspace_resource_test.go b/azurerm/internal/services/loganalytics/tests/log_analytics_workspace_resource_test.go index 88687d1752c64..7905cf017de84 100644 --- a/azurerm/internal/services/loganalytics/tests/log_analytics_workspace_resource_test.go +++ b/azurerm/internal/services/loganalytics/tests/log_analytics_workspace_resource_test.go @@ -115,6 +115,25 @@ func TestAccAzureRMLogAnalyticsWorkspace_complete(t *testing.T) { }) } +func TestAccAzureRMLogAnalyticsWorkspace_freeTier(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_log_analytics_workspace", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMLogAnalyticsWorkspaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMLogAnalyticsWorkspace_freeTier(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLogAnalyticsWorkspaceExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + func testCheckAzureRMLogAnalyticsWorkspaceDestroy(s *terraform.State) error { conn := acceptance.AzureProvider.Meta().(*clients.Client).LogAnalytics.WorkspacesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -229,3 +248,24 @@ resource "azurerm_log_analytics_workspace" "test" { } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } + +func testAccAzureRMLogAnalyticsWorkspace_freeTier(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_log_analytics_workspace" "test" { + name = "acctestLAW-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku = "Free" + retention_in_days = 7 +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} diff --git a/website/docs/r/log_analytics_workspace.html.markdown b/website/docs/r/log_analytics_workspace.html.markdown index fdff86b466d16..cd2016922e81e 100644 --- a/website/docs/r/log_analytics_workspace.html.markdown +++ b/website/docs/r/log_analytics_workspace.html.markdown @@ -41,7 +41,7 @@ The following arguments are supported: ~> **NOTE:** A new pricing model took effect on `2018-04-03`, which requires the SKU `PerGB2018`. If you're provisioned resources before this date you have the option of remaining with the previous Pricing SKU and using the other SKU's defined above. More information about [the Pricing SKU's is available at the following URI](http://aka.ms/PricingTierWarning). -* `retention_in_days` - (Optional) The workspace data retention in days. Possible values range between 30 and 730. +* `retention_in_days` - (Optional) The workspace data retention in days. Possible values are either 7 (Free Tier only) or range between 30 and 730. * `tags` - (Optional) A mapping of tags to assign to the resource. From 1b52f1d1dba166d0c2cfb7d7866f2d9919da98bb Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Tue, 12 May 2020 13:43:46 -0700 Subject: [PATCH 054/104] Update changelog for #6844 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b8063c17b4ced..c514d59023667 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ IMPROVEMENTS: * All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] +* `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] From cf5b326c969dc3d03e7274d6bcac7581b505fb18 Mon Sep 17 00:00:00 2001 From: Neil Ye Date: Wed, 13 May 2020 05:48:30 +0800 Subject: [PATCH 055/104] Update doc for network profile of aks (#6810) fixes #5298 It only supports below scenarios: network_plugin = azure, network_policy = azure/calico network_plugin = kubenet, network_policy = calico --- website/docs/r/kubernetes_cluster.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/kubernetes_cluster.html.markdown b/website/docs/r/kubernetes_cluster.html.markdown index a23096d427708..b19faf8cbf808 100644 --- a/website/docs/r/kubernetes_cluster.html.markdown +++ b/website/docs/r/kubernetes_cluster.html.markdown @@ -267,7 +267,7 @@ A `network_profile` block supports the following: * `network_policy` - (Optional) Sets up network policy to be used with Azure CNI. [Network policy allows us to control the traffic flow between pods](https://docs.microsoft.com/en-us/azure/aks/use-network-policies). Currently supported values are `calico` and `azure`. Changing this forces a new resource to be created. -~> **NOTE:** When `network_plugin` is set to `kubenet` the `network_policy` field can only be set to `calico`, otherwise it has to be set to `azure`. +~> **NOTE:** When `network_policy` is set to `azure`, the `network_plugin` field can only be set to `azure`. * `dns_service_ip` - (Optional) IP address within the Kubernetes service address range that will be used by cluster service discovery (kube-dns). This is required when `network_plugin` is set to `azure`. Changing this forces a new resource to be created. From 3828e745828f86991ea58cdbb82d5828cddc68b6 Mon Sep 17 00:00:00 2001 From: Yuping Wei <56525716+yupwei68@users.noreply.github.com> Date: Wed, 13 May 2020 06:29:55 +0800 Subject: [PATCH 056/104] azurerm_api_management_named_value - fix the non empty plan when `secret` is true (#6834) Fix #6688 --- .../api_management_named_value_resource.go | 5 ++++- .../api_management_named_value_resource_test.go | 16 ++-------------- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/azurerm/internal/services/apimanagement/api_management_named_value_resource.go b/azurerm/internal/services/apimanagement/api_management_named_value_resource.go index cbfd467c15f72..5c3b06c3c872e 100644 --- a/azurerm/internal/services/apimanagement/api_management_named_value_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_named_value_resource.go @@ -149,7 +149,10 @@ func resourceArmApiManagementNamedValueRead(d *schema.ResourceData, meta interfa if properties := resp.NamedValueContractProperties; properties != nil { d.Set("display_name", properties.DisplayName) d.Set("secret", properties.Secret) - d.Set("value", properties.Value) + // API will not return `value` when `secret` is `true`, in which case we shall not set the `value`. Refer to the issue : #6688 + if properties.Secret != nil && !*properties.Secret { + d.Set("value", properties.Value) + } d.Set("tags", properties.Tags) } diff --git a/azurerm/internal/services/apimanagement/tests/api_management_named_value_resource_test.go b/azurerm/internal/services/apimanagement/tests/api_management_named_value_resource_test.go index ba1fb9b37d5b2..494efaaa9f2f3 100644 --- a/azurerm/internal/services/apimanagement/tests/api_management_named_value_resource_test.go +++ b/azurerm/internal/services/apimanagement/tests/api_management_named_value_resource_test.go @@ -23,10 +23,6 @@ func TestAccAzureRMAPIManagementNamedValue_basic(t *testing.T) { Config: testAccAzureRMAPIManagementNamedValue_basic(data), Check: resource.ComposeTestCheckFunc( testCheckAzureRMAPIManagementNamedValueExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "display_name", fmt.Sprintf("TestProperty%d", data.RandomInteger)), - resource.TestCheckResourceAttr(data.ResourceName, "value", "Test Value"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.0", "tag1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.1", "tag2"), ), }, data.ImportStep(), @@ -46,24 +42,16 @@ func TestAccAzureRMAPIManagementNamedValue_update(t *testing.T) { Config: testAccAzureRMAPIManagementNamedValue_basic(data), Check: resource.ComposeTestCheckFunc( testCheckAzureRMAPIManagementNamedValueExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "display_name", fmt.Sprintf("TestProperty%d", data.RandomInteger)), - resource.TestCheckResourceAttr(data.ResourceName, "value", "Test Value"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.0", "tag1"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.1", "tag2"), ), }, + data.ImportStep(), { Config: testAccAzureRMAPIManagementNamedValue_update(data), Check: resource.ComposeTestCheckFunc( testCheckAzureRMAPIManagementNamedValueExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "display_name", fmt.Sprintf("TestProperty2%d", data.RandomInteger)), - resource.TestCheckResourceAttr(data.ResourceName, "value", "Test Value2"), - resource.TestCheckResourceAttr(data.ResourceName, "secret", "true"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.0", "tag3"), - resource.TestCheckResourceAttr(data.ResourceName, "tags.1", "tag4"), ), }, - data.ImportStep(), + data.ImportStep("value"), }, }) } From e69f9b670aa5cc86a407f0faedb1f1fc9857a881 Mon Sep 17 00:00:00 2001 From: kt Date: Tue, 12 May 2020 15:31:46 -0700 Subject: [PATCH 057/104] update CHANGELOG.md to include #6834 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c514d59023667..fe626086dfeaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ BUG FIXES: * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] +* `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true [GH-6834] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] From 4038ea79c57ce1c04c107c5e68f2636a9c003fe6 Mon Sep 17 00:00:00 2001 From: neil-yechenwei Date: Wed, 13 May 2020 11:21:23 +0800 Subject: [PATCH 058/104] Update import command in eventhub ns doc --- .../docs/r/eventhub_namespace_authorization_rule.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/eventhub_namespace_authorization_rule.html.markdown b/website/docs/r/eventhub_namespace_authorization_rule.html.markdown index 67b7995992c4f..ddc5ae515195a 100644 --- a/website/docs/r/eventhub_namespace_authorization_rule.html.markdown +++ b/website/docs/r/eventhub_namespace_authorization_rule.html.markdown @@ -93,5 +93,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d EventHub Namespace Authorization Rules can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_eventhub_namespace_authorization_rule.rule1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.EventHub/namespaces/namespace1/AuthorizationRules/rule1 +$ terraform import azurerm_eventhub_namespace_authorization_rule.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.EventHub/namespaces/namespace1/AuthorizationRules/rule1 ``` From 1da6f1d083ef94c138a150ba4bad94517b1b0457 Mon Sep 17 00:00:00 2001 From: njucz <740360112@qq.com> Date: Wed, 13 May 2020 11:41:38 +0800 Subject: [PATCH 059/104] update doc for `azurerm_role_assignment` --- website/docs/r/role_assignment.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/website/docs/r/role_assignment.html.markdown b/website/docs/r/role_assignment.html.markdown index 0e192005a7717..07b6cd3d5fc3b 100644 --- a/website/docs/r/role_assignment.html.markdown +++ b/website/docs/r/role_assignment.html.markdown @@ -3,13 +3,13 @@ subcategory: "Authorization" layout: "azurerm" page_title: "Azure Resource Manager: azurerm_role_assignment" description: |- - Assigns a given Principal (User or Application) to a given Role. + Assigns a given Principal (User or Group) to a given Role. --- # azurerm_role_assignment -Assigns a given Principal (User or Application) to a given Role. +Assigns a given Principal (User or Group) to a given Role. ## Example Usage (using a built-in Role) @@ -138,7 +138,7 @@ The following arguments are supported: * `role_definition_name` - (Optional) The name of a built-in Role. Changing this forces a new resource to be created. Conflicts with `role_definition_id`. -* `principal_id` - (Required) The ID of the Principal (User, Group, Service Principal, or Application) to assign the Role Definition to. Changing this forces a new resource to be created. +* `principal_id` - (Required) The ID of the Principal (User, Group, Service Principal) to assign the Role Definition to. Changing this forces a new resource to be created. ~> **NOTE:** The Principal ID is also known as the Object ID (ie not the "Application ID" for applications). From 3bdd3b4cbc30896ed2a15713923d21bc1e9e6ecd Mon Sep 17 00:00:00 2001 From: njucz <740360112@qq.com> Date: Wed, 13 May 2020 11:45:14 +0800 Subject: [PATCH 060/104] update --- website/docs/r/role_assignment.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/role_assignment.html.markdown b/website/docs/r/role_assignment.html.markdown index 07b6cd3d5fc3b..f32ad281f59cb 100644 --- a/website/docs/r/role_assignment.html.markdown +++ b/website/docs/r/role_assignment.html.markdown @@ -138,7 +138,7 @@ The following arguments are supported: * `role_definition_name` - (Optional) The name of a built-in Role. Changing this forces a new resource to be created. Conflicts with `role_definition_id`. -* `principal_id` - (Required) The ID of the Principal (User, Group, Service Principal) to assign the Role Definition to. Changing this forces a new resource to be created. +* `principal_id` - (Required) The ID of the Principal (User, Group or Service Principal) to assign the Role Definition to. Changing this forces a new resource to be created. ~> **NOTE:** The Principal ID is also known as the Object ID (ie not the "Application ID" for applications). From 3c26e10a582c98b8d3a7f1676a9da2f959b64cea Mon Sep 17 00:00:00 2001 From: Steve <11830746+jackofallops@users.noreply.github.com> Date: Wed, 13 May 2020 08:19:17 +0100 Subject: [PATCH 061/104] Update for #6821 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe626086dfeaf..db1170e67352f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ IMPROVEMENTS: * All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] +* `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] From 83dcf31c7d64b758eb3554f54f7d637f9188de71 Mon Sep 17 00:00:00 2001 From: tombuildsstuff Date: Wed, 13 May 2020 11:19:38 +0200 Subject: [PATCH 062/104] tool: adding a check for gradually deprecated functions Go's linter immediately flags usages of functions which are marked as Deprecated - which makes sense when there's 10 usages, but less so when there's hundreds of usages and you want to remove things gradually. This PR introduces a check for functions which will be deprecated in the future, since they're no longer required - namely the feature flag "RequireResourcesToBeImported" which is now enabled by default. Over time we'll work through the existing codebase and remove usages of this function - but we intentionally don't want to do this in a single sweep as to not break open PR's (since this defaulted to "enabled" there's not much harm in this code kicking around for a while) --- GNUmakefile | 1 + scripts/run-gradually-deprecated.sh | 44 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100755 scripts/run-gradually-deprecated.sh diff --git a/GNUmakefile b/GNUmakefile index df31fde5072a7..51d38c9ec22c9 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -82,6 +82,7 @@ test-docker: docker run --rm -v $$(pwd):/go/src/github.com/terraform-providers/terraform-provider-azurerm -w /go/src/github.com/terraform-providers/terraform-provider-azurerm golang:1.13 make test test: fmtcheck + @TEST=$(TEST) ./scripts/run-gradually-deprecated.sh @TEST=$(TEST) ./scripts/run-test.sh test-compile: diff --git a/scripts/run-gradually-deprecated.sh b/scripts/run-gradually-deprecated.sh new file mode 100755 index 0000000000000..15ff698c52ba3 --- /dev/null +++ b/scripts/run-gradually-deprecated.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +function checkForConditionalRun { + if [ "$TRAVIS" == "ci" ]; + then + echo "Checking if this should be conditionally run.." + result=$(git diff --name-only origin/master | grep azurerm/) + if [ "$result" = "" ]; + then + echo "No changes committed to ./azurerm - nothing to lint - exiting" + exit 0 + fi + fi +} + +function runDeprecatedFunctions { + echo "==> Checking for use of gradually deprecated functions..." + result=$(git diff --name-only origin/master | grep azurerm/) + if [ "$result" = "" ]; + then + # No changes committed to ./azurerm - so nothing to check + exit 0 + fi + + # require resources to be imported is now hard-coded on - but only checking for additions + result=$(git diff origin/master | grep + | grep -R "features\.ShouldResourcesBeImported") + if [ "$result" = "" ]; + then + echo "The Feature Flag for 'ShouldResourcesBeImported' will be deprecated in the future" + echo "and shouldn't be used in new resources - please remove new usages of the" + echo "'ShouldResourcesBeImported' function from these changes - since this is now enabled" + echo "by default." + echo "" + echo "In the future this function will be marked as Deprecated - however it's not for" + echo "the moment to not conflict with open Pull Requests." + fi +} + +function main { + checkForConditionalRun + runDeprecatedFunctions +} + +main From 04b5466bba353832a82b4ab69bbb86ecc2228e3c Mon Sep 17 00:00:00 2001 From: Dominik Deutsch Date: Wed, 13 May 2020 22:51:11 +0200 Subject: [PATCH 063/104] size property must not be defined if source_uri is used (#6897) --- website/docs/r/storage_blob.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/website/docs/r/storage_blob.html.markdown b/website/docs/r/storage_blob.html.markdown index d4d9d7586040b..07b7d9d5f4689 100644 --- a/website/docs/r/storage_blob.html.markdown +++ b/website/docs/r/storage_blob.html.markdown @@ -54,7 +54,9 @@ The following arguments are supported: * `type` - (Required) The type of the storage blob to be created. Possible values are `Append`, `Block` or `Page`. Changing this forces a new resource to be created. -* `size` - (Optional) Used only for `page` blobs to specify the size in bytes of the blob to be created. Must be a multiple of 512. Defaults to 0. +* `size` - (Optional) Used only for `page` blobs to specify the size in bytes of the blob to be created. Must be a multiple of 512. Defaults to 0. + +~> **Note:** `size` is required if `source_uri` is not set. * `access_tier` - (Optional) The access tier of the storage blob. Possible values are `Archive`, `Cool` and `Hot`. From 55e8dc199e6c8c42a764ff74f9c06c833a526138 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Wed, 13 May 2020 14:06:19 -0700 Subject: [PATCH 064/104] `data.azurerm_security_group` - fixing crash where id is nil #6910 --- .../services/network/network_security_group_data_source.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/azurerm/internal/services/network/network_security_group_data_source.go b/azurerm/internal/services/network/network_security_group_data_source.go index b2d9f09c9d313..f4ab5881e981e 100644 --- a/azurerm/internal/services/network/network_security_group_data_source.go +++ b/azurerm/internal/services/network/network_security_group_data_source.go @@ -148,9 +148,12 @@ func dataSourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interfac if utils.ResponseWasNotFound(resp.Response) { return fmt.Errorf("Error: Network Security Group %q (Resource Group %q) was not found", name, resourceGroup) } - return fmt.Errorf("Error making Read request on Network Security Group %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("making Read request on Network Security Group %q (Resource Group %q): %+v", name, resourceGroup, err) } + if resp.ID == nil || *resp.ID == "" { + return fmt.Errorf("reading request on Network Security Group %q (Resource Group %q): %+v", name, resourceGroup, err) + } d.SetId(*resp.ID) d.Set("name", resp.Name) From 1c5cd9ce039b6932084dc0370fb40e02e444d1d2 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Wed, 13 May 2020 14:07:34 -0700 Subject: [PATCH 065/104] Update changelog for #6910 --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db1170e67352f..68d540f24eca7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,11 +21,12 @@ IMPROVEMENTS: BUG FIXES: * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] +* Data Source: `azurerm_security_group` - fixing crash where id is nil [GH-6910] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true [GH-6834] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] -* `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] +* `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] ## 2.9.0 (May 07, 2020) From 8d09d93af9448931ee461bfe8ba3e8a4d2ae49f0 Mon Sep 17 00:00:00 2001 From: Sune Keller Date: Wed, 13 May 2020 23:23:05 +0200 Subject: [PATCH 066/104] azurerm_application_gateway - support WAF Policies (#6105) Fixes #4667. --- .../network/application_gateway_resource.go | 17 +++ .../application_gateway_resource_test.go | 121 ++++++++++++++++++ .../docs/r/application_gateway.html.markdown | 2 + 3 files changed, 140 insertions(+) diff --git a/azurerm/internal/services/network/application_gateway_resource.go b/azurerm/internal/services/network/application_gateway_resource.go index 3e488cf48c697..fc8b3a77fa76b 100644 --- a/azurerm/internal/services/network/application_gateway_resource.go +++ b/azurerm/internal/services/network/application_gateway_resource.go @@ -1267,6 +1267,12 @@ func resourceArmApplicationGateway() *schema.Resource { }, }, + "firewall_policy_id": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: azure.ValidateResourceID, + }, + "custom_error_configuration": { Type: schema.TypeList, Optional: true, @@ -1428,6 +1434,13 @@ func resourceArmApplicationGatewayCreateUpdate(d *schema.ResourceData, meta inte gateway.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration = expandApplicationGatewayWafConfig(d) } + if v, ok := d.GetOk("firewall_policy_id"); ok { + id := v.(string) + gateway.ApplicationGatewayPropertiesFormat.FirewallPolicy = &network.SubResource{ + ID: &id, + } + } + if stopApplicationGateway { future, err := client.Stop(ctx, resGroup, name) if err != nil { @@ -1606,6 +1619,10 @@ func resourceArmApplicationGatewayRead(d *schema.ResourceData, meta interface{}) if setErr := d.Set("waf_configuration", flattenApplicationGatewayWafConfig(props.WebApplicationFirewallConfiguration)); setErr != nil { return fmt.Errorf("Error setting `waf_configuration`: %+v", setErr) } + + if props.FirewallPolicy != nil { + d.Set("firewall_policy_id", props.FirewallPolicy.ID) + } } return tags.FlattenAndSet(d, applicationGateway.Tags) diff --git a/azurerm/internal/services/network/tests/application_gateway_resource_test.go b/azurerm/internal/services/network/tests/application_gateway_resource_test.go index e86a963b2ccb9..23e808d0ffb6a 100644 --- a/azurerm/internal/services/network/tests/application_gateway_resource_test.go +++ b/azurerm/internal/services/network/tests/application_gateway_resource_test.go @@ -215,6 +215,26 @@ func TestAccAzureRMApplicationGateway_authCertificate(t *testing.T) { }) } +func TestAccAzureRMApplicationGateway_customFirewallPolicy(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_application_gateway", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApplicationGatewayDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApplicationGateway_customFirewallPolicy(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApplicationGatewayExists(data.ResourceName), + resource.TestCheckResourceAttrSet(data.ResourceName, "firewall_policy_id"), + ), + }, + data.ImportStep(), + }, + }) +} + // TODO required soft delete on the keyvault func TestAccAzureRMApplicationGateway_trustedRootCertificate_keyvault(t *testing.T) { t.Skip() @@ -1979,6 +1999,107 @@ resource "azurerm_application_gateway" "test" { `, template, data.RandomInteger) } +func testAccAzureRMApplicationGateway_customFirewallPolicy(data acceptance.TestData) string { + template := testAccAzureRMApplicationGateway_template(data) + return fmt.Sprintf(` +%[1]s + +# since these variables are re-used - a locals block makes this more maintainable +locals { + backend_address_pool_name = "${azurerm_virtual_network.test.name}-beap" + frontend_port_name = "${azurerm_virtual_network.test.name}-feport" + frontend_ip_configuration_name = "${azurerm_virtual_network.test.name}-feip" + http_setting_name = "${azurerm_virtual_network.test.name}-be-htst" + listener_name = "${azurerm_virtual_network.test.name}-httplstn" + request_routing_rule_name = "${azurerm_virtual_network.test.name}-rqrt" +} + +resource "azurerm_public_ip" "teststd" { + name = "acctest-PubIpStd-%[2]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + allocation_method = "Static" + sku = "Standard" +} + +resource "azurerm_web_application_firewall_policy" "testfwp" { + name = "acctest-fwp-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + + policy_settings { + enabled = true + mode = "Prevention" + } + + managed_rules { + managed_rule_set { + type = "OWASP" + version = "3.1" + } + } +} + +resource "azurerm_application_gateway" "test" { + name = "acctestag-%[2]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + + sku { + name = "WAF_v2" + tier = "WAF_v2" + capacity = 2 + } + + firewall_policy_id = azurerm_web_application_firewall_policy.testfwp.id + + gateway_ip_configuration { + name = "my-gateway-ip-configuration" + subnet_id = azurerm_subnet.test.id + } + + frontend_port { + name = local.frontend_port_name + port = 80 + } + + frontend_ip_configuration { + name = local.frontend_ip_configuration_name + public_ip_address_id = azurerm_public_ip.teststd.id + } + + backend_address_pool { + name = local.backend_address_pool_name + } + + backend_http_settings { + name = local.http_setting_name + cookie_based_affinity = "Disabled" + port = 443 + protocol = "Https" + request_timeout = 1 + + pick_host_name_from_backend_address = true + } + + http_listener { + name = local.listener_name + frontend_ip_configuration_name = local.frontend_ip_configuration_name + frontend_port_name = local.frontend_port_name + protocol = "Http" + } + + request_routing_rule { + name = local.request_routing_rule_name + rule_type = "Basic" + http_listener_name = local.listener_name + backend_address_pool_name = local.backend_address_pool_name + backend_http_settings_name = local.http_setting_name + } +} +`, template, data.RandomInteger) +} + func testAccAzureRMApplicationGateway_authCertificateUpdated(data acceptance.TestData) string { template := testAccAzureRMApplicationGateway_template(data) return fmt.Sprintf(` diff --git a/website/docs/r/application_gateway.html.markdown b/website/docs/r/application_gateway.html.markdown index a5ea01240c60d..067d595096063 100644 --- a/website/docs/r/application_gateway.html.markdown +++ b/website/docs/r/application_gateway.html.markdown @@ -167,6 +167,8 @@ The following arguments are supported: * `custom_error_configuration` - (Optional) One or more `custom_error_configuration` blocks as defined below. +* `firewall_policy_id` - (Optional) The resource ID of a firewall policy. + * `redirect_configuration` - (Optional) A `redirect_configuration` block as defined below. * `autoscale_configuration` - (Optional) A `autoscale_configuration` block as defined below. From f3429d9df1c54c8ed966be48ae0e9a45fd893cbb Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 14:24:08 -0700 Subject: [PATCH 067/104] update CHANGELOG.md to include #6105 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68d540f24eca7..9196f04597ea3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ IMPROVEMENTS: * All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] +* `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] From 8ff0f58bc065575be9c0277ca22a9f123b45afde Mon Sep 17 00:00:00 2001 From: Sune Keller Date: Wed, 13 May 2020 23:31:01 +0200 Subject: [PATCH 068/104] Support the Developer Portal type of hostname_configuration in azurerm_api_management (#6724) Fixes #6714. --- .../api_management_data_source.go | 20 +++++++++++--- .../apimanagement/api_management_resource.go | 27 ++++++++++++++++--- .../tests/api_management_resource_test.go | 24 ++++++++++++----- website/docs/d/api_management.html.markdown | 12 +++++++++ website/docs/r/api_management.html.markdown | 4 ++- 5 files changed, 72 insertions(+), 15 deletions(-) diff --git a/azurerm/internal/services/apimanagement/api_management_data_source.go b/azurerm/internal/services/apimanagement/api_management_data_source.go index b9c8d6cc5d5c6..a0e2b3551213c 100644 --- a/azurerm/internal/services/apimanagement/api_management_data_source.go +++ b/azurerm/internal/services/apimanagement/api_management_data_source.go @@ -124,6 +124,13 @@ func dataSourceApiManagementService() *schema.Resource { Schema: apiManagementDataSourceHostnameSchema(), }, }, + "developer_portal": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: apiManagementDataSourceHostnameSchema(), + }, + }, "proxy": { Type: schema.TypeList, Computed: true, @@ -207,6 +214,7 @@ func flattenDataSourceApiManagementHostnameConfigurations(input *[]apimanagement managementResults := make([]interface{}, 0) proxyResults := make([]interface{}, 0) portalResults := make([]interface{}, 0) + developerPortalResults := make([]interface{}, 0) scmResults := make([]interface{}, 0) for _, config := range *input { @@ -238,6 +246,9 @@ func flattenDataSourceApiManagementHostnameConfigurations(input *[]apimanagement case strings.ToLower(string(apimanagement.HostnameTypePortal)): portalResults = append(portalResults, output) + case strings.ToLower(string(apimanagement.HostnameTypeDeveloperPortal)): + developerPortalResults = append(developerPortalResults, output) + case strings.ToLower(string(apimanagement.HostnameTypeScm)): scmResults = append(scmResults, output) } @@ -245,10 +256,11 @@ func flattenDataSourceApiManagementHostnameConfigurations(input *[]apimanagement return []interface{}{ map[string]interface{}{ - "management": managementResults, - "portal": portalResults, - "proxy": proxyResults, - "scm": scmResults, + "management": managementResults, + "portal": portalResults, + "developer_portal": developerPortalResults, + "proxy": proxyResults, + "scm": scmResults, }, } } diff --git a/azurerm/internal/services/apimanagement/api_management_resource.go b/azurerm/internal/services/apimanagement/api_management_resource.go index 930ecd86ec92d..6b485ea13328c 100644 --- a/azurerm/internal/services/apimanagement/api_management_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_resource.go @@ -278,6 +278,13 @@ func resourceArmApiManagementService() *schema.Resource { Schema: apiManagementResourceHostnameSchema("portal"), }, }, + "developer_portal": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: apiManagementResourceHostnameSchema("developer_portal"), + }, + }, "proxy": { Type: schema.TypeList, Optional: true, @@ -711,6 +718,13 @@ func expandAzureRmApiManagementHostnameConfigurations(d *schema.ResourceData) *[ results = append(results, output) } + developerPortalVs := hostnameV["developer_portal"].([]interface{}) + for _, developerPortalV := range developerPortalVs { + v := developerPortalV.(map[string]interface{}) + output := expandApiManagementCommonHostnameConfiguration(v, apimanagement.HostnameTypeDeveloperPortal) + results = append(results, output) + } + proxyVs := hostnameV["proxy"].([]interface{}) for _, proxyV := range proxyVs { v := proxyV.(map[string]interface{}) @@ -761,6 +775,7 @@ func flattenApiManagementHostnameConfigurations(input *[]apimanagement.HostnameC managementResults := make([]interface{}, 0) portalResults := make([]interface{}, 0) + developerPortalResults := make([]interface{}, 0) proxyResults := make([]interface{}, 0) scmResults := make([]interface{}, 0) @@ -813,6 +828,9 @@ func flattenApiManagementHostnameConfigurations(input *[]apimanagement.HostnameC case strings.ToLower(string(apimanagement.HostnameTypePortal)): portalResults = append(portalResults, output) + case strings.ToLower(string(apimanagement.HostnameTypeDeveloperPortal)): + developerPortalResults = append(developerPortalResults, output) + case strings.ToLower(string(apimanagement.HostnameTypeScm)): scmResults = append(scmResults, output) } @@ -820,10 +838,11 @@ func flattenApiManagementHostnameConfigurations(input *[]apimanagement.HostnameC return []interface{}{ map[string]interface{}{ - "management": managementResults, - "portal": portalResults, - "proxy": proxyResults, - "scm": scmResults, + "management": managementResults, + "portal": portalResults, + "developer_portal": developerPortalResults, + "proxy": proxyResults, + "scm": scmResults, }, } } diff --git a/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go b/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go index dca3bcafe0118..8418648f806df 100644 --- a/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go +++ b/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go @@ -84,6 +84,10 @@ func TestAccAzureRMApiManagement_complete(t *testing.T) { resource.TestCheckResourceAttr(data.ResourceName, "tags.Acceptance", "Test"), resource.TestCheckResourceAttrSet(data.ResourceName, "public_ip_addresses.#"), resource.TestCheckResourceAttr(data.ResourceName, "protocols.0.enable_http2", "true"), + resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.proxy.0.host_name", "api.terraform.io"), + resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.proxy.1.host_name", "api2.terraform.io"), + resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.portal.0.host_name", "portal.terraform.io"), + resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.developer_portal.0.host_name", "developer-portal.terraform.io"), ), }, { @@ -92,12 +96,14 @@ func TestAccAzureRMApiManagement_complete(t *testing.T) { ImportStateVerify: true, ImportStateVerifyIgnore: []string{ "certificate", // not returned from API, sensitive - "hostname_configuration.0.portal.0.certificate", // not returned from API, sensitive - "hostname_configuration.0.portal.0.certificate_password", // not returned from API, sensitive - "hostname_configuration.0.proxy.0.certificate", // not returned from API, sensitive - "hostname_configuration.0.proxy.0.certificate_password", // not returned from API, sensitive - "hostname_configuration.0.proxy.1.certificate", // not returned from API, sensitive - "hostname_configuration.0.proxy.1.certificate_password", // not returned from API, sensitive + "hostname_configuration.0.portal.0.certificate", // not returned from API, sensitive + "hostname_configuration.0.portal.0.certificate_password", // not returned from API, sensitive + "hostname_configuration.0.developer_portal.0.certificate", // not returned from API, sensitive + "hostname_configuration.0.developer_portal.0.certificate_password", // not returned from API, sensitive + "hostname_configuration.0.proxy.0.certificate", // not returned from API, sensitive + "hostname_configuration.0.proxy.0.certificate_password", // not returned from API, sensitive + "hostname_configuration.0.proxy.1.certificate", // not returned from API, sensitive + "hostname_configuration.0.proxy.1.certificate_password", // not returned from API, sensitive }, }, }, @@ -513,6 +519,12 @@ resource "azurerm_api_management" "test" { certificate = filebase64("testdata/api_management_portal_test.pfx") certificate_password = "terraform" } + + developer_portal { + host_name = "developer-portal.terraform.io" + certificate = filebase64("testdata/api_management_developer_portal_test.pfx") + certificate_password = "terraform" + } } sku_name = "Premium_1" diff --git a/website/docs/d/api_management.html.markdown b/website/docs/d/api_management.html.markdown index 4237eae295ea5..2c6876288410f 100644 --- a/website/docs/d/api_management.html.markdown +++ b/website/docs/d/api_management.html.markdown @@ -79,6 +79,8 @@ A `hostname_configuration` block exports the following: * `portal` - One or more `portal` blocks as documented below. +* `developer_portal` - One or more `developer_portal` blocks as documented below. + * `proxy` - One or more `proxy` blocks as documented below. * `scm` - One or more `scm` blocks as documented below. @@ -105,6 +107,16 @@ A `portal` block exports the following: --- +A `developer_portal` block exports the following: + +* `host_name` - The Hostname used for the Portal. + +* `key_vault_id` - The ID of the Key Vault Secret which contains the SSL Certificate. + +* `negotiate_client_certificate` - Is Client Certificate Negotiation enabled? + +--- + A `proxy` block exports the following: * `default_ssl_binding` - Is this the default SSL Binding? diff --git a/website/docs/r/api_management.html.markdown b/website/docs/r/api_management.html.markdown index 26aa3063d1459..2304a0b4781bf 100644 --- a/website/docs/r/api_management.html.markdown +++ b/website/docs/r/api_management.html.markdown @@ -110,6 +110,8 @@ A `hostname_configuration` block supports the following: * `portal` - (Optional) One or more `portal` blocks as documented below. +* `developer_portal` - (Optional) One or more `developer_portal` blocks as documented below. + * `proxy` - (Optional) One or more `proxy` blocks as documented below. * `scm` - (Optional) One or more `scm` blocks as documented below. @@ -122,7 +124,7 @@ A `identity` block supports the following: --- -A `management`, `portal` and `scm` block supports the following: +A `management`, `portal`, `developer_portal` and `scm` block supports the following: * `host_name` - (Required) The Hostname to use for the Management API. From a8d5265e1684745413cbd722ca9a70089ed53eca Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 14:32:13 -0700 Subject: [PATCH 069/104] update CHANGELOG.md to include #6724 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9196f04597ea3..d141636bb8d2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ IMPROVEMENTS: * All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] +* `azurerm_api_management` - support for configuring the Developer Portal [GH-6724] * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] From 4d8403891432880f92e77cca64bf584d33b2bbe1 Mon Sep 17 00:00:00 2001 From: Christian Pearce Date: Wed, 13 May 2020 17:35:50 -0400 Subject: [PATCH 070/104] azurerm_express_route_circuit - de-provision and re-provision circuit when changing bandwidth reduction (#3983) (#6601) Reduction in bandwidth forces new resource, utilizing CustomizeDiff Fixes #3983 --- .../network/express_route_circuit_resource.go | 8 +++ .../express_route_circuit_resource_test.go | 62 ++++++++++++++++ .../helper/customdiff/compose.go | 72 +++++++++++++++++++ .../helper/customdiff/computed.go | 16 +++++ .../helper/customdiff/condition.go | 60 ++++++++++++++++ .../helper/customdiff/doc.go | 11 +++ .../helper/customdiff/force_new.go | 40 +++++++++++ .../helper/customdiff/validate.go | 38 ++++++++++ vendor/modules.txt | 1 + 9 files changed, 308 insertions(+) create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/doc.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go create mode 100644 vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go diff --git a/azurerm/internal/services/network/express_route_circuit_resource.go b/azurerm/internal/services/network/express_route_circuit_resource.go index e118898c2590a..0263430428a43 100644 --- a/azurerm/internal/services/network/express_route_circuit_resource.go +++ b/azurerm/internal/services/network/express_route_circuit_resource.go @@ -6,6 +6,7 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network" + "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" @@ -31,6 +32,13 @@ func resourceArmExpressRouteCircuit() *schema.Resource { State: schema.ImportStatePassthrough, }, + CustomizeDiff: customdiff.Sequence( + // If bandwidth is reduced force a new resource + customdiff.ForceNewIfChange("bandwidth_in_mbps", func(old, new, meta interface{}) bool { + return new.(int) < old.(int) + }), + ), + Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(30 * time.Minute), Read: schema.DefaultTimeout(5 * time.Minute), diff --git a/azurerm/internal/services/network/tests/express_route_circuit_resource_test.go b/azurerm/internal/services/network/tests/express_route_circuit_resource_test.go index ee227c178bd4c..851f599ba1f2e 100644 --- a/azurerm/internal/services/network/tests/express_route_circuit_resource_test.go +++ b/azurerm/internal/services/network/tests/express_route_circuit_resource_test.go @@ -28,6 +28,7 @@ func TestAccAzureRMExpressRouteCircuit(t *testing.T) { "allowClassicOperationsUpdate": testAccAzureRMExpressRouteCircuit_allowClassicOperationsUpdate, "requiresImport": testAccAzureRMExpressRouteCircuit_requiresImport, "data_basic": testAccDataSourceAzureRMExpressRoute_basicMetered, + "bandwidthReduction": testAccAzureRMExpressRouteCircuit_bandwidthReduction, }, "PrivatePeering": { "azurePrivatePeering": testAccAzureRMExpressRouteCircuitPeering_azurePrivatePeering, @@ -273,6 +274,33 @@ func testAccAzureRMExpressRouteCircuit_allowClassicOperationsUpdate(t *testing.T }) } +func testAccAzureRMExpressRouteCircuit_bandwidthReduction(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_express_route_circuit", "test") + var erc network.ExpressRouteCircuit + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMExpressRouteCircuitDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMExpressRouteCircuit_bandwidthReductionConfig(data, "100"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMExpressRouteCircuitExists("azurerm_express_route_circuit.test", &erc), + resource.TestCheckResourceAttr(data.ResourceName, "bandwidth_in_mbps", "100"), + ), + }, + { + Config: testAccAzureRMExpressRouteCircuit_bandwidthReductionConfig(data, "50"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMExpressRouteCircuitExists("azurerm_express_route_circuit.test", &erc), + resource.TestCheckResourceAttr(data.ResourceName, "bandwidth_in_mbps", "50"), + ), + }, + }, + }) +} + func testCheckAzureRMExpressRouteCircuitExists(resourceName string, erc *network.ExpressRouteCircuit) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] @@ -528,3 +556,37 @@ resource "azurerm_express_route_circuit" "test" { } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, allowClassicOperations) } + +func testAccAzureRMExpressRouteCircuit_bandwidthReductionConfig(data acceptance.TestData, bandwidth string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_express_route_circuit" "test" { + name = "acctest-erc-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + service_provider_name = "Equinix" + peering_location = "Silicon Valley" + bandwidth_in_mbps = %s + + sku { + tier = "Standard" + family = "MeteredData" + } + + allow_classic_operations = false + + tags = { + Environment = "production" + Purpose = "AcceptanceTests" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, bandwidth) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go new file mode 100644 index 0000000000000..b09199953e8e1 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go @@ -0,0 +1,72 @@ +package customdiff + +import ( + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +// All returns a CustomizeDiffFunc that runs all of the given +// CustomizeDiffFuncs and returns all of the errors produced. +// +// If one function produces an error, functions after it are still run. +// If this is not desirable, use function Sequence instead. +// +// If multiple functions returns errors, the result is a multierror. +// +// For example: +// +// &schema.Resource{ +// // ... +// CustomizeDiff: customdiff.All( +// customdiff.ValidateChange("size", func (old, new, meta interface{}) error { +// // If we are increasing "size" then the new value must be +// // a multiple of the old value. +// if new.(int) <= old.(int) { +// return nil +// } +// if (new.(int) % old.(int)) != 0 { +// return fmt.Errorf("new size value must be an integer multiple of old value %d", old.(int)) +// } +// return nil +// }), +// customdiff.ForceNewIfChange("size", func (old, new, meta interface{}) bool { +// // "size" can only increase in-place, so we must create a new resource +// // if it is decreased. +// return new.(int) < old.(int) +// }), +// customdiff.ComputedIf("version_id", func (d *schema.ResourceDiff, meta interface{}) bool { +// // Any change to "content" causes a new "version_id" to be allocated. +// return d.HasChange("content") +// }), +// ), +// } +// +func All(funcs ...schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + var err error + for _, f := range funcs { + thisErr := f(d, meta) + if thisErr != nil { + err = multierror.Append(err, thisErr) + } + } + return err + } +} + +// Sequence returns a CustomizeDiffFunc that runs all of the given +// CustomizeDiffFuncs in sequence, stopping at the first one that returns +// an error and returning that error. +// +// If all functions succeed, the combined function also succeeds. +func Sequence(funcs ...schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + for _, f := range funcs { + err := f(d, meta) + if err != nil { + return err + } + } + return nil + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go new file mode 100644 index 0000000000000..54ea5c402069c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go @@ -0,0 +1,16 @@ +package customdiff + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +// ComputedIf returns a CustomizeDiffFunc that sets the given key's new value +// as computed if the given condition function returns true. +func ComputedIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + if f(d, meta) { + d.SetNewComputed(key) + } + return nil + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go new file mode 100644 index 0000000000000..1d8e2bfd6558f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go @@ -0,0 +1,60 @@ +package customdiff + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +// ResourceConditionFunc is a function type that makes a boolean decision based +// on an entire resource diff. +type ResourceConditionFunc func(d *schema.ResourceDiff, meta interface{}) bool + +// ValueChangeConditionFunc is a function type that makes a boolean decision +// by comparing two values. +type ValueChangeConditionFunc func(old, new, meta interface{}) bool + +// ValueConditionFunc is a function type that makes a boolean decision based +// on a given value. +type ValueConditionFunc func(value, meta interface{}) bool + +// If returns a CustomizeDiffFunc that calls the given condition +// function and then calls the given CustomizeDiffFunc only if the condition +// function returns true. +// +// This can be used to include conditional customizations when composing +// customizations using All and Sequence, but should generally be used only in +// simple scenarios. Prefer directly writing a CustomizeDiffFunc containing +// a conditional branch if the given CustomizeDiffFunc is already a +// locally-defined function, since this avoids obscuring the control flow. +func If(cond ResourceConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + if cond(d, meta) { + return f(d, meta) + } + return nil + } +} + +// IfValueChange returns a CustomizeDiffFunc that calls the given condition +// function with the old and new values of the given key and then calls the +// given CustomizeDiffFunc only if the condition function returns true. +func IfValueChange(key string, cond ValueChangeConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + old, new := d.GetChange(key) + if cond(old, new, meta) { + return f(d, meta) + } + return nil + } +} + +// IfValue returns a CustomizeDiffFunc that calls the given condition +// function with the new values of the given key and then calls the +// given CustomizeDiffFunc only if the condition function returns true. +func IfValue(key string, cond ValueConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + if cond(d.Get(key), meta) { + return f(d, meta) + } + return nil + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/doc.go new file mode 100644 index 0000000000000..c6ad1199cdc6f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/doc.go @@ -0,0 +1,11 @@ +// Package customdiff provides a set of reusable and composable functions +// to enable more "declarative" use of the CustomizeDiff mechanism available +// for resources in package helper/schema. +// +// The intent of these helpers is to make the intent of a set of diff +// customizations easier to see, rather than lost in a sea of Go function +// boilerplate. They should _not_ be used in situations where they _obscure_ +// intent, e.g. by over-using the composition functions where a single +// function containing normal Go control flow statements would be more +// straightforward. +package customdiff diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go new file mode 100644 index 0000000000000..26afa8cb697d2 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go @@ -0,0 +1,40 @@ +package customdiff + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +// ForceNewIf returns a CustomizeDiffFunc that flags the given key as +// requiring a new resource if the given condition function returns true. +// +// The return value of the condition function is ignored if the old and new +// values of the field compare equal, since no attribute diff is generated in +// that case. +func ForceNewIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + if f(d, meta) { + d.ForceNew(key) + } + return nil + } +} + +// ForceNewIfChange returns a CustomizeDiffFunc that flags the given key as +// requiring a new resource if the given condition function returns true. +// +// The return value of the condition function is ignored if the old and new +// values compare equal, since no attribute diff is generated in that case. +// +// This function is similar to ForceNewIf but provides the condition function +// only the old and new values of the given key, which leads to more compact +// and explicit code in the common case where the decision can be made with +// only the specific field value. +func ForceNewIfChange(key string, f ValueChangeConditionFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + old, new := d.GetChange(key) + if f(old, new, meta) { + d.ForceNew(key) + } + return nil + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go new file mode 100644 index 0000000000000..0bc2c69505b61 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go @@ -0,0 +1,38 @@ +package customdiff + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +// ValueChangeValidationFunc is a function type that validates the difference +// (or lack thereof) between two values, returning an error if the change +// is invalid. +type ValueChangeValidationFunc func(old, new, meta interface{}) error + +// ValueValidationFunc is a function type that validates a particular value, +// returning an error if the value is invalid. +type ValueValidationFunc func(value, meta interface{}) error + +// ValidateChange returns a CustomizeDiffFunc that applies the given validation +// function to the change for the given key, returning any error produced. +func ValidateChange(key string, f ValueChangeValidationFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + old, new := d.GetChange(key) + return f(old, new, meta) + } +} + +// ValidateValue returns a CustomizeDiffFunc that applies the given validation +// function to value of the given key, returning any error produced. +// +// This should generally not be used since it is functionally equivalent to +// a validation function applied directly to the schema attribute in question, +// but is provided for situations where composing multiple CustomizeDiffFuncs +// together makes intent clearer than spreading that validation across the +// schema. +func ValidateValue(key string, f ValueValidationFunc) schema.CustomizeDiffFunc { + return func(d *schema.ResourceDiff, meta interface{}) error { + val := d.Get(key) + return f(val, meta) + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 52e98d8f5ce75..1b8bf4237129f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -246,6 +246,7 @@ github.com/hashicorp/logutils github.com/hashicorp/terraform-config-inspect/tfconfig # github.com/hashicorp/terraform-plugin-sdk v1.6.0 github.com/hashicorp/terraform-plugin-sdk/helper/acctest +github.com/hashicorp/terraform-plugin-sdk/helper/customdiff github.com/hashicorp/terraform-plugin-sdk/helper/hashcode github.com/hashicorp/terraform-plugin-sdk/helper/logging github.com/hashicorp/terraform-plugin-sdk/helper/mutexkv From 2bb29c132a1189ea6be95a15835a511ba99e1933 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 14:36:37 -0700 Subject: [PATCH 071/104] update CHANGELOG.md to include #6601 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d141636bb8d2e..b0bd98c55863f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ IMPROVEMENTS: * `azurerm_api_management` - support for configuring the Developer Portal [GH-6724] * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] +* `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] From 001fefb72772daa124c820ccaba6578855242ab3 Mon Sep 17 00:00:00 2001 From: WS <20408400+WodansSon@users.noreply.github.com> Date: Wed, 13 May 2020 15:07:51 -0700 Subject: [PATCH 072/104] fixes #5864 and #6763 * Adding private endpoint example HCL * Update examples/private_endpoint/postgreSql/README.md Co-authored-by: Tom Harvey * Update examples/private_endpoint/cosmosDb/README.md Co-authored-by: Tom Harvey * Requested changes per PR review * Update location descriptions in README.md Co-authored-by: Tom Harvey --- examples/private-endpoint/cosmos-db/README.md | 9 ++ examples/private-endpoint/cosmos-db/main.tf | 66 ++++++++++++++ .../cosmos-db}/variables.tf | 0 .../private-endpoint/postgresql/README.md | 9 ++ examples/private-endpoint/postgresql/main.tf | 54 ++++++++++++ .../private-endpoint/postgresql/variables.tf | 7 ++ .../private-link-service/README.md | 9 ++ .../private-link-service/main.tf | 85 +++++++++++++++++++ .../private-link-service/variables.tf | 7 ++ examples/private_endpoint/README.md | 9 -- examples/private_endpoint/main.tf | 71 ---------------- website/docs/r/private_endpoint.html.markdown | 6 ++ 12 files changed, 252 insertions(+), 80 deletions(-) create mode 100644 examples/private-endpoint/cosmos-db/README.md create mode 100644 examples/private-endpoint/cosmos-db/main.tf rename examples/{private_endpoint => private-endpoint/cosmos-db}/variables.tf (100%) create mode 100644 examples/private-endpoint/postgresql/README.md create mode 100644 examples/private-endpoint/postgresql/main.tf create mode 100644 examples/private-endpoint/postgresql/variables.tf create mode 100644 examples/private-endpoint/private-link-service/README.md create mode 100644 examples/private-endpoint/private-link-service/main.tf create mode 100644 examples/private-endpoint/private-link-service/variables.tf delete mode 100644 examples/private_endpoint/README.md delete mode 100644 examples/private_endpoint/main.tf diff --git a/examples/private-endpoint/cosmos-db/README.md b/examples/private-endpoint/cosmos-db/README.md new file mode 100644 index 0000000000000..c0ea0821dded6 --- /dev/null +++ b/examples/private-endpoint/cosmos-db/README.md @@ -0,0 +1,9 @@ +## Example: Private Endpoint + +This example provisions a Private Endpoint in Azure connected to a CosmosDB Account configured with MongoDB. + +### Variables + +* `prefix` - (Required) The prefix used for all resources in this example. + +* `location` - (Required) The Azure Region in which all resources in this example should be created. diff --git a/examples/private-endpoint/cosmos-db/main.tf b/examples/private-endpoint/cosmos-db/main.tf new file mode 100644 index 0000000000000..5a04bec903ecd --- /dev/null +++ b/examples/private-endpoint/cosmos-db/main.tf @@ -0,0 +1,66 @@ +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "example" { + name = "${var.prefix}-resources" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "example" { + name = "${var.prefix}-vnet" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name +} + +resource "azurerm_subnet" "endpoint" { + name = "endpoint" + resource_group_name = azurerm_resource_group.example.name + virtual_network_name = azurerm_virtual_network.example.name + address_prefix = "10.0.2.0/24" + + enforce_private_link_endpoint_network_policies = true +} + +resource "azurerm_cosmosdb_account" "example" { + name = "${var.prefix}-cosmosdb-example" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + offer_type = "Standard" + kind = "MongoDB" + + enable_automatic_failover = false + is_virtual_network_filter_enabled = true + ip_range_filter = "104.42.195.92,40.76.54.131,52.176.6.30,52.169.50.45,52.187.184.26" + + capabilities { + name = "EnableMongo" + } + + consistency_policy { + consistency_level = "BoundedStaleness" + max_interval_in_seconds = 310 + max_staleness_prefix = 101000 + } + + geo_location { + prefix = "${var.prefix}-cosmos-db-customid" + location = azurerm_resource_group.example.location + failover_priority = 0 + } +} + +resource "azurerm_private_endpoint" "example" { + name = "${var.prefix}-pe" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + subnet_id = azurerm_subnet.endpoint.id + + private_service_connection { + name = "tfex-cosmosdb-connection" + is_manual_connection = false + private_connection_resource_id = azurerm_cosmosdb_account.example.id + subresource_names = ["MongoDB"] + } +} diff --git a/examples/private_endpoint/variables.tf b/examples/private-endpoint/cosmos-db/variables.tf similarity index 100% rename from examples/private_endpoint/variables.tf rename to examples/private-endpoint/cosmos-db/variables.tf diff --git a/examples/private-endpoint/postgresql/README.md b/examples/private-endpoint/postgresql/README.md new file mode 100644 index 0000000000000..d750c8d3f9348 --- /dev/null +++ b/examples/private-endpoint/postgresql/README.md @@ -0,0 +1,9 @@ +## Example: Private Endpoint + +This example provisions a Private Endpoint which connects to a PostgreSQL server within Azure. + +### Variables + +* `prefix` - (Required) The prefix used for all resources in this example. + +* `location` - (Required) The Azure Region in which all resources in this example should be created. diff --git a/examples/private-endpoint/postgresql/main.tf b/examples/private-endpoint/postgresql/main.tf new file mode 100644 index 0000000000000..34794f90bb959 --- /dev/null +++ b/examples/private-endpoint/postgresql/main.tf @@ -0,0 +1,54 @@ +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "example" { + name = "${var.prefix}-resources" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "example" { + name = "${var.prefix}-vnet" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name +} + +resource "azurerm_subnet" "endpoint" { + name = "endpoint" + resource_group_name = azurerm_resource_group.example.name + virtual_network_name = azurerm_virtual_network.example.name + address_prefix = "10.0.2.0/24" + + enforce_private_link_endpoint_network_policies = true +} + +resource "azurerm_postgresql_server" "example" { + name = "${var.prefix}-postgresql" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + + administrator_login = "psqladmin" + administrator_login_password = "H@Sh1CoR3!" + auto_grow_enabled = true + backup_retention_days = 7 + geo_redundant_backup_enabled = false + sku_name = "GP_Gen5_2" + ssl_enforcement_enabled = true + storage_mb = 51200 + version = "11" +} + +resource "azurerm_private_endpoint" "example" { + name = "${var.prefix}-pe" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + subnet_id = azurerm_subnet.endpoint.id + + private_service_connection { + name = "tfex-postgresql-connection" + is_manual_connection = false + private_connection_resource_id = azurerm_postgresql_server.example.id + subresource_names = ["postgresqlServer"] + } +} diff --git a/examples/private-endpoint/postgresql/variables.tf b/examples/private-endpoint/postgresql/variables.tf new file mode 100644 index 0000000000000..f8b75a591141d --- /dev/null +++ b/examples/private-endpoint/postgresql/variables.tf @@ -0,0 +1,7 @@ +variable "prefix" { + description = "The Prefix used for all resources in this example" +} + +variable "location" { + description = "The Azure Region in which all resources in this example should be created." +} diff --git a/examples/private-endpoint/private-link-service/README.md b/examples/private-endpoint/private-link-service/README.md new file mode 100644 index 0000000000000..a683eb34c93a1 --- /dev/null +++ b/examples/private-endpoint/private-link-service/README.md @@ -0,0 +1,9 @@ +## Example: Private Endpoint + +This example provisions a Private Endpoint which connects to a Private Link Service within Azure. + +### Variables + +* `prefix` - (Required) The prefix used for all resources in this example. + +* `location` - (Required) The Azure Region in which all resources in this example should be created. diff --git a/examples/private-endpoint/private-link-service/main.tf b/examples/private-endpoint/private-link-service/main.tf new file mode 100644 index 0000000000000..c99b504311e64 --- /dev/null +++ b/examples/private-endpoint/private-link-service/main.tf @@ -0,0 +1,85 @@ +provider "azurerm" { + features {} +} + +data "azurerm_subscription" "current" {} + +resource "azurerm_resource_group" "example" { + name = "${var.prefix}-resources" + location = "${var.location}" +} + +resource "azurerm_virtual_network" "example" { + name = "${var.prefix}-vnet" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name +} + +resource "azurerm_subnet" "service" { + name = "service" + resource_group_name = azurerm_resource_group.example.name + virtual_network_name = azurerm_virtual_network.example.name + address_prefix = "10.0.1.0/24" + + enforce_private_link_service_network_policies = true +} + +resource "azurerm_subnet" "endpoint" { + name = "endpoint" + resource_group_name = azurerm_resource_group.example.name + virtual_network_name = azurerm_virtual_network.example.name + address_prefix = "10.0.2.0/24" + + enforce_private_link_endpoint_network_policies = true +} + +resource "azurerm_public_ip" "example" { + name = "${var.prefix}-pip" + sku = "Standard" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + allocation_method = "Static" +} + +resource "azurerm_lb" "example" { + name = "${var.prefix}-lb" + sku = "Standard" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + + frontend_ip_configuration { + name = azurerm_public_ip.example.name + public_ip_address_id = azurerm_public_ip.example.id + } +} + +resource "azurerm_private_link_service" "example" { + name = "${var.prefix}-pls" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + + auto_approval_subscription_ids = [data.azurerm_subscription.current.subscription_id] + visibility_subscription_ids = [data.azurerm_subscription.current.subscription_id] + + nat_ip_configuration { + name = azurerm_public_ip.example.name + subnet_id = azurerm_subnet.service.id + primary = true + } + + load_balancer_frontend_ip_configuration_ids = [azurerm_lb.example.frontend_ip_configuration.0.id] +} + +resource "azurerm_private_endpoint" "example" { + name = "${var.prefix}-pe" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + subnet_id = azurerm_subnet.endpoint.id + + private_service_connection { + name = "tfex-pls-connection" + is_manual_connection = false + private_connection_resource_id = azurerm_private_link_service.example.id + } +} diff --git a/examples/private-endpoint/private-link-service/variables.tf b/examples/private-endpoint/private-link-service/variables.tf new file mode 100644 index 0000000000000..f8b75a591141d --- /dev/null +++ b/examples/private-endpoint/private-link-service/variables.tf @@ -0,0 +1,7 @@ +variable "prefix" { + description = "The Prefix used for all resources in this example" +} + +variable "location" { + description = "The Azure Region in which all resources in this example should be created." +} diff --git a/examples/private_endpoint/README.md b/examples/private_endpoint/README.md deleted file mode 100644 index 4b6378f1f59d1..0000000000000 --- a/examples/private_endpoint/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Example: Private Endpoint - -This example provisions a Private Endpoint within Azure. - -### Variables - -* `prefix` - (Required) The prefix used for all resources in this example. - -* `location` - (Required) The Azure Region in which the Logic App should be created. diff --git a/examples/private_endpoint/main.tf b/examples/private_endpoint/main.tf deleted file mode 100644 index 277c7b72b3047..0000000000000 --- a/examples/private_endpoint/main.tf +++ /dev/null @@ -1,71 +0,0 @@ -provider "azurerm" { - features {} -} - -resource "azurerm_resource_group" "example" { - name = "${var.prefix}-resources" - location = "${var.location}" -} - -resource "azurerm_virtual_network" "example" { - name = "${var.prefix}-vnet" - address_space = ["10.0.0.0/16"] - location = "${azurerm_resource_group.example.location}" - resource_group_name = "${azurerm_resource_group.example.name}" -} - -resource "azurerm_subnet" "example" { - name = "${var.prefix}-subnet" - resource_group_name = "${azurerm_resource_group.example.name}" - virtual_network_name = "${azurerm_virtual_network.example.name}" - address_prefix = "10.0.1.0/24" - private_link_service_network_policies = "Disabled" - private_endpoint_network_policies = "Disabled" -} - -resource "azurerm_public_ip" "example" { - name = "${var.prefix}-pip" - sku = "Standard" - location = "${azurerm_resource_group.example.location}" - resource_group_name = "${azurerm_resource_group.example.name}" - allocation_method = "Static" -} - -resource "azurerm_lb" "example" { - name = "${var.prefix}-lb" - sku = "Standard" - location = "${azurerm_resource_group.example.location}" - resource_group_name = "${azurerm_resource_group.example.name}" - frontend_ip_configuration { - name = "${azurerm_public_ip.example.name}" - public_ip_address_id = "${azurerm_public_ip.example.id}" - } -} - -resource "azurerm_private_link_service" "example" { - name = "${var.prefix}-pls" - location = "${azurerm_resource_group.example.location}" - resource_group_name = "${azurerm_resource_group.example.name}" - nat_ip_configuration { - name = "${azurerm_public_ip.example.name}" - subnet_id = "${azurerm_subnet.example.id}" - } - load_balancer_frontend_ip_configuration_ids = ["${azurerm_lb.test.frontend_ip_configuration.0.id}"] -} - -resource "azurerm_private_link_endpoint" "example" { - name = "${var.prefix}-pe" - location = "${azurerm_resource_group.example.location}" - resource_group_name = "${azurerm_resource_group.example.name}" - subnet_id = "${azurerm_subnet.example.id}" - tags = { - env = "test" - version = "2" - } - - private_link_service_connections { - name = "testplsconnection" - private_link_service_id = "${azurerm_private_link_service.example.id}" - request_message = "Please approve my connection" - } -} diff --git a/website/docs/r/private_endpoint.html.markdown b/website/docs/r/private_endpoint.html.markdown index 6fb34c9c75ac4..95bf3a9f61030 100644 --- a/website/docs/r/private_endpoint.html.markdown +++ b/website/docs/r/private_endpoint.html.markdown @@ -151,6 +151,12 @@ The following attributes are exported: * `id` - The ID of the Private Endpoint. +## Example HCL Configurations + +* How to connect a `Private Endpoint` to a [Cosmos MongoDB](https://github.com/terraform-providers/terraform-provider-azurerm/tree/master/examples/private-endpoint/cosmos-db) +* How to connect a `Private Endpoint` to a [PostgreSQL Server](https://github.com/terraform-providers/terraform-provider-azurerm/tree/master/examples/private-endpoint/postgresql) +* How to connect a `Private Endpoint` to a [Private Link Service](https://github.com/terraform-providers/terraform-provider-azurerm/tree/master/examples/private-endpoint/private-link-service) + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: From b5a336cbeda31dc299a9c4ed4d54ec14c035a776 Mon Sep 17 00:00:00 2001 From: Sune Keller Date: Thu, 14 May 2020 01:01:50 +0200 Subject: [PATCH 073/104] azurerm_api_management - Only set `hostname_configuration` properties if not empty (#6850) When the fields are set to empty strings instead of null, the error message in #6621 is given. When set to null when empty strings, the update goes through. Fixes #6621. --- .../apimanagement/api_management_resource.go | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/azurerm/internal/services/apimanagement/api_management_resource.go b/azurerm/internal/services/apimanagement/api_management_resource.go index 6b485ea13328c..a2070eeda6276 100644 --- a/azurerm/internal/services/apimanagement/api_management_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_resource.go @@ -747,17 +747,28 @@ func expandAzureRmApiManagementHostnameConfigurations(d *schema.ResourceData) *[ } func expandApiManagementCommonHostnameConfiguration(input map[string]interface{}, hostnameType apimanagement.HostnameType) apimanagement.HostnameConfiguration { - encodedCertificate := input["certificate"].(string) - certificatePassword := input["certificate_password"].(string) - hostName := input["host_name"].(string) - keyVaultId := input["key_vault_id"].(string) - output := apimanagement.HostnameConfiguration{ - EncodedCertificate: utils.String(encodedCertificate), - CertificatePassword: utils.String(certificatePassword), - HostName: utils.String(hostName), - KeyVaultID: utils.String(keyVaultId), - Type: hostnameType, + Type: hostnameType, + } + if v, ok := input["certificate"]; ok { + if v.(string) != "" { + output.EncodedCertificate = utils.String(v.(string)) + } + } + if v, ok := input["certificate_password"]; ok { + if v.(string) != "" { + output.CertificatePassword = utils.String(v.(string)) + } + } + if v, ok := input["host_name"]; ok { + if v.(string) != "" { + output.HostName = utils.String(v.(string)) + } + } + if v, ok := input["key_vault_id"]; ok { + if v.(string) != "" { + output.KeyVaultID = utils.String(v.(string)) + } } if v, ok := input["negotiate_client_certificate"]; ok { From 054246dd1d32e01604f6fbdb6ad053a7ea3e5725 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 16:02:59 -0700 Subject: [PATCH 074/104] update CHANGELOG.md to include #6850 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b0bd98c55863f..b96ec6d1641d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ BUG FIXES: * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] * Data Source: `azurerm_security_group` - fixing crash where id is nil [GH-6910] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] +* `azurerm_api_management` - only sending the `hostname_configuration` properties if they are not empty [GH-6850] * `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true [GH-6834] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] From 6f17144f6667051006a34d9809ad0563e495186f Mon Sep 17 00:00:00 2001 From: Sune Keller Date: Thu, 14 May 2020 01:11:03 +0200 Subject: [PATCH 075/104] api_managment - support user assigned managed identities (#6783) Fixes #6782. --- .../api_management_data_source.go | 28 ++ .../apimanagement/api_management_resource.go | 69 ++- .../tests/api_management_resource_test.go | 393 ++++++++++++++++++ website/docs/d/api_management.html.markdown | 16 + website/docs/r/api_management.html.markdown | 8 +- 5 files changed, 504 insertions(+), 10 deletions(-) diff --git a/azurerm/internal/services/apimanagement/api_management_data_source.go b/azurerm/internal/services/apimanagement/api_management_data_source.go index a0e2b3551213c..66ae015482c02 100644 --- a/azurerm/internal/services/apimanagement/api_management_data_source.go +++ b/azurerm/internal/services/apimanagement/api_management_data_source.go @@ -52,6 +52,34 @@ func dataSourceApiManagementService() *schema.Resource { Computed: true, }, + "identity": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Computed: true, + }, + "principal_id": { + Type: schema.TypeString, + Computed: true, + }, + "tenant_id": { + Type: schema.TypeString, + Computed: true, + }, + "identity_ids": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + "notification_sender_email": { Type: schema.TypeString, Computed: true, diff --git a/azurerm/internal/services/apimanagement/api_management_resource.go b/azurerm/internal/services/apimanagement/api_management_resource.go index a2070eeda6276..d75305d26b80f 100644 --- a/azurerm/internal/services/apimanagement/api_management_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_resource.go @@ -87,9 +87,13 @@ func resourceArmApiManagementService() *schema.Resource { Schema: map[string]*schema.Schema{ "type": { Type: schema.TypeString, - Required: true, + Optional: true, + Default: string(apimanagement.None), ValidateFunc: validation.StringInSlice([]string{ - "SystemAssigned", + string(apimanagement.None), + string(apimanagement.SystemAssigned), + string(apimanagement.UserAssigned), + string(apimanagement.SystemAssignedUserAssigned), }, false), }, "principal_id": { @@ -100,6 +104,15 @@ func resourceArmApiManagementService() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "identity_ids": { + Type: schema.TypeSet, + Optional: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, + }, + }, }, }, }, @@ -477,7 +490,11 @@ func resourceArmApiManagementServiceCreateUpdate(d *schema.ResourceData, meta in } if _, ok := d.GetOk("identity"); ok { - properties.Identity = expandAzureRmApiManagementIdentity(d) + identity, err := expandAzureRmApiManagementIdentity(d) + if err != nil { + return fmt.Errorf("Error expanding `identity`: %+v", err) + } + properties.Identity = identity } if _, ok := d.GetOk("additional_location"); ok { @@ -929,17 +946,43 @@ func flattenApiManagementAdditionalLocations(input *[]apimanagement.AdditionalLo return results } -func expandAzureRmApiManagementIdentity(d *schema.ResourceData) *apimanagement.ServiceIdentity { +func expandAzureRmApiManagementIdentity(d *schema.ResourceData) (*apimanagement.ServiceIdentity, error) { + var identityIdSet *schema.Set + managedServiceIdentity := apimanagement.ServiceIdentity{} + vs := d.Get("identity").([]interface{}) if len(vs) == 0 { - return nil + managedServiceIdentity.Type = apimanagement.None + } else { + v := vs[0].(map[string]interface{}) + identityType, exists := v["type"] + if !exists { + return nil, fmt.Errorf("`type` must be specified when `identity` is set") + } + managedServiceIdentity.Type = apimanagement.ApimIdentityType(identityType.(string)) + if identityIds, exists := v["identity_ids"]; exists { + identityIdSet = (identityIds.(*schema.Set)) + } } - v := vs[0].(map[string]interface{}) - identityType := v["type"].(string) - return &apimanagement.ServiceIdentity{ - Type: apimanagement.ApimIdentityType(identityType), + // If type contains `UserAssigned`, `identity_ids` must be specified and have at least 1 element + if managedServiceIdentity.Type == apimanagement.UserAssigned || managedServiceIdentity.Type == apimanagement.SystemAssignedUserAssigned { + if identityIdSet == nil || identityIdSet.Len() == 0 { + return nil, fmt.Errorf("`identity_ids` must have at least 1 element when `type` includes `UserAssigned`") + } + + userAssignedIdentities := make(map[string]*apimanagement.UserIdentityProperties) + for _, id := range identityIdSet.List() { + userAssignedIdentities[id.(string)] = &apimanagement.UserIdentityProperties{} + } + + managedServiceIdentity.UserAssignedIdentities = userAssignedIdentities + } else if identityIdSet != nil && identityIdSet.Len() > 0 { + // If type does _not_ contain `UserAssigned` (i.e. is set to `SystemAssigned` or defaulted to `None`), `identity_ids` is not allowed + return nil, fmt.Errorf("`identity_ids` can only be specified when `type` includes `UserAssigned`; but `type` is currently %q", managedServiceIdentity.Type) } + + return &managedServiceIdentity, nil } func flattenAzureRmApiManagementMachineIdentity(identity *apimanagement.ServiceIdentity) []interface{} { @@ -959,6 +1002,14 @@ func flattenAzureRmApiManagementMachineIdentity(identity *apimanagement.ServiceI result["tenant_id"] = identity.TenantID.String() } + identityIds := make([]interface{}, 0) + if identity.UserAssignedIdentities != nil { + for key := range identity.UserAssignedIdentities { + identityIds = append(identityIds, key) + } + result["identity_ids"] = schema.NewSet(schema.HashString, identityIds) + } + return []interface{}{result} } diff --git a/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go b/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go index 8418648f806df..959578090643b 100644 --- a/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go +++ b/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go @@ -84,6 +84,8 @@ func TestAccAzureRMApiManagement_complete(t *testing.T) { resource.TestCheckResourceAttr(data.ResourceName, "tags.Acceptance", "Test"), resource.TestCheckResourceAttrSet(data.ResourceName, "public_ip_addresses.#"), resource.TestCheckResourceAttr(data.ResourceName, "protocols.0.enable_http2", "true"), + resource.TestCheckResourceAttr(data.ResourceName, "identity.#", "1"), + resource.TestCheckResourceAttr(data.ResourceName, "identity.0.type", "None"), resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.proxy.0.host_name", "api.terraform.io"), resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.proxy.1.host_name", "api2.terraform.io"), resource.TestCheckResourceAttr(data.ResourceName, "hostname_configuration.0.portal.0.host_name", "portal.terraform.io"), @@ -246,6 +248,271 @@ func testCheckAzureRMApiManagementExists(resourceName string) resource.TestCheck } } +func TestAccAzureRMApiManagement_identityUserAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identityUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identityNoneUpdateUserAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identityNone(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identityUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identityUserAssignedUpdateNone(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identityUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identityNone(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssignedUpdateNone(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identityNone(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identityNoneUpdateSystemAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identityNone(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identitySystemAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssignedUserAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssignedUserAssignedUpdateNone(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identityNone(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identityNoneUpdateSystemAssignedUserAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identityNone(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssignedUserAssignedUpdateSystemAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identitySystemAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssignedUserAssignedUpdateUserAssigned(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identityUserAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + func testAccAzureRMApiManagement_basic(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { @@ -580,3 +847,129 @@ resource "azurerm_api_management" "test" { } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger) } + +func testAccAzureRMApiManagement_identityUserAssigned(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_user_assigned_identity" "test" { + name = "acctestUAI-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} + +resource "azurerm_api_management" "test" { + name = "acctestAM-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + publisher_name = "pub1" + publisher_email = "pub1@email.com" + + sku_name = "Developer_1" + + identity { + type = "UserAssigned" + identity_ids = [ + azurerm_user_assigned_identity.test.id, + ] + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) +} + +func testAccAzureRMApiManagement_identitySystemAssigned(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_api_management" "test" { + name = "acctestAM-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + publisher_name = "pub1" + publisher_email = "pub1@email.com" + + sku_name = "Developer_1" + + identity { + type = "SystemAssigned" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + +func testAccAzureRMApiManagement_identitySystemAssignedUserAssigned(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_user_assigned_identity" "test" { + name = "acctestUAI-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} + +resource "azurerm_api_management" "test" { + name = "acctestAM-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + publisher_name = "pub1" + publisher_email = "pub1@email.com" + + sku_name = "Developer_1" + + identity { + type = "SystemAssigned, UserAssigned" + identity_ids = [ + azurerm_user_assigned_identity.test.id, + ] + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) +} + +func testAccAzureRMApiManagement_identityNone(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_api_management" "test" { + name = "acctestAM-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + publisher_name = "pub1" + publisher_email = "pub1@email.com" + + sku_name = "Developer_1" + + identity { + type = "None" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} diff --git a/website/docs/d/api_management.html.markdown b/website/docs/d/api_management.html.markdown index 2c6876288410f..349a3ee988776 100644 --- a/website/docs/d/api_management.html.markdown +++ b/website/docs/d/api_management.html.markdown @@ -41,6 +41,8 @@ output "api_management_id" { * `gateway_regional_url` - The URL for the Gateway in the Default Region. +* `identity` - (Optional) An `identity` block as defined below. + * `hostname_configuration` - A `hostname_configuration` block as defined below. * `management_api_url` - The URL for the Management API. @@ -73,6 +75,20 @@ A `additional_location` block exports the following: --- +A `identity` block exports the following: + +~> **Note:** User Assigned Managed Identities are in Preview + +* `type` - Specifies the type of Managed Service Identity that is configured on this API Management Service. + +* `principal_id` - Specifies the Principal ID of the System Assigned Managed Service Identity that is configured on this API Management Service. + +* `tenant_id` - Specifies the Tenant ID of the System Assigned Managed Service Identity that is configured on this API Management Service. + +* `identity_ids` - A list of IDs for User Assigned Managed Identity resources to be assigned. + +--- + A `hostname_configuration` block exports the following: * `management` - One or more `management` blocks as documented below. diff --git a/website/docs/r/api_management.html.markdown b/website/docs/r/api_management.html.markdown index 2304a0b4781bf..2da6eb4a6695d 100644 --- a/website/docs/r/api_management.html.markdown +++ b/website/docs/r/api_management.html.markdown @@ -120,7 +120,13 @@ A `hostname_configuration` block supports the following: A `identity` block supports the following: -* `type` - (Required) Specifies the type of Managed Service Identity that should be configured on this API Management Service. At this time the only supported value is`SystemAssigned`. +~> **Note:** User Assigned Managed Identities are in Preview + +* `type` - (Required) Specifies the type of Managed Service Identity that should be configured on this API Management Service. Possible values are `SystemAssigned`, `UserAssigned` or `SystemAssigned, UserAssigned` (to enable both). + +* `identity_ids` - (Optional) A list of IDs for User Assigned Managed Identity resources to be assigned. + +~> **NOTE:** This is required when `type` is set to `UserAssigned` or `SystemAssigned, UserAssigned`. --- From ecdeb0d56ca46e2003b76942c735f2df8fbf0981 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 16:11:56 -0700 Subject: [PATCH 076/104] update CHANGELOG.md to include #6783 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b96ec6d1641d4..7313292fd9cdd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ IMPROVEMENTS: * All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] * `azurerm_api_management` - support for configuring the Developer Portal [GH-6724] +* `azurerm_api_managment` - support for user assigned managed identities [GH-6783] * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] From f91f3b04710f144cdd0610fe0652ed4dff436931 Mon Sep 17 00:00:00 2001 From: Neil Ye Date: Thu, 14 May 2020 07:53:04 +0800 Subject: [PATCH 077/104] Update doc for validation of aks (#6884) --- website/docs/r/kubernetes_cluster.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/website/docs/r/kubernetes_cluster.html.markdown b/website/docs/r/kubernetes_cluster.html.markdown index b19faf8cbf808..aab3c9dd76060 100644 --- a/website/docs/r/kubernetes_cluster.html.markdown +++ b/website/docs/r/kubernetes_cluster.html.markdown @@ -269,17 +269,17 @@ A `network_profile` block supports the following: ~> **NOTE:** When `network_policy` is set to `azure`, the `network_plugin` field can only be set to `azure`. -* `dns_service_ip` - (Optional) IP address within the Kubernetes service address range that will be used by cluster service discovery (kube-dns). This is required when `network_plugin` is set to `azure`. Changing this forces a new resource to be created. +* `dns_service_ip` - (Optional) IP address within the Kubernetes service address range that will be used by cluster service discovery (kube-dns). Changing this forces a new resource to be created. -* `docker_bridge_cidr` - (Optional) IP address (in CIDR notation) used as the Docker bridge IP address on nodes. This is required when `network_plugin` is set to `azure`. Changing this forces a new resource to be created. +* `docker_bridge_cidr` - (Optional) IP address (in CIDR notation) used as the Docker bridge IP address on nodes. Changing this forces a new resource to be created. * `outbound_type` - (Optional) The outbound (egress) routing method which should be used for this Kubernetes Cluster. Possible values are `loadBalancer` and `userDefinedRouting`. Defaults to `loadBalancer`. * `pod_cidr` - (Optional) The CIDR to use for pod IP addresses. This field can only be set when `network_plugin` is set to `kubenet`. Changing this forces a new resource to be created. -* `service_cidr` - (Optional) The Network Range used by the Kubernetes service. This is required when `network_plugin` is set to `azure`. Changing this forces a new resource to be created. +* `service_cidr` - (Optional) The Network Range used by the Kubernetes service. Changing this forces a new resource to be created. -~> **NOTE:** This range should not be used by any network element on or connected to this VNet. Service address CIDR must be smaller than /12. +~> **NOTE:** This range should not be used by any network element on or connected to this VNet. Service address CIDR must be smaller than /12. `docker_bridge_cidr`, `dns_service_ip` and `service_cidr` should all be empty or all should be set. Examples of how to use [AKS with Advanced Networking](https://docs.microsoft.com/en-us/azure/aks/networking-overview#advanced-networking) can be [found in the `./examples/kubernetes/` directory in the Github repository](https://github.com/terraform-providers/terraform-provider-azurerm/tree/master/examples/kubernetes). From a3132c0c5d1426d2c018fcc97fd99e36aa82c316 Mon Sep 17 00:00:00 2001 From: Matthew Frahry Date: Wed, 13 May 2020 16:54:18 -0700 Subject: [PATCH 078/104] `azurerm_monitor_diagnostic_setting` - Fix crash around `retention_policy` (#6911) Fixes #6908 --- .../services/monitor/monitor_diagnostic_setting_resource.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/internal/services/monitor/monitor_diagnostic_setting_resource.go b/azurerm/internal/services/monitor/monitor_diagnostic_setting_resource.go index bea152d2eed54..b392002e0154f 100644 --- a/azurerm/internal/services/monitor/monitor_diagnostic_setting_resource.go +++ b/azurerm/internal/services/monitor/monitor_diagnostic_setting_resource.go @@ -463,7 +463,7 @@ func expandMonitorDiagnosticsSettingsMetrics(input []interface{}) []insights.Met policiesRaw := v["retention_policy"].([]interface{}) var retentionPolicy *insights.RetentionPolicy - if policiesRaw != nil { + if len(policiesRaw) > 0 && policiesRaw[0] != nil { policyRaw := policiesRaw[0].(map[string]interface{}) retentionDays := policyRaw["days"].(int) retentionEnabled := policyRaw["enabled"].(bool) From b39893a718da18e050c183d81eec247dec487397 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 16:55:21 -0700 Subject: [PATCH 079/104] update CHANGELOG.md to include #6911 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7313292fd9cdd..c6b795f1d63d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ BUG FIXES: * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] * `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] +* `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` [GH-6911] ## 2.9.0 (May 07, 2020) From cc979d4eaf3cc4a0d72b19f6e4732e6c7447ed73 Mon Sep 17 00:00:00 2001 From: Jochen Rauschenbusch Date: Thu, 14 May 2020 02:17:24 +0200 Subject: [PATCH 080/104] New Resource: `azurerm_eventgrid_domain_topic` (#6859) Adds new resource azurerm_eventgrid_domain_topic Fixes #4097 --- .../services/eventgrid/client/client.go | 5 + .../eventgrid_domain_topic_resource.go | 153 ++++++++++++++++++ .../eventgrid/parse/eventgrid_domain_topic.go | 38 +++++ .../services/eventgrid/registration.go | 1 + .../eventgrid_domain_topic_resource_test.go | 149 +++++++++++++++++ website/azurerm.erb | 4 + .../r/eventgrid_domain_topic.html.markdown | 66 ++++++++ 7 files changed, 416 insertions(+) create mode 100644 azurerm/internal/services/eventgrid/eventgrid_domain_topic_resource.go create mode 100644 azurerm/internal/services/eventgrid/parse/eventgrid_domain_topic.go create mode 100644 azurerm/internal/services/eventgrid/tests/eventgrid_domain_topic_resource_test.go create mode 100644 website/docs/r/eventgrid_domain_topic.html.markdown diff --git a/azurerm/internal/services/eventgrid/client/client.go b/azurerm/internal/services/eventgrid/client/client.go index 2e74b0c0f3c00..4ed958b3b7e78 100644 --- a/azurerm/internal/services/eventgrid/client/client.go +++ b/azurerm/internal/services/eventgrid/client/client.go @@ -7,6 +7,7 @@ import ( type Client struct { DomainsClient *eventgrid.DomainsClient + DomainTopicsClient *eventgrid.DomainTopicsClient EventSubscriptionsClient *eventgrid.EventSubscriptionsClient TopicsClient *eventgrid.TopicsClient } @@ -15,6 +16,9 @@ func NewClient(o *common.ClientOptions) *Client { DomainsClient := eventgrid.NewDomainsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&DomainsClient.Client, o.ResourceManagerAuthorizer) + DomainTopicsClient := eventgrid.NewDomainTopicsClient(o.SubscriptionId) + o.ConfigureClient(&DomainTopicsClient.Client, o.ResourceManagerAuthorizer) + EventSubscriptionsClient := eventgrid.NewEventSubscriptionsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&EventSubscriptionsClient.Client, o.ResourceManagerAuthorizer) @@ -24,6 +28,7 @@ func NewClient(o *common.ClientOptions) *Client { return &Client{ DomainsClient: &DomainsClient, EventSubscriptionsClient: &EventSubscriptionsClient, + DomainTopicsClient: &DomainTopicsClient, TopicsClient: &TopicsClient, } } diff --git a/azurerm/internal/services/eventgrid/eventgrid_domain_topic_resource.go b/azurerm/internal/services/eventgrid/eventgrid_domain_topic_resource.go new file mode 100644 index 0000000000000..0e3fa23e47b29 --- /dev/null +++ b/azurerm/internal/services/eventgrid/eventgrid_domain_topic_resource.go @@ -0,0 +1,153 @@ +package eventgrid + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/go-azure-helpers/response" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid/parse" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmEventGridDomainTopic() *schema.Resource { + return &schema.Resource{ + Create: resourceArmEventGridDomainTopicCreate, + Read: resourceArmEventGridDomainTopicRead, + Delete: resourceArmEventGridDomainTopicDelete, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Read: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.EventGridDomainTopicID(id) + return err + }), + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "domain_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": azure.SchemaResourceGroupName(), + }, + } +} + +func resourceArmEventGridDomainTopicCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).EventGrid.DomainTopicsClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + name := d.Get("name").(string) + domainName := d.Get("domain_name").(string) + resourceGroup := d.Get("resource_group_name").(string) + + if features.ShouldResourcesBeImported() && d.IsNewResource() { + existing, err := client.Get(ctx, resourceGroup, domainName, name) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("Error checking for presence of existing EventGrid Domain Topic %q (Resource Group %q): %s", name, resourceGroup, err) + } + } + + if existing.ID != nil && *existing.ID != "" { + return tf.ImportAsExistsError("azurerm_eventgrid_domain_topic", *existing.ID) + } + } + + future, err := client.CreateOrUpdate(ctx, resourceGroup, domainName, name) + if err != nil { + return fmt.Errorf("Error creating/updating EventGrid Domain Topic %q (Resource Group %q): %s", name, resourceGroup, err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Error waiting for EventGrid Domain Topic %q (Resource Group %q) to become available: %s", name, resourceGroup, err) + } + + read, err := client.Get(ctx, resourceGroup, domainName, name) + if err != nil { + return fmt.Errorf("Error retrieving EventGrid Domain Topic %q (Resource Group %q): %s", name, resourceGroup, err) + } + if read.ID == nil { + return fmt.Errorf("Cannot read EventGrid Domain Topic %q (resource group %s) ID", name, resourceGroup) + } + + d.SetId(*read.ID) + + return resourceArmEventGridDomainTopicRead(d, meta) +} + +func resourceArmEventGridDomainTopicRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).EventGrid.DomainTopicsClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.EventGridDomainTopicID(d.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.Domain, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[WARN] EventGrid Domain Topic %q was not found (Resource Group %q)", id.Name, id.ResourceGroup) + d.SetId("") + return nil + } + + return fmt.Errorf("Error making Read request on EventGrid Domain Topic %q: %+v", id.Name, err) + } + + d.Set("name", resp.Name) + d.Set("domain_name", id.Domain) + d.Set("resource_group_name", id.ResourceGroup) + + return nil +} + +func resourceArmEventGridDomainTopicDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).EventGrid.DomainTopicsClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.EventGridDomainTopicID(d.Id()) + if err != nil { + return err + } + + future, err := client.Delete(ctx, id.ResourceGroup, id.Domain, id.Name) + if err != nil { + if response.WasNotFound(future.Response()) { + return nil + } + return fmt.Errorf("Error deleting EventGrid Domain Topic %q: %+v", id.Name, err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + if response.WasNotFound(future.Response()) { + return nil + } + return fmt.Errorf("Error deleting EventGrid Domain Topic %q: %+v", id.Name, err) + } + + return nil +} diff --git a/azurerm/internal/services/eventgrid/parse/eventgrid_domain_topic.go b/azurerm/internal/services/eventgrid/parse/eventgrid_domain_topic.go new file mode 100644 index 0000000000000..f11961171e95f --- /dev/null +++ b/azurerm/internal/services/eventgrid/parse/eventgrid_domain_topic.go @@ -0,0 +1,38 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type EventGridDomainTopicId struct { + ResourceGroup string + Name string + Domain string +} + +func EventGridDomainTopicID(input string) (*EventGridDomainTopicId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse EventGrid Domain Topic ID %q: %+v", input, err) + } + + domainTopic := EventGridDomainTopicId{ + ResourceGroup: id.ResourceGroup, + } + + if domainTopic.Name, err = id.PopSegment("topics"); err != nil { + return nil, err + } + + if domainTopic.Domain, err = id.PopSegment("domains"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &domainTopic, nil +} diff --git a/azurerm/internal/services/eventgrid/registration.go b/azurerm/internal/services/eventgrid/registration.go index f1b2feda1dc8b..7ea4410b7d24f 100644 --- a/azurerm/internal/services/eventgrid/registration.go +++ b/azurerm/internal/services/eventgrid/registration.go @@ -29,6 +29,7 @@ func (r Registration) SupportedDataSources() map[string]*schema.Resource { func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ "azurerm_eventgrid_domain": resourceArmEventGridDomain(), + "azurerm_eventgrid_domain_topic": resourceArmEventGridDomainTopic(), "azurerm_eventgrid_event_subscription": resourceArmEventGridEventSubscription(), "azurerm_eventgrid_topic": resourceArmEventGridTopic(), } diff --git a/azurerm/internal/services/eventgrid/tests/eventgrid_domain_topic_resource_test.go b/azurerm/internal/services/eventgrid/tests/eventgrid_domain_topic_resource_test.go new file mode 100644 index 0000000000000..62eef498b5a99 --- /dev/null +++ b/azurerm/internal/services/eventgrid/tests/eventgrid_domain_topic_resource_test.go @@ -0,0 +1,149 @@ +package tests + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMEventGridDomainTopic_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_eventgrid_domain_topic", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMEventGridDomainTopicDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMEventGridDomainTopic_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMEventGridDomainTopicExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMEventGridDomainTopic_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_eventgrid_domain_topic", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMEventGridTopicDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMEventGridDomainTopic_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMEventGridDomainTopicExists(data.ResourceName), + ), + }, + { + Config: testAccAzureRMEventGridDomainTopic_requiresImport(data), + ExpectError: acceptance.RequiresImportError("azurerm_eventgrid_domain_topic"), + }, + }, + }) +} + +func testCheckAzureRMEventGridDomainTopicDestroy(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).EventGrid.DomainTopicsClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_eventgrid_domain_topic" { + continue + } + + name := rs.Primary.Attributes["name"] + domainName := rs.Primary.Attributes["domain_name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := client.Get(ctx, resourceGroup, domainName, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return nil + } + + return err + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("EventGrid Domain Topic still exists:\n%#v", resp) + } + } + + return nil +} + +func testCheckAzureRMEventGridDomainTopicExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).EventGrid.DomainTopicsClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + name := rs.Primary.Attributes["name"] + domainName := rs.Primary.Attributes["domain_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for EventGrid Domain Topic: %s", name) + } + + resp, err := client.Get(ctx, resourceGroup, domainName, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: EventGrid Domain Topic %q (resource group: %s) does not exist", name, resourceGroup) + } + + return fmt.Errorf("Bad: Get on EventGrid.DomainTopicsClient: %s", err) + } + + return nil + } +} + +func testAccAzureRMEventGridDomainTopic_basic(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} +resource "azurerm_eventgrid_domain" "test" { + name = "acctestegdomain-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} +resource "azurerm_eventgrid_domain_topic" "test" { + name = "acctestegtopic-%d" + domain_name = azurerm_eventgrid_domain.test.name + resource_group_name = azurerm_resource_group.test.name +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) +} + +func testAccAzureRMEventGridDomainTopic_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMEventGridDomainTopic_basic(data) + return fmt.Sprintf(` +%s +resource "azurerm_eventgrid_domain_topic" "import" { + name = azurerm_eventgrid_domain_topic.test.name + domain_name = azurerm_eventgrid_domain_topic.test.domain_name + resource_group_name = azurerm_eventgrid_domain_topic.test.resource_group_name +} +`, template) +} diff --git a/website/azurerm.erb b/website/azurerm.erb index 685e435743743..0ce801bf38ad6 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -1793,6 +1793,10 @@
  • azurerm_eventgrid_domain
  • + +
  • + azurerm_eventgrid_domain_topic +
  • azurerm_eventgrid_event_subscription diff --git a/website/docs/r/eventgrid_domain_topic.html.markdown b/website/docs/r/eventgrid_domain_topic.html.markdown new file mode 100644 index 0000000000000..1a1f45ede7dc9 --- /dev/null +++ b/website/docs/r/eventgrid_domain_topic.html.markdown @@ -0,0 +1,66 @@ +--- +subcategory: "Messaging" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_eventgrid_domain_topic" +description: |- + Manages an EventGrid Domain Topic +--- + +# azurerm_eventgrid_domain_topic + +Manages an EventGrid Domain Topic + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "resourceGroup1" + location = "West US 2" +} +resource "azurerm_eventgrid_domain" "example" { + name = "my-eventgrid-domain" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + tags = { + environment = "Production" + } +} +resource "azurerm_eventgrid_domain_topic" "example" { + name = "my-eventgrid-domain-topic" + domain_name = azurerm_eventgrid_domain.example.name + resource_group_name = azurerm_resource_group.example.name +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the EventGrid Domain Topic resource. Changing this forces a new resource to be created. + +* `domain_name` - (Required) Specifies the name of the EventGrid Domain. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group in which the EventGrid Domain exists. Changing this forces a new resource to be created. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The ID of the EventGrid Domain Topic. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the EventGrid Domain Topic. +* `update` - (Defaults to 30 minutes) Used when updating the EventGrid Domain Topic. +* `read` - (Defaults to 5 minutes) Used when retrieving the EventGrid Domain Topic. +* `delete` - (Defaults to 30 minutes) Used when deleting the EventGrid Domain Topic. + +## Import + +EventGrid Domain Topics can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_eventgrid_domain_topic.topic1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.EventGrid/domains/domain1/topics/topic1 +``` \ No newline at end of file From 3b56e8b38512aaf8964b6b240e7110fc795164cc Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 17:18:05 -0700 Subject: [PATCH 081/104] update CHANGELOG.md to include #6859 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6b795f1d63d4..ebd6a0eb5ad55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ DEPENDENCIES: FEATURES: * **New Data Source:** `azurerm_eventhub` [GH-6841] +* **New Resource:** `azurerm_eventgrid_domain_topic` [GH-6859] IMPROVEMENTS: From e6711482d1d3766003ea4e7f9adb94e181211983 Mon Sep 17 00:00:00 2001 From: Tom Bamford Date: Thu, 14 May 2020 04:36:48 +0100 Subject: [PATCH 082/104] mariadb_server: New attributes, flatten `storage_profile` block (#6865) --- azurerm/helpers/validate/database.go | 23 - azurerm/helpers/validate/mariadb.go | 28 - .../mariadb/mariadb_configuration_resource.go | 13 +- .../mariadb/mariadb_database_resource.go | 24 +- .../mariadb/mariadb_firewall_rule_resource.go | 22 +- .../mariadb/mariadb_server_data_source.go | 6 - .../mariadb/mariadb_server_resource.go | 518 ++++++++++++------ .../mariadb_virtual_network_rule_resource.go | 8 +- .../services/mariadb/parse/mariadb.go | 33 ++ .../services/mariadb/parse/mariadb_test.go | 68 +++ .../mariadb_configuration_resource_test.go | 16 +- .../mariadb_firewall_rule_resource_test.go | 28 +- .../tests/mariadb_server_resource_test.go | 402 +++++++------- ...iadb_virtual_network_rule_resource_test.go | 70 +-- .../services/mariadb/validate/mariadb.go | 30 + .../services/mariadb/validate/mariadb_test.go | 106 ++++ website/docs/d/mariadb_server.html.markdown | 2 - website/docs/r/mariadb_server.html.markdown | 50 +- 18 files changed, 935 insertions(+), 512 deletions(-) delete mode 100644 azurerm/helpers/validate/database.go delete mode 100644 azurerm/helpers/validate/mariadb.go create mode 100644 azurerm/internal/services/mariadb/parse/mariadb.go create mode 100644 azurerm/internal/services/mariadb/parse/mariadb_test.go create mode 100644 azurerm/internal/services/mariadb/validate/mariadb.go create mode 100644 azurerm/internal/services/mariadb/validate/mariadb_test.go diff --git a/azurerm/helpers/validate/database.go b/azurerm/helpers/validate/database.go deleted file mode 100644 index d531faca7937e..0000000000000 --- a/azurerm/helpers/validate/database.go +++ /dev/null @@ -1,23 +0,0 @@ -package validate - -import ( - "fmt" - "regexp" -) - -func MariaDatabaseCollation(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return - } - - matched, _ := regexp.MatchString(`^[A-Za-z0-9_. ]+$`, v) - - if !matched { - errors = append(errors, fmt.Errorf("%s contains invalid characters, only alphanumeric, underscore, space characters are supported, got %s", k, v)) - return - } - - return warnings, errors -} diff --git a/azurerm/helpers/validate/mariadb.go b/azurerm/helpers/validate/mariadb.go deleted file mode 100644 index 0cd951947bf63..0000000000000 --- a/azurerm/helpers/validate/mariadb.go +++ /dev/null @@ -1,28 +0,0 @@ -package validate - -import ( - "fmt" - "regexp" -) - -func MariaDBFirewallRuleName(v interface{}, _ string) (warnings []string, errors []error) { - value := v.(string) - - // Firewall rule name can contain alphanumeric characters and hyphens and must be 1 - 128 characters long - if matched := regexp.MustCompile("^[-a-z0-9]{1,128}$").Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("Firewall rule name must be 1 - 128 characters long, contain only letters, numbers and hyphens.")) - } - - return warnings, errors -} - -func MariaDBServerName(v interface{}, _ string) (warnings []string, errors []error) { - value := v.(string) - - // MariaDB server name can contain alphanumeric characters and hyphens and must be 3 - 63 characters long - if matched := regexp.MustCompile("^[-a-z0-9]{3,63}$").Match([]byte(value)); !matched { - errors = append(errors, fmt.Errorf("Server name must be 3 - 63 characters long, contain only letters, numbers and hyphens.")) - } - - return warnings, errors -} diff --git a/azurerm/internal/services/mariadb/mariadb_configuration_resource.go b/azurerm/internal/services/mariadb/mariadb_configuration_resource.go index c109c0896f657..1d3ba4770dbe1 100644 --- a/azurerm/internal/services/mariadb/mariadb_configuration_resource.go +++ b/azurerm/internal/services/mariadb/mariadb_configuration_resource.go @@ -3,7 +3,6 @@ package mariadb import ( "fmt" "log" - "regexp" "time" "github.com/Azure/azure-sdk-for-go/services/mariadb/mgmt/2018-06-01/mariadb" @@ -11,6 +10,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -43,13 +43,10 @@ func resourceArmMariaDbConfiguration() *schema.Resource { "resource_group_name": azure.SchemaResourceGroupName(), "server_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^[-a-zA-Z0-9]{3,50}$"), - "server_name must be 3 - 50 characters long, and contain only letters, numbers and hyphens", - ), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.MariaDbServerServerName, }, "value": { diff --git a/azurerm/internal/services/mariadb/mariadb_database_resource.go b/azurerm/internal/services/mariadb/mariadb_database_resource.go index 21c5ee6e2ff42..1da63ec2fd50e 100644 --- a/azurerm/internal/services/mariadb/mariadb_database_resource.go +++ b/azurerm/internal/services/mariadb/mariadb_database_resource.go @@ -12,9 +12,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -49,13 +49,10 @@ func resourceArmMariaDbDatabase() *schema.Resource { "resource_group_name": azure.SchemaResourceGroupName(), "server_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^[-a-zA-Z0-9]{3,50}$"), - "server_name must be 3 - 50 characters long, and contain only letters, numbers and hyphens", - ), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.MariaDbServerServerName, }, "charset": { @@ -69,10 +66,13 @@ func resourceArmMariaDbDatabase() *schema.Resource { }, "collation": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validate.MariaDatabaseCollation, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile("^[A-Za-z0-9_. ]+$"), + "collation must contain only alphanumeric, underscore, space and dot characters", + ), }, }, } diff --git a/azurerm/internal/services/mariadb/mariadb_firewall_rule_resource.go b/azurerm/internal/services/mariadb/mariadb_firewall_rule_resource.go index 60c2217c04ff6..bfaab85693a6b 100644 --- a/azurerm/internal/services/mariadb/mariadb_firewall_rule_resource.go +++ b/azurerm/internal/services/mariadb/mariadb_firewall_rule_resource.go @@ -3,15 +3,18 @@ package mariadb import ( "fmt" "log" + "regexp" "time" "github.com/Azure/azure-sdk-for-go/services/mariadb/mgmt/2018-06-01/mariadb" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" + azValidate "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -35,10 +38,13 @@ func resourceArmMariaDBFirewallRule() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validate.MariaDBFirewallRuleName, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile("^[-a-z0-9]{1,128}$"), + "name must be 1-128 characters long and contain only letters, numbers and hyphens", + ), }, "resource_group_name": azure.SchemaResourceGroupName(), @@ -47,19 +53,19 @@ func resourceArmMariaDBFirewallRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.MariaDBServerName, + ValidateFunc: validate.MariaDbServerServerName, }, "start_ip_address": { Type: schema.TypeString, Required: true, - ValidateFunc: validate.IPv4Address, + ValidateFunc: azValidate.IPv4Address, }, "end_ip_address": { Type: schema.TypeString, Required: true, - ValidateFunc: validate.IPv4Address, + ValidateFunc: azValidate.IPv4Address, }, }, } diff --git a/azurerm/internal/services/mariadb/mariadb_server_data_source.go b/azurerm/internal/services/mariadb/mariadb_server_data_source.go index 038dd21ffb694..616c05cdc0b3b 100644 --- a/azurerm/internal/services/mariadb/mariadb_server_data_source.go +++ b/azurerm/internal/services/mariadb/mariadb_server_data_source.go @@ -46,12 +46,6 @@ func dataSourceMariaDbServer() *schema.Resource { Computed: true, }, - "administrator_login_password": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - }, - "version": { Type: schema.TypeString, Computed: true, diff --git a/azurerm/internal/services/mariadb/mariadb_server_resource.go b/azurerm/internal/services/mariadb/mariadb_server_resource.go index 251889db4847e..5e615ea3a203a 100644 --- a/azurerm/internal/services/mariadb/mariadb_server_resource.go +++ b/azurerm/internal/services/mariadb/mariadb_server_resource.go @@ -3,19 +3,22 @@ package mariadb import ( "fmt" "log" - "regexp" "strconv" "strings" "time" "github.com/Azure/azure-sdk-for-go/services/mariadb/mgmt/2018-06-01/mariadb" + "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" @@ -23,12 +26,24 @@ import ( func resourceArmMariaDbServer() *schema.Resource { return &schema.Resource{ - Create: resourceArmMariaDbServerCreateUpdate, + Create: resourceArmMariaDbServerCreate, Read: resourceArmMariaDbServerRead, - Update: resourceArmMariaDbServerCreateUpdate, + Update: resourceArmMariaDbServerUpdate, Delete: resourceArmMariaDbServerDelete, + Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + if _, err := parse.MariaDbServerServerID(d.Id()); err != nil { + return []*schema.ResourceData{d}, err + } + + d.Set("create_mode", "Default") + if v, ok := d.GetOk("create_mode"); ok && v.(string) != "" { + d.Set("create_mode", v) + } + + return []*schema.ResourceData{d}, nil + }, }, Timeouts: &schema.ResourceTimeout{ @@ -40,19 +55,86 @@ func resourceArmMariaDbServer() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.MariaDbServerServerName, + }, + + "administrator_login": { Type: schema.TypeString, - Required: true, + Optional: true, + Computed: true, ForceNew: true, - ValidateFunc: validation.StringMatch( - regexp.MustCompile("^[-a-zA-Z0-9]{3,50}$"), - "MariaDB server name must be 3 - 50 characters long, contain only letters, numbers and hyphens.", - ), + }, + + "administrator_login_password": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + }, + + "auto_grow_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, // TODO: remove in 3.0 and default to true + ConflictsWith: []string{"storage_profile.0.auto_grow"}, + }, + + "backup_retention_days": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ConflictsWith: []string{"storage_profile.0.backup_retention_days"}, + ValidateFunc: validation.IntBetween(7, 35), + }, + + "create_mode": { + Type: schema.TypeString, + Optional: true, + Default: string(mariadb.CreateModeDefault), + ValidateFunc: validation.StringInSlice([]string{ + string(mariadb.CreateModeDefault), + string(mariadb.CreateModeGeoRestore), + string(mariadb.CreateModePointInTimeRestore), + string(mariadb.CreateModeReplica), + }, false), + }, + + "creation_source_server_id": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.MariaDbServerServerID, + }, + + "fqdn": { + Type: schema.TypeString, + Computed: true, + }, + + "geo_redundant_backup_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + ConflictsWith: []string{"storage_profile.0.geo_redundant_backup"}, }, "location": azure.SchemaLocation(), + "public_network_access_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "resource_group_name": azure.SchemaResourceGroupName(), + "restore_point_in_time": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.IsRFC3339Time, + }, + "sku_name": { Type: schema.TypeString, Required: true, @@ -71,94 +153,111 @@ func resourceArmMariaDbServer() *schema.Resource { }, false), }, - "administrator_login": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, + "ssl_enforcement": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Deprecated: "this has been moved to the boolean attribute `ssl_enforcement_enabled` and will be removed in version 3.0 of the provider.", + ExactlyOneOf: []string{"ssl_enforcement", "ssl_enforcement_enabled"}, + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(mariadb.SslEnforcementEnumDisabled), + string(mariadb.SslEnforcementEnumEnabled), + }, false), }, - "administrator_login_password": { - Type: schema.TypeString, - Required: true, - Sensitive: true, - ValidateFunc: validation.StringIsNotEmpty, + "ssl_enforcement_enabled": { + Type: schema.TypeBool, + Optional: true, // required in 3.0 + Computed: true, // remove computed in 3.0 + ExactlyOneOf: []string{"ssl_enforcement", "ssl_enforcement_enabled"}, }, - "version": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validation.StringInSlice([]string{ - "10.2", - "10.3", - }, false), + "storage_mb": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ExactlyOneOf: []string{"storage_profile.0.storage_mb"}, + ValidateFunc: validation.All( + validation.IntBetween(5120, 4194304), + validation.IntDivisibleBy(1024), + ), }, "storage_profile": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Deprecated: "all storage_profile properties have been moved to the top level. This block will be removed in version 3.0 of the provider.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "storage_mb": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.All( - validation.IntBetween(5120, 4096000), - validation.IntDivisibleBy(1024), - ), + "auto_grow": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"auto_grow_enabled"}, + Deprecated: "this has been moved to the top level boolean attribute `auto_grow_enabled` and will be removed in version 3.0 of the provider.", + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(mariadb.StorageAutogrowEnabled), + string(mariadb.StorageAutogrowDisabled), + }, false), }, "backup_retention_days": { - Type: schema.TypeInt, - Optional: true, - ValidateFunc: validation.IntBetween(7, 35), + Type: schema.TypeInt, + Optional: true, + Computed: true, + ConflictsWith: []string{"backup_retention_days"}, + Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.", + ValidateFunc: validation.IntBetween(7, 35), }, "geo_redundant_backup": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"geo_redundant_backup_enabled"}, + Deprecated: "this has been moved to the top level boolean attribute `geo_redundant_backup_enabled` and will be removed in version 3.0 of the provider.", + DiffSuppressFunc: suppress.CaseDifference, ValidateFunc: validation.StringInSlice([]string{ string(mariadb.Enabled), string(mariadb.Disabled), }, false), }, - "auto_grow": { - Type: schema.TypeString, - Optional: true, - Default: string(mariadb.StorageAutogrowEnabled), - ValidateFunc: validation.StringInSlice([]string{ - string(mariadb.StorageAutogrowEnabled), - string(mariadb.StorageAutogrowDisabled), - }, false), + "storage_mb": { + Type: schema.TypeInt, + Optional: true, + ConflictsWith: []string{"storage_mb"}, + Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.", + ValidateFunc: validation.All( + validation.IntBetween(5120, 4096000), + validation.IntDivisibleBy(1024), + ), }, }, }, }, - "ssl_enforcement": { + "tags": tags.Schema(), + + "version": { Type: schema.TypeString, Required: true, + ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ - string(mariadb.SslEnforcementEnumDisabled), - string(mariadb.SslEnforcementEnumEnabled), + "10.2", + "10.3", }, false), }, - - "fqdn": { - Type: schema.TypeString, - Computed: true, - }, - - "tags": tags.Schema(), }, } } -func resourceArmMariaDbServerCreateUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceArmMariaDbServerCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).MariaDB.ServersClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -166,6 +265,7 @@ func resourceArmMariaDbServerCreateUpdate(d *schema.ResourceData, meta interface log.Printf("[INFO] preparing arguments for AzureRM MariaDB Server creation.") name := d.Get("name").(string) + location := azure.NormalizeLocation(d.Get("location").(string)) resourceGroup := d.Get("resource_group_name").(string) if features.ShouldResourcesBeImported() && d.IsNewResource() { @@ -181,97 +281,183 @@ func resourceArmMariaDbServerCreateUpdate(d *schema.ResourceData, meta interface } } - location := azure.NormalizeLocation(d.Get("location").(string)) - - storageProfile := expandAzureRmMariaDbStorageProfile(d) + mode := mariadb.CreateMode(d.Get("create_mode").(string)) + source := d.Get("creation_source_server_id").(string) + version := mariadb.ServerVersion(d.Get("version").(string)) sku, err := expandServerSkuName(d.Get("sku_name").(string)) if err != nil { return fmt.Errorf("error expanding sku_name for MariaDB Server %q (Resource Group %q): %v", name, resourceGroup, err) } - skuName := sku.Name - capacity := sku.Capacity - tier := string(sku.Tier) - storageMB := storageProfile.StorageMB + publicAccess := mariadb.PublicNetworkAccessEnumEnabled + if v := d.Get("public_network_access_enabled"); !v.(bool) { + publicAccess = mariadb.PublicNetworkAccessEnumDisabled + } - // General sku validation for all sku's - if !strings.HasSuffix(*skuName, strconv.Itoa(int(*capacity))) { - return fmt.Errorf("the value in the capacity property must match the capacity value defined in the sku name (sku.capacity: %d, sku.name: %s)", *capacity, *skuName) + ssl := mariadb.SslEnforcementEnumEnabled + if v, ok := d.GetOk("ssl_enforcement"); ok && strings.EqualFold(v.(string), string(mariadb.SslEnforcementEnumDisabled)) { + ssl = mariadb.SslEnforcementEnumDisabled + } + if v, ok := d.GetOkExists("ssl_enforcement_enabled"); ok && !v.(bool) { + ssl = mariadb.SslEnforcementEnumDisabled } - // Specific validation based on sku's pricing tier - // Basic - if strings.ToLower(tier) == "basic" { - if !strings.HasPrefix(*skuName, "B_") { - return fmt.Errorf("the basic pricing tier sku name must begin with the letter B (sku.name: %s)", *skuName) - } + storage := expandMariaDbStorageProfile(d) - if *storageMB > 1024000 { - return fmt.Errorf("basic pricing tier only supports upto 1,024,000 MB (1TB) of storage (storageProfile.StorageMB: %d)", *storageMB) + var props mariadb.BasicServerPropertiesForCreate + switch mode { + case mariadb.CreateModeDefault: + admin := d.Get("administrator_login").(string) + pass := d.Get("administrator_login_password").(string) + + if admin == "" { + return fmt.Errorf("`administrator_login` must not be empty when `create_mode` is `default`") + } + if pass == "" { + return fmt.Errorf("`administrator_login_password` must not be empty when `create_mode` is `default`") } - if *capacity > 2 { - return fmt.Errorf("basic pricing tier only supports upto 2 vCores (sku.capacity: %d)", *capacity) + if _, ok := d.GetOk("restore_point_in_time"); ok { + return fmt.Errorf("`restore_point_in_time` cannot be set when `create_mode` is `default`") } - } - // General Purpose - if strings.ToLower(tier) == "generalpurpose" { - if !strings.HasPrefix(*skuName, "GP_") { - return fmt.Errorf("the general purpose pricing tier sku name must begin with the letters GP (sku.name: %s)", *skuName) + props = &mariadb.ServerPropertiesForDefaultCreate{ + AdministratorLogin: &admin, + AdministratorLoginPassword: &pass, + CreateMode: mode, + PublicNetworkAccess: publicAccess, + SslEnforcement: ssl, + StorageProfile: storage, + Version: version, } + case mariadb.CreateModePointInTimeRestore: + v, ok := d.GetOk("restore_point_in_time") + if !ok || v.(string) == "" { + return fmt.Errorf("restore_point_in_time must be set when create_mode is PointInTimeRestore") + } + time, _ := time.Parse(time.RFC3339, v.(string)) // should be validated by the schema - if *capacity < 2 { - return fmt.Errorf("general purpose pricing tier must have at least 2 vCores (sku.capacity: %d)", *capacity) + props = &mariadb.ServerPropertiesForRestore{ + CreateMode: mode, + SourceServerID: &source, + RestorePointInTime: &date.Time{ + Time: time, + }, + PublicNetworkAccess: publicAccess, + SslEnforcement: ssl, + StorageProfile: storage, + Version: version, + } + case mariadb.CreateModeGeoRestore: + props = &mariadb.ServerPropertiesForGeoRestore{ + CreateMode: mode, + SourceServerID: &source, + PublicNetworkAccess: publicAccess, + SslEnforcement: ssl, + StorageProfile: storage, + Version: version, + } + case mariadb.CreateModeReplica: + props = &mariadb.ServerPropertiesForReplica{ + CreateMode: mode, + SourceServerID: &source, + PublicNetworkAccess: publicAccess, + SslEnforcement: ssl, + Version: version, } } - // Memory Optimized - if strings.ToLower(tier) == "memoryoptimized" { - if !strings.HasPrefix(*skuName, "MO_") { - return fmt.Errorf("the memory optimized pricing tier sku name must begin with the letters MO (sku.name: %s)", *skuName) - } + server := mariadb.ServerForCreate{ + Location: &location, + Properties: props, + Sku: sku, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + } - if *capacity < 2 { - return fmt.Errorf("memory optimized pricing tier must have at least 2 vCores (sku.capacity: %d)", *capacity) - } + future, err := client.Create(ctx, resourceGroup, name, server) + if err != nil { + return fmt.Errorf("creating MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + } - if *capacity > 16 { - return fmt.Errorf("memory optimized pricing tier only supports upto 16 vCores (sku.capacity: %d)", *capacity) - } + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("waiting for creation of MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + read, err := client.Get(ctx, resourceGroup, name) + if err != nil { + return fmt.Errorf("retrieving MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + if read.ID == nil { + return fmt.Errorf("cannot read MariaDB Server %q (Resource Group %q) ID", name, resourceGroup) + } + + d.SetId(*read.ID) + + return resourceArmMariaDbServerRead(d, meta) +} + +func resourceArmMariaDbServerUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).MariaDB.ServersClient + ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + log.Printf("[INFO] preparing arguments for AzureRM MariaDB Server update.") + + id, err := parse.MariaDbServerServerID(d.Id()) + if err != nil { + return fmt.Errorf("parsing MariaDB Server ID : %v", err) + } + + sku, err := expandServerSkuName(d.Get("sku_name").(string)) + if err != nil { + return fmt.Errorf("expanding sku_name for MariaDB Server %q (Resource Group %q): %v", id.Name, id.ResourceGroup, err) } - properties := mariadb.ServerForCreate{ - Location: &location, - Properties: &mariadb.ServerPropertiesForDefaultCreate{ - AdministratorLogin: utils.String(d.Get("administrator_login").(string)), + publicAccess := mariadb.PublicNetworkAccessEnumEnabled + if v := d.Get("public_network_access_enabled").(bool); !v { + publicAccess = mariadb.PublicNetworkAccessEnumDisabled + } + + ssl := mariadb.SslEnforcementEnumEnabled + if v := d.Get("ssl_enforcement"); strings.EqualFold(v.(string), string(mariadb.SslEnforcementEnumDisabled)) { + ssl = mariadb.SslEnforcementEnumDisabled + } + if v := d.Get("ssl_enforcement_enabled").(bool); !v { + ssl = mariadb.SslEnforcementEnumDisabled + } + + storageProfile := expandMariaDbStorageProfile(d) + + properties := mariadb.ServerUpdateParameters{ + ServerUpdateParametersProperties: &mariadb.ServerUpdateParametersProperties{ AdministratorLoginPassword: utils.String(d.Get("administrator_login_password").(string)), - Version: mariadb.ServerVersion(d.Get("version").(string)), - SslEnforcement: mariadb.SslEnforcementEnum(d.Get("ssl_enforcement").(string)), + PublicNetworkAccess: publicAccess, + SslEnforcement: ssl, StorageProfile: storageProfile, - CreateMode: mariadb.CreateModeDefault, + Version: mariadb.ServerVersion(d.Get("version").(string)), }, Sku: sku, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - future, err := client.Create(ctx, resourceGroup, name, properties) + future, err := client.Update(ctx, id.ResourceGroup, id.Name, properties) if err != nil { - return fmt.Errorf("Error creating MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("updating MariaDB Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for creation of MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("waiting for MariaDB Server %q (Resource Group %q) to finish updating: %+v", id.Name, id.ResourceGroup, err) } - read, err := client.Get(ctx, resourceGroup, name) + read, err := client.Get(ctx, id.ResourceGroup, id.Name) if err != nil { - return fmt.Errorf("Error retrieving MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("retrieving MariaDB Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read MariaDB Server %q (Resource Group %q) ID", name, resourceGroup) + return fmt.Errorf("cannot read MariaDB Server %q (Resource Group %q) ID", id.Name, id.ResourceGroup) } d.SetId(*read.ID) @@ -284,26 +470,24 @@ func resourceArmMariaDbServerRead(d *schema.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.MariaDbServerServerID(d.Id()) if err != nil { - return err + return fmt.Errorf("parsing MariaDB Server ID : %v", err) } - resourceGroup := id.ResourceGroup - name := id.Path["servers"] - resp, err := client.Get(ctx, resourceGroup, name) + resp, err := client.Get(ctx, id.ResourceGroup, id.Name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[WARN] MariaDB Server %q was not found (Resource Group %q)", name, resourceGroup) + log.Printf("[WARN] MariaDB Server %q was not found (Resource Group %q)", id.Name, id.ResourceGroup) d.SetId("") return nil } - return fmt.Errorf("Error making Read request on Azure MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("making Read request on Azure MariaDB Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) + d.Set("resource_group_name", id.ResourceGroup) if location := resp.Location; location != nil { d.Set("location", azure.NormalizeLocation(*location)) @@ -313,16 +497,26 @@ func resourceArmMariaDbServerRead(d *schema.ResourceData, meta interface{}) erro d.Set("sku_name", sku.Name) } - if properties := resp.ServerProperties; properties != nil { - d.Set("administrator_login", properties.AdministratorLogin) - d.Set("version", string(properties.Version)) - d.Set("ssl_enforcement", string(properties.SslEnforcement)) - // Computed - d.Set("fqdn", properties.FullyQualifiedDomainName) + if props := resp.ServerProperties; props != nil { + d.Set("administrator_login", props.AdministratorLogin) + d.Set("public_network_access_enabled", props.PublicNetworkAccess == mariadb.PublicNetworkAccessEnumEnabled) + d.Set("ssl_enforcement", string(props.SslEnforcement)) + d.Set("ssl_enforcement_enabled", props.SslEnforcement == mariadb.SslEnforcementEnumEnabled) + d.Set("version", string(props.Version)) - if err := d.Set("storage_profile", flattenMariaDbStorageProfile(properties.StorageProfile)); err != nil { - return fmt.Errorf("Error setting `storage_profile`: %+v", err) + if err := d.Set("storage_profile", flattenMariaDbStorageProfile(resp.StorageProfile)); err != nil { + return fmt.Errorf("setting `storage_profile`: %+v", err) } + + if storage := props.StorageProfile; storage != nil { + d.Set("auto_grow_enabled", storage.StorageAutogrow == mariadb.StorageAutogrowEnabled) + d.Set("backup_retention_days", storage.BackupRetentionDays) + d.Set("geo_redundant_backup_enabled", storage.GeoRedundantBackup == mariadb.Enabled) + d.Set("storage_mb", storage.StorageMB) + } + + // Computed + d.Set("fqdn", props.FullyQualifiedDomainName) } return tags.FlattenAndSet(d, resp.Tags) @@ -333,20 +527,18 @@ func resourceArmMariaDbServerDelete(d *schema.ResourceData, meta interface{}) er ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.MariaDbServerServerID(d.Id()) if err != nil { - return err + return fmt.Errorf("parsing MariaDB Server ID : %v", err) } - resourceGroup := id.ResourceGroup - name := id.Path["servers"] - future, err := client.Delete(ctx, resourceGroup, name) + future, err := client.Delete(ctx, id.ResourceGroup, id.Name) if err != nil { if response.WasNotFound(future.Response()) { return nil } - return fmt.Errorf("Error deleting MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("deleting MariaDB Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { @@ -354,7 +546,7 @@ func resourceArmMariaDbServerDelete(d *schema.ResourceData, meta interface{}) er return nil } - return fmt.Errorf("Error waiting for deletion of MariaDB Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("waiting for deletion of MariaDB Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } return nil @@ -363,7 +555,7 @@ func resourceArmMariaDbServerDelete(d *schema.ResourceData, meta interface{}) er func expandServerSkuName(skuName string) (*mariadb.Sku, error) { parts := strings.Split(skuName, "_") if len(parts) != 3 { - return nil, fmt.Errorf("sku_name (%s) has the worng number of parts (%d) after splitting on _", skuName, len(parts)) + return nil, fmt.Errorf("sku_name (%s) has the wrong number of parts (%d) after splitting on _", skuName, len(parts)) } var tier mariadb.SkuTier @@ -391,21 +583,41 @@ func expandServerSkuName(skuName string) (*mariadb.Sku, error) { }, nil } -func expandAzureRmMariaDbStorageProfile(d *schema.ResourceData) *mariadb.StorageProfile { - storageprofiles := d.Get("storage_profile").([]interface{}) - storageprofile := storageprofiles[0].(map[string]interface{}) +func expandMariaDbStorageProfile(d *schema.ResourceData) *mariadb.StorageProfile { + storage := mariadb.StorageProfile{} + if v, ok := d.GetOk("storage_profile"); ok { + storageprofile := v.([]interface{})[0].(map[string]interface{}) - backupRetentionDays := storageprofile["backup_retention_days"].(int) - geoRedundantBackup := storageprofile["geo_redundant_backup"].(string) - storageMB := storageprofile["storage_mb"].(int) - autoGrow := storageprofile["auto_grow"].(string) + storage.BackupRetentionDays = utils.Int32(int32(storageprofile["backup_retention_days"].(int))) + storage.GeoRedundantBackup = mariadb.GeoRedundantBackup(storageprofile["geo_redundant_backup"].(string)) + storage.StorageAutogrow = mariadb.StorageAutogrow(storageprofile["auto_grow"].(string)) + storage.StorageMB = utils.Int32(int32(storageprofile["storage_mb"].(int))) + } - return &mariadb.StorageProfile{ - BackupRetentionDays: utils.Int32(int32(backupRetentionDays)), - GeoRedundantBackup: mariadb.GeoRedundantBackup(geoRedundantBackup), - StorageMB: utils.Int32(int32(storageMB)), - StorageAutogrow: mariadb.StorageAutogrow(autoGrow), + // now override whatever we may have from the block with the top level properties + if v, ok := d.GetOk("auto_grow_enabled"); ok { + storage.StorageAutogrow = mariadb.StorageAutogrowDisabled + if v.(bool) { + storage.StorageAutogrow = mariadb.StorageAutogrowEnabled + } } + + if v, ok := d.GetOk("backup_retention_days"); ok { + storage.BackupRetentionDays = utils.Int32(int32(v.(int))) + } + + if v, ok := d.GetOk("geo_redundant_backup_enabled"); ok { + storage.GeoRedundantBackup = mariadb.Disabled + if v.(bool) { + storage.GeoRedundantBackup = mariadb.Enabled + } + } + + if v, ok := d.GetOk("storage_mb"); ok { + storage.StorageMB = utils.Int32(int32(v.(int))) + } + + return &storage } func flattenMariaDbStorageProfile(storage *mariadb.StorageProfile) []interface{} { @@ -415,9 +627,7 @@ func flattenMariaDbStorageProfile(storage *mariadb.StorageProfile) []interface{} return []interface{}{} } - if storageMB := storage.StorageMB; storageMB != nil { - values["storage_mb"] = *storageMB - } + values["auto_grow"] = string(storage.StorageAutogrow) if backupRetentionDays := storage.BackupRetentionDays; backupRetentionDays != nil { values["backup_retention_days"] = *backupRetentionDays @@ -425,7 +635,9 @@ func flattenMariaDbStorageProfile(storage *mariadb.StorageProfile) []interface{} values["geo_redundant_backup"] = string(storage.GeoRedundantBackup) - values["auto_grow"] = string(storage.StorageAutogrow) + if storageMB := storage.StorageMB; storageMB != nil { + values["storage_mb"] = *storageMB + } return []interface{}{values} } diff --git a/azurerm/internal/services/mariadb/mariadb_virtual_network_rule_resource.go b/azurerm/internal/services/mariadb/mariadb_virtual_network_rule_resource.go index d59179d23a91e..393cc83a1be69 100644 --- a/azurerm/internal/services/mariadb/mariadb_virtual_network_rule_resource.go +++ b/azurerm/internal/services/mariadb/mariadb_virtual_network_rule_resource.go @@ -11,12 +11,12 @@ import ( "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" + azValidate "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -43,7 +43,7 @@ func resourceArmMariaDbVirtualNetworkRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.VirtualNetworkRuleName, + ValidateFunc: azValidate.VirtualNetworkRuleName, }, "resource_group_name": azure.SchemaResourceGroupName(), @@ -52,7 +52,7 @@ func resourceArmMariaDbVirtualNetworkRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, + ValidateFunc: validate.MariaDbServerServerName, }, "subnet_id": { diff --git a/azurerm/internal/services/mariadb/parse/mariadb.go b/azurerm/internal/services/mariadb/parse/mariadb.go new file mode 100644 index 0000000000000..f13fbfb352e3a --- /dev/null +++ b/azurerm/internal/services/mariadb/parse/mariadb.go @@ -0,0 +1,33 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type MariaDbServerServerId struct { + ResourceGroup string + Name string +} + +func MariaDbServerServerID(input string) (*MariaDbServerServerId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("unable to parse MariaDB Server ID %q: %+v", input, err) + } + + server := MariaDbServerServerId{ + ResourceGroup: id.ResourceGroup, + } + + if server.Name, err = id.PopSegment("servers"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &server, nil +} diff --git a/azurerm/internal/services/mariadb/parse/mariadb_test.go b/azurerm/internal/services/mariadb/parse/mariadb_test.go new file mode 100644 index 0000000000000..a8bfac7548319 --- /dev/null +++ b/azurerm/internal/services/mariadb/parse/mariadb_test.go @@ -0,0 +1,68 @@ +package parse + +import ( + "testing" +) + +func TestValidateMariaDbServerServerID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *MariaDbServerServerId + }{ + { + Name: "Empty resource ID", + Input: "", + Expected: nil, + }, + { + Name: "No resourceGroups segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No resource group name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource group", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/", + Expected: nil, + }, + { + Name: "Missing server name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMariaDB/servers/", + Expected: nil, + }, + { + Name: "Valid", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMariaDB/servers/test-mariadb", + Expected: &MariaDbServerServerId{ + Name: "test-mariadb", + ResourceGroup: "test-rg", + }, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := MariaDbServerServerID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/mariadb/tests/mariadb_configuration_resource_test.go b/azurerm/internal/services/mariadb/tests/mariadb_configuration_resource_test.go index 7cf5c68a23a10..ac2c0ab8d3bae 100644 --- a/azurerm/internal/services/mariadb/tests/mariadb_configuration_resource_test.go +++ b/azurerm/internal/services/mariadb/tests/mariadb_configuration_resource_test.go @@ -218,19 +218,15 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" - - sku = "GP_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } + sku_name = "GP_Gen5_2" + version = "10.2" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } diff --git a/azurerm/internal/services/mariadb/tests/mariadb_firewall_rule_resource_test.go b/azurerm/internal/services/mariadb/tests/mariadb_firewall_rule_resource_test.go index 19b0baaf93ae8..816ef9f11ac50 100644 --- a/azurerm/internal/services/mariadb/tests/mariadb_firewall_rule_resource_test.go +++ b/azurerm/internal/services/mariadb/tests/mariadb_firewall_rule_resource_test.go @@ -11,18 +11,18 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func TestAccAzureRMMariaDBFirewallRule_basic(t *testing.T) { +func TestAccAzureRMMariaDbFirewallRule_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_firewall_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBFirewallRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbFirewallRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBFirewallRule_basic(data), + Config: testAccAzureRMMariaDbFirewallRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBFirewallRuleExists(data.ResourceName), + testCheckAzureRMMariaDbFirewallRuleExists(data.ResourceName), ), }, data.ImportStep(), @@ -30,29 +30,29 @@ func TestAccAzureRMMariaDBFirewallRule_basic(t *testing.T) { }) } -func TestAccAzureRMMariaDBFirewallRule_requiresImport(t *testing.T) { +func TestAccAzureRMMariaDbFirewallRule_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_firewall_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBFirewallRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbFirewallRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBFirewallRule_basic(data), + Config: testAccAzureRMMariaDbFirewallRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBFirewallRuleExists(data.ResourceName), + testCheckAzureRMMariaDbFirewallRuleExists(data.ResourceName), ), }, { - Config: testAccAzureRMMariaDBFirewallRule_requiresImport(data), + Config: testAccAzureRMMariaDbFirewallRule_requiresImport(data), ExpectError: acceptance.RequiresImportError("azurerm_mariadb_firewall_rule"), }, }, }) } -func testCheckAzureRMMariaDBFirewallRuleExists(resourceName string) resource.TestCheckFunc { +func testCheckAzureRMMariaDbFirewallRuleExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MariaDB.FirewallRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -82,7 +82,7 @@ func testCheckAzureRMMariaDBFirewallRuleExists(resourceName string) resource.Tes } } -func testCheckAzureRMMariaDBFirewallRuleDestroy(s *terraform.State) error { +func testCheckAzureRMMariaDbFirewallRuleDestroy(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MariaDB.DatabasesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -109,7 +109,7 @@ func testCheckAzureRMMariaDBFirewallRuleDestroy(s *terraform.State) error { return nil } -func testAccAzureRMMariaDBFirewallRule_basic(data acceptance.TestData) string { +func testAccAzureRMMariaDbFirewallRule_basic(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -149,7 +149,7 @@ resource "azurerm_mariadb_firewall_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMariaDBFirewallRule_requiresImport(data acceptance.TestData) string { +func testAccAzureRMMariaDbFirewallRule_requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s @@ -160,5 +160,5 @@ resource "azurerm_mariadb_firewall_rule" "import" { start_ip_address = azurerm_mariadb_firewall_rule.test.start_ip_address end_ip_address = azurerm_mariadb_firewall_rule.test.end_ip_address } -`, testAccAzureRMMariaDBFirewallRule_basic(data)) +`, testAccAzureRMMariaDbFirewallRule_basic(data)) } diff --git a/azurerm/internal/services/mariadb/tests/mariadb_server_resource_test.go b/azurerm/internal/services/mariadb/tests/mariadb_server_resource_test.go index 9dfe8fc610437..a4a2fdb13fb92 100644 --- a/azurerm/internal/services/mariadb/tests/mariadb_server_resource_test.go +++ b/azurerm/internal/services/mariadb/tests/mariadb_server_resource_test.go @@ -3,6 +3,7 @@ package tests import ( "fmt" "testing" + "time" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/terraform" @@ -11,8 +12,9 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func TestAccAzureRMMariaDbServer_basic(t *testing.T) { +func TestAccAzureRMMariaDbServer_basicTenTwo(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.2" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -20,12 +22,10 @@ func TestAccAzureRMMariaDbServer_basic(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_basic(data), + Config: testAccAzureRMMariaDbServer_basic(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), - resource.TestCheckResourceAttr(data.ResourceName, "version", "10.2"), - resource.TestCheckResourceAttr(data.ResourceName, "ssl_enforcement", "Enabled"), + resource.TestCheckResourceAttr(data.ResourceName, "version", version), ), }, data.ImportStep("administrator_login_password"), // not returned as sensitive @@ -33,8 +33,9 @@ func TestAccAzureRMMariaDbServer_basic(t *testing.T) { }) } -func TestAccAzureRMMariaDbServer_requiresImport(t *testing.T) { +func TestAccAzureRMMariaDbServer_basicTenTwoDeprecated(t *testing.T) { // remove in v3.0 data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.2" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -42,21 +43,41 @@ func TestAccAzureRMMariaDbServer_requiresImport(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_basic(data), + Config: testAccAzureRMMariaDbServer_basicDeprecated(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "version", version), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + }, + }) +} + +func TestAccAzureRMMariaDbServer_basicTenThree(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.3" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMariaDbServerDestroy, + Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_requiresImport(data), - ExpectError: acceptance.RequiresImportError("azurerm_mariadb_server"), + Config: testAccAzureRMMariaDbServer_basic(data, version), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "version", version), + ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } -func TestAccAzureRMMariaDbServer_basicMaxStorage(t *testing.T) { +func TestAccAzureRMMariaDbServer_autogrowOnly(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.3" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -64,12 +85,9 @@ func TestAccAzureRMMariaDbServer_basicMaxStorage(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_basicMaxStorage(data), + Config: testAccAzureRMMariaDbServer_autogrow(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), - resource.TestCheckResourceAttr(data.ResourceName, "version", "10.2"), - resource.TestCheckResourceAttr(data.ResourceName, "ssl_enforcement", "Enabled"), ), }, data.ImportStep("administrator_login_password"), // not returned as sensitive @@ -77,7 +95,26 @@ func TestAccAzureRMMariaDbServer_basicMaxStorage(t *testing.T) { }) } -func TestAccAzureRMMariaDbServer_generalPurpose(t *testing.T) { +func TestAccAzureRMMariaDbServer_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMariaDbServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMariaDbServer_basic(data, "10.3"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMMariaDbServer_requiresImport), + }, + }) +} + +func TestAccAzureRMMariaDbServer_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") resource.ParallelTest(t, resource.TestCase{ @@ -86,7 +123,7 @@ func TestAccAzureRMMariaDbServer_generalPurpose(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_generalPurpose(data), + Config: testAccAzureRMMariaDbServer_complete(data, "10.3"), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), ), @@ -96,8 +133,9 @@ func TestAccAzureRMMariaDbServer_generalPurpose(t *testing.T) { }) } -func TestAccAzureRMMariaDbServer_memoryOptimized(t *testing.T) { +func TestAccAzureRMMariaDbServer_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.3" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -105,7 +143,21 @@ func TestAccAzureRMMariaDbServer_memoryOptimized(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_memoryOptimizedGeoRedundant(data), + Config: testAccAzureRMMariaDbServer_basic(data, version), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMariaDbServer_complete(data, version), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMariaDbServer_basic(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), ), @@ -115,8 +167,9 @@ func TestAccAzureRMMariaDbServer_memoryOptimized(t *testing.T) { }) } -func TestAccAzureRMMariaDbServer_updatePassword(t *testing.T) { +func TestAccAzureRMMariaDbServer_completeDeprecatedMigrate(t *testing.T) { // remove in v3.0 data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.3" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -124,23 +177,26 @@ func TestAccAzureRMMariaDbServer_updatePassword(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_basic(data), + Config: testAccAzureRMMariaDbServer_completeDeprecated(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive { - Config: testAccAzureRMMariaDbServer_basicUpdatedPassword(data), + Config: testAccAzureRMMariaDbServer_complete(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } -func TestAccAzureRMMariaDbServer_updated(t *testing.T) { +func TestAccAzureRMMariaDbServer_updateDeprecated(t *testing.T) { // remove in v3.0 data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.2" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -148,25 +204,26 @@ func TestAccAzureRMMariaDbServer_updated(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_basic(data), + Config: testAccAzureRMMariaDbServer_basicDeprecated(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku.0.name", "B_Gen5_2"), - resource.TestCheckResourceAttr(data.ResourceName, "version", "10.2"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "51200"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMariaDbServer_completeDeprecated(data, version), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive { - Config: testAccAzureRMMariaDbServer_basicUpdated(data), + Config: testAccAzureRMMariaDbServer_basicDeprecated(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku.0.name", "B_Gen5_1"), - resource.TestCheckResourceAttr(data.ResourceName, "version", "10.2"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "640000"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } @@ -180,29 +237,55 @@ func TestAccAzureRMMariaDbServer_updateSKU(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_generalPurpose(data), + Config: testAccAzureRMMariaDbServer_sku(data, "GP_Gen5_32"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMariaDbServer_sku(data, "MO_Gen5_16"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMariaDbServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + }, + }) +} + +func TestAccAzureRMMariaDbServer_createReplica(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + version := "10.3" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMariaDbServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMariaDbServer_basic(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku_name", "GP_Gen5_32"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "640000"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive { - Config: testAccAzureRMMariaDbServer_memoryOptimized(data), + Config: testAccAzureRMMariaDbServer_createReplica(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku_name", "MO_Gen5_16"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "4096000"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), + testCheckAzureRMMariaDbServerExists("azurerm_mariadb_server.replica"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } -func TestAccAzureRMMariaDbServer_storageAutogrow(t *testing.T) { +func TestAccAzureRMMariaDbServer_createPointInTimeRestore(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_server", "test") + restoreTime := time.Now().Add(11 * time.Minute) + version := "10.3" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -210,19 +293,21 @@ func TestAccAzureRMMariaDbServer_storageAutogrow(t *testing.T) { CheckDestroy: testCheckAzureRMMariaDbServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDbServer_basic(data), + Config: testAccAzureRMMariaDbServer_basic(data, version), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.auto_grow", "Enabled"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive { - Config: testAccAzureRMMariaDbServer_storageAutogrowUpdated(data), + PreConfig: func() { time.Sleep(restoreTime.Sub(time.Now().Add(-7 * time.Minute))) }, + Config: testAccAzureRMMariaDbServer_createPointInTimeRestore(data, version, restoreTime.Format(time.RFC3339)), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMariaDbServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.auto_grow", "Disabled"), + testCheckAzureRMMariaDbServerExists("azurerm_mariadb_server.restore"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } @@ -284,7 +369,7 @@ func testCheckAzureRMMariaDbServerDestroy(s *terraform.State) error { return nil } -func testAccAzureRMMariaDbServer_basic(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_basic(data acceptance.TestData, version string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -299,50 +384,18 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "B_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } - - administrator_login = "acctestun" - administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) -} - -func testAccAzureRMMariaDbServer_requiresImport(data acceptance.TestData) string { - template := testAccAzureRMMariaDbServer_basic(data) - return fmt.Sprintf(` -%s - -resource "azurerm_mariadb_server" "import" { - name = azurerm_mariadb_server.test.name - location = azurerm_mariadb_server.test.location - resource_group_name = azurerm_mariadb_server.test.resource_group_name - - sku_name = "B_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } + sku_name = "B_Gen5_2" + version = "%s" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, template) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMariaDbServer_basicUpdatedPassword(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_basicDeprecated(data acceptance.TestData, version string) string { // remove in v3.0 return fmt.Sprintf(` provider "azurerm" { features {} @@ -357,24 +410,21 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "B_Gen5_2" + sku_name = "B_Gen5_2" + version = "%s" storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" + storage_mb = 51200 } administrator_login = "acctestun" - administrator_login_password = "R3dH0TCh1l1P3pp3rs!" - version = "10.2" + administrator_login_password = "H@Sh1CoR3!" ssl_enforcement = "Enabled" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMariaDbServer_basicUpdated(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_complete(data acceptance.TestData, version string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -389,24 +439,22 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "B_Gen5_1" - - storage_profile { - storage_mb = 640000 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } + sku_name = "B_Gen5_2" + version = "%s" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + auto_grow_enabled = true + backup_retention_days = 14 + create_mode = "Default" + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMariaDbServer_basicMaxStorage(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_completeDeprecated(data acceptance.TestData, version string) string { // remove in v3.0 return fmt.Sprintf(` provider "azurerm" { features {} @@ -421,24 +469,25 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "B_Gen5_2" + sku_name = "B_Gen5_2" + version = "%s" storage_profile { - storage_mb = 947200 + auto_grow = "Enabled" backup_retention_days = 7 geo_redundant_backup = "Disabled" + storage_mb = 51200 } administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" + create_mode = "Default" ssl_enforcement = "Enabled" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMariaDbServer_generalPurpose(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_autogrow(data acceptance.TestData, version string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -453,56 +502,43 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "GP_Gen5_32" - - storage_profile { - storage_mb = 640000 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } + sku_name = "B_Gen5_2" + version = "%s" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + auto_grow_enabled = true + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMariaDbServer_memoryOptimized(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMMariaDbServer_basic(data, "10.3") return fmt.Sprintf(` -provider "azurerm" { - features {} -} - -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} - -resource "azurerm_mariadb_server" "test" { - name = "acctestmariadbsvr-%d" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - - sku_name = "MO_Gen5_16" +%s - storage_profile { - storage_mb = 4096000 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } +resource "azurerm_mariadb_server" "import" { + name = azurerm_mariadb_server.test.name + location = azurerm_mariadb_server.test.location + resource_group_name = azurerm_mariadb_server.test.resource_group_name + sku_name = "B_Gen5_2" + version = "10.3" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, template) } -func testAccAzureRMMariaDbServer_memoryOptimizedGeoRedundant(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_sku(data acceptance.TestData, sku string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -517,52 +553,50 @@ resource "azurerm_mariadb_server" "test" { name = "acctestmariadbsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "MO_Gen5_16" - - storage_profile { - storage_mb = 4096000 - backup_retention_days = 7 - geo_redundant_backup = "Enabled" - } + sku_name = "%s" + version = "10.2" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 640000 } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, sku) } -func testAccAzureRMMariaDbServer_storageAutogrowUpdated(data acceptance.TestData) string { +func testAccAzureRMMariaDbServer_createReplica(data acceptance.TestData, version string) string { return fmt.Sprintf(` -provider "azurerm" { - features {} -} +%s -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" +resource "azurerm_mariadb_server" "replica" { + name = "acctestmariadbsvr-%d-replica" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku_name = "B_Gen5_2" + version = "%s" + create_mode = "Replica" + creation_source_server_id = azurerm_mariadb_server.test.id + ssl_enforcement_enabled = true +} +`, testAccAzureRMMariaDbServer_basic(data, version), data.RandomInteger, version) } -resource "azurerm_mariadb_server" "test" { - name = "acctestmariadbsvr-%d" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - - sku_name = "B_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - auto_grow = "Disabled" - } +func testAccAzureRMMariaDbServer_createPointInTimeRestore(data acceptance.TestData, version, restoreTime string) string { + return fmt.Sprintf(` +%s - administrator_login = "acctestun" - administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" -} -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +resource "azurerm_mariadb_server" "restore" { + name = "acctestmariadbsvr-%d-restore" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku_name = "B_Gen5_2" + version = "%s" + create_mode = "PointInTimeRestore" + creation_source_server_id = azurerm_mariadb_server.test.id + restore_point_in_time = "%s" + ssl_enforcement_enabled = true +} +`, testAccAzureRMMariaDbServer_basic(data, version), data.RandomInteger, version, restoreTime) } diff --git a/azurerm/internal/services/mariadb/tests/mariadb_virtual_network_rule_resource_test.go b/azurerm/internal/services/mariadb/tests/mariadb_virtual_network_rule_resource_test.go index 220e66361f78e..17389e00e524e 100644 --- a/azurerm/internal/services/mariadb/tests/mariadb_virtual_network_rule_resource_test.go +++ b/azurerm/internal/services/mariadb/tests/mariadb_virtual_network_rule_resource_test.go @@ -13,47 +13,47 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func TestAccAzureRMMariaDBVirtualNetworkRule_basic(t *testing.T) { +func TestAccAzureRMMariaDbVirtualNetworkRule_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBVirtualNetworkRule_basic(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(data.ResourceName), ), }, }, }) } -func TestAccAzureRMMariaDBVirtualNetworkRule_requiresImport(t *testing.T) { +func TestAccAzureRMMariaDbVirtualNetworkRule_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBVirtualNetworkRule_basic(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(data.ResourceName), ), }, { - Config: testAccAzureRMMariaDBVirtualNetworkRule_requiresImport(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_requiresImport(data), ExpectError: acceptance.RequiresImportError("azurerm_mariadb_virtual_network_rule"), }, }, }) } -func TestAccAzureRMMariaDBVirtualNetworkRule_switchSubnets(t *testing.T) { +func TestAccAzureRMMariaDbVirtualNetworkRule_switchSubnets(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_virtual_network_rule", "test") // Create regex strings that will ensure that one subnet name exists, but not the other @@ -63,19 +63,19 @@ func TestAccAzureRMMariaDBVirtualNetworkRule_switchSubnets(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBVirtualNetworkRule_subnetSwitchPre(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_subnetSwitchPre(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(data.ResourceName), resource.TestMatchResourceAttr(data.ResourceName, "subnet_id", preConfigRegex), ), }, { - Config: testAccAzureRMMariaDBVirtualNetworkRule_subnetSwitchPost(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_subnetSwitchPost(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(data.ResourceName), resource.TestMatchResourceAttr(data.ResourceName, "subnet_id", postConfigRegex), ), }, @@ -83,19 +83,19 @@ func TestAccAzureRMMariaDBVirtualNetworkRule_switchSubnets(t *testing.T) { }) } -func TestAccAzureRMMariaDBVirtualNetworkRule_disappears(t *testing.T) { +func TestAccAzureRMMariaDbVirtualNetworkRule_disappears(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBVirtualNetworkRule_basic(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBVirtualNetworkRuleExists(data.ResourceName), - testCheckAzureRMMariaDBVirtualNetworkRuleDisappears(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleDisappears(data.ResourceName), ), ExpectNonEmptyPlan: true, }, @@ -103,7 +103,7 @@ func TestAccAzureRMMariaDBVirtualNetworkRule_disappears(t *testing.T) { }) } -func TestAccAzureRMMariaDBVirtualNetworkRule_multipleSubnets(t *testing.T) { +func TestAccAzureRMMariaDbVirtualNetworkRule_multipleSubnets(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mariadb_virtual_network_rule", "rule1") resourceName2 := "azurerm_mariadb_virtual_network_rule.rule2" resourceName3 := "azurerm_mariadb_virtual_network_rule.rule3" @@ -111,21 +111,21 @@ func TestAccAzureRMMariaDBVirtualNetworkRule_multipleSubnets(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMariaDBVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMariaDbVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMariaDBVirtualNetworkRule_multipleSubnets(data), + Config: testAccAzureRMMariaDbVirtualNetworkRule_multipleSubnets(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMariaDBVirtualNetworkRuleExists(data.ResourceName), - testCheckAzureRMMariaDBVirtualNetworkRuleExists(resourceName2), - testCheckAzureRMMariaDBVirtualNetworkRuleExists(resourceName3), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(resourceName2), + testCheckAzureRMMariaDbVirtualNetworkRuleExists(resourceName3), ), }, }, }) } -func testCheckAzureRMMariaDBVirtualNetworkRuleExists(resourceName string) resource.TestCheckFunc { +func testCheckAzureRMMariaDbVirtualNetworkRuleExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MariaDB.VirtualNetworkRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -152,7 +152,7 @@ func testCheckAzureRMMariaDBVirtualNetworkRuleExists(resourceName string) resour } } -func testCheckAzureRMMariaDBVirtualNetworkRuleDestroy(s *terraform.State) error { +func testCheckAzureRMMariaDbVirtualNetworkRuleDestroy(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MariaDB.VirtualNetworkRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -180,7 +180,7 @@ func testCheckAzureRMMariaDBVirtualNetworkRuleDestroy(s *terraform.State) error return nil } -func testCheckAzureRMMariaDBVirtualNetworkRuleDisappears(resourceName string) resource.TestCheckFunc { +func testCheckAzureRMMariaDbVirtualNetworkRuleDisappears(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MariaDB.VirtualNetworkRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -219,7 +219,7 @@ func testCheckAzureRMMariaDBVirtualNetworkRuleDisappears(resourceName string) re } } -func testAccAzureRMMariaDBVirtualNetworkRule_basic(data acceptance.TestData) string { +func testAccAzureRMMariaDbVirtualNetworkRule_basic(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -271,7 +271,7 @@ resource "azurerm_mariadb_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMariaDBVirtualNetworkRule_requiresImport(data acceptance.TestData) string { +func testAccAzureRMMariaDbVirtualNetworkRule_requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s @@ -281,10 +281,10 @@ resource "azurerm_mariadb_virtual_network_rule" "import" { server_name = azurerm_mariadb_virtual_network_rule.test.server_name subnet_id = azurerm_mariadb_virtual_network_rule.test.subnet_id } -`, testAccAzureRMMariaDBVirtualNetworkRule_basic(data)) +`, testAccAzureRMMariaDbVirtualNetworkRule_basic(data)) } -func testAccAzureRMMariaDBVirtualNetworkRule_subnetSwitchPre(data acceptance.TestData) string { +func testAccAzureRMMariaDbVirtualNetworkRule_subnetSwitchPre(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -344,7 +344,7 @@ resource "azurerm_mariadb_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMariaDBVirtualNetworkRule_subnetSwitchPost(data acceptance.TestData) string { +func testAccAzureRMMariaDbVirtualNetworkRule_subnetSwitchPost(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -404,7 +404,7 @@ resource "azurerm_mariadb_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMariaDBVirtualNetworkRule_multipleSubnets(data acceptance.TestData) string { +func testAccAzureRMMariaDbVirtualNetworkRule_multipleSubnets(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} diff --git a/azurerm/internal/services/mariadb/validate/mariadb.go b/azurerm/internal/services/mariadb/validate/mariadb.go new file mode 100644 index 0000000000000..a7aadae3947c6 --- /dev/null +++ b/azurerm/internal/services/mariadb/validate/mariadb.go @@ -0,0 +1,30 @@ +package validate + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mariadb/parse" +) + +func MariaDbServerServerID(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return warnings, errors + } + + if _, err := parse.MariaDbServerServerID(v); err != nil { + errors = append(errors, fmt.Errorf("cannot parse %q as a MariaDB Server resource id: %v", k, err)) + } + + return warnings, errors +} + +func MariaDbServerServerName(i interface{}, k string) (_ []string, errors []error) { + if m, regexErrs := validate.RegExHelper(i, k, `^[0-9a-z][-0-9a-z]{1,61}[0-9a-z]$`); !m { + return nil, append(regexErrs, fmt.Errorf("%q can contain only lowercase letters, numbers, and '-', but can't start or end with '-', and must be at least 3 characters and no more than 63 characters long.", k)) + } + + return nil, nil +} diff --git a/azurerm/internal/services/mariadb/validate/mariadb_test.go b/azurerm/internal/services/mariadb/validate/mariadb_test.go new file mode 100644 index 0000000000000..481d3320fafa4 --- /dev/null +++ b/azurerm/internal/services/mariadb/validate/mariadb_test.go @@ -0,0 +1,106 @@ +package validate + +import ( + "testing" +) + +func TestValidateMariaDbServerServerID(t *testing.T) { + testData := []struct { + input string + expected bool + }{ + { + // empty + input: "", + expected: false, + }, + { + // invalid + input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", + expected: false, + }, + { + // valid + input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMariaDB/servers/test-mariadb", + expected: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q..", v.input) + + _, errors := MariaDbServerServerID(v.input, "name") + actual := len(errors) == 0 + if v.expected != actual { + t.Fatalf("Expected %t but got %t", v.expected, actual) + } + } +} + +func TestValidateMariaDbServerServerName(t *testing.T) { + testData := []struct { + input string + expected bool + }{ + { + // empty + input: "", + expected: false, + }, + { + // basic example + input: "ab-c", + expected: true, + }, + { + // can't contain upper case letter + input: "AbcD", + expected: false, + }, + { + // can't start with a hyphen + input: "-abc", + expected: false, + }, + { + // can't contain underscore + input: "ab_c", + expected: false, + }, + { + // can't end with hyphen + input: "abc-", + expected: false, + }, + { + // can not be shorter than 3 characters + input: "ab", + expected: false, + }, + { + // can not be shorter than 3 characters (catching bad regex) + input: "a", + expected: false, + }, + { + // 63 chars + input: "abcdefghijklmnopqrstuvwxyzabcdefabcdefghijklmnopqrstuvwxyzabcde", + expected: true, + }, + { + // 64 chars + input: "abcdefghijklmnopqrstuvwxyzabcdefabcdefghijklmnopqrstuvwxyzabcdef", + expected: false, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q..", v.input) + + _, errors := MariaDbServerServerName(v.input, "name") + actual := len(errors) == 0 + if v.expected != actual { + t.Fatalf("Expected %t but got %t", v.expected, actual) + } + } +} diff --git a/website/docs/d/mariadb_server.html.markdown b/website/docs/d/mariadb_server.html.markdown index 6002c83c883ce..cd51308606e3e 100644 --- a/website/docs/d/mariadb_server.html.markdown +++ b/website/docs/d/mariadb_server.html.markdown @@ -47,8 +47,6 @@ The following attributes are exported: * `administrator_login` - The Administrator Login for the MariaDB Server. -* `administrator_login_password` - The password associated with the `administrator_login` for the MariaDB Server. - * `version` - The version of MariaDB being used. * `ssl_enforcement` - The SSL being enforced on connections. diff --git a/website/docs/r/mariadb_server.html.markdown b/website/docs/r/mariadb_server.html.markdown index 94baedaa439cd..dba9ef57002f4 100644 --- a/website/docs/r/mariadb_server.html.markdown +++ b/website/docs/r/mariadb_server.html.markdown @@ -13,29 +13,31 @@ Manages a MariaDB Server. ## Example Usage ```hcl +provider "azurerm" { + features {} +} + resource "azurerm_resource_group" "example" { - name = "api-rg-pro" + name = "example-resources" location = "West Europe" } resource "azurerm_mariadb_server" "example" { - name = "mariadb-server-1" + name = "example-mariadb-server" location = "${azurerm_resource_group.example.location}" resource_group_name = "${azurerm_resource_group.example.name}" - sku_name = "B_Gen5_2" - - storage_profile { - storage_mb = 5120 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - auto_grow = "Disabled" - } - administrator_login = "mariadbadmin" administrator_login_password = "H@Sh1CoR3!" - version = "10.2" - ssl_enforcement = "Enabled" + + sku_name = "B_Gen5_2" + storage_mb = 5120 + version = "10.2" + + auto_grow_enabled = true + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true } ``` @@ -51,31 +53,29 @@ The following arguments are supported: * `sku_name` - (Required) Specifies the SKU Name for this MariaDB Server. The name of the SKU, follows the `tier` + `family` + `cores` pattern (e.g. `B_Gen4_1`, `GP_Gen5_8`). For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mariadb/servers/create#sku). -* `storage_profile` - (Required) A `storage_profile` block as defined below. +* `version` - (Required) Specifies the version of MariaDB to use. Possible values are `10.2` and `10.3`. Changing this forces a new resource to be created. * `administrator_login` - (Required) The Administrator Login for the MariaDB Server. Changing this forces a new resource to be created. * `administrator_login_password` - (Required) The Password associated with the `administrator_login` for the MariaDB Server. -* `version` - (Required) Specifies the version of MariaDB to use. Possible values are `10.2` and `10.3`. Changing this forces a new resource to be created. - -* `ssl_enforcement` - (Required) Specifies if SSL should be enforced on connections. Possible values are `Enabled` and `Disabled`. +* `auto_grow_enabled` - (Optional) Enable/Disable auto-growing of the storage. Storage auto-grow prevents your server from running out of storage and becoming read-only. If storage auto grow is enabled, the storage automatically grows without impacting the workload. The default value if not explicitly specified is `true`. -* `tags` - (Optional) A mapping of tags to assign to the resource. +* `backup_retention_days` - (Optional) Backup retention days for the server, supported values are between `7` and `35` days. ---- +* `create_mode` - (Optional) The creation mode. Can be used to restore or replicate existing servers. Possible values are `Default`, `Replica`, `GeoRestore`, and `PointInTimeRestore`. Defaults to `Default`. -A `storage_profile` block supports the following: +* `creation_source_server_id` - (Optional) For creation modes other than `Default`, the source server ID to use. -* `storage_mb` - (Required) Max storage allowed for a server. Possible values are between `5120` MB (5GB) and `1024000`MB (1TB) for the Basic SKU and between `5120` MB (5GB) and `4096000` MB (4TB) for General Purpose/Memory Optimized SKUs. For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mariadb/servers/create#storageprofile). +* `geo_redundant_backup_enabled` - (Optional) Turn Geo-redundant server backups on/off. This allows you to choose between locally redundant or geo-redundant backup storage in the General Purpose and Memory Optimized tiers. When the backups are stored in geo-redundant backup storage, they are not only stored within the region in which your server is hosted, but are also replicated to a paired data center. This provides better protection and ability to restore your server in a different region in the event of a disaster. This is not supported for the Basic tier. -* `backup_retention_days` - (Optional) Backup retention days for the server, supported values are between `7` and `35` days. +* `restore_point_in_time` - (Optional) When `create_mode` is `PointInTimeRestore`, specifies the point in time to restore from `creation_source_server_id`. -* `geo_redundant_backup` - (Optional) Enable Geo-redundant or not for server backup. Valid values for this property are `Enabled` or `Disabled`. Changing this forces a new resource to be created. +* `ssl_enforcement_enabled` - (Required) Specifies if SSL should be enforced on connections. Possible values are `true` and `false`. --> **NOTE:** Geo Redundant Backups cannot be configured when using the `Basic` tier, and is only allowed during server create. +* `storage_mb` - (Required) Max storage allowed for a server. Possible values are between `5120` MB (5GB) and `1024000`MB (1TB) for the Basic SKU and between `5120` MB (5GB) and `4096000` MB (4TB) for General Purpose/Memory Optimized SKUs. For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mariadb/servers/create#storageprofile). -* `auto_grow` - (Optional) Defines whether autogrow is enabled or disabled for the storage. Valid values are `Enabled` or `Disabled`. +* `tags` - (Optional) A mapping of tags to assign to the resource. ## Attributes Reference From 05e303b59a9863a20331008ef4095d46973edb9e Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 20:45:49 -0700 Subject: [PATCH 083/104] update CHANGELOG.md to include #6865 --- CHANGELOG.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebd6a0eb5ad55..68671fcfe5f9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,10 @@ IMPROVEMENTS: * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] +* `azurerm_mysql_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6865] +* `azurerm_mysql_server` - support for the `public_network_access_enabled` property [GH-6865] +* `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6865] +* `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` [GH-6865] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] @@ -27,6 +31,7 @@ BUG FIXES: * Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] * Data Source: `azurerm_security_group` - fixing crash where id is nil [GH-6910] +* Data Source: `azurerm_mysql_server` - remove `administrator_login_password` property as it is not returned from the api [GH-6865] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_api_management` - only sending the `hostname_configuration` properties if they are not empty [GH-6850] * `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true [GH-6834] @@ -34,6 +39,7 @@ BUG FIXES: * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] * `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] * `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` [GH-6911] +* `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6865] ## 2.9.0 (May 07, 2020) @@ -140,7 +146,7 @@ IMPROVEMENTS: * `azurerm_postgres_server` - support for the `create_mode` property allowing replicas, point in time restores, and geo restores to be created ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) * `azurerm_postgres_server` - support for the `infrastructure_encryption_enabled`, `public_network_access_enabled`, and `ssl_minimal_tls_version_enforced` properties ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) * `azurerm_postgres_server` - all properties in the `storage_profile` block have been moved to the top level ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) -* `azurerm_postgres_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `backup_geo_redundant_enabled`, and `auto_grow` to `auto_grow_enabled` ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) +* `azurerm_postgres_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) * `azurerm_private_endpoint` - Add support for `tags` ([#6574](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6574)) * `azurerm_shared_image` - support `hyper_v_generation` property ([#6511](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6511)) * `azurerm_linux_virtual_machine_scale_set` - support for the `automatic_instance_repair` property ([#6346](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6346)) @@ -156,7 +162,7 @@ BUG FIXES: * `azurerm_iothub_dps` - fix crash when path isn't cased correctly ([#6570](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6570)) * `azurerm_linux_virtual_machine_scale_set` - fixes crash with `boot_diagnositics` ([#6569](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6569)) * `azurerm_policy_assignment` - allow scopes that don't start with `subscription/` ([#6576](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6576)) -* `azurerm_postgres_server` - the `storage_mb` is no optional when `auto_grow` is enabled ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) +* `azurerm_postgres_server` - the `storage_mb` property is now optional when `auto_grow` is enabled ([#6459](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6459)) * `azurerm_public_ip_prefix` - update `prefix_length` validation to accept all valid IPv4 address ranges ([#6589](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6589)) * `azurerm_route` - add validation to the `name` and `route_table_name`propeties ([#6055](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6055)) * `azurerm_virtual_network_gateway` - per api requirements, `public_ip_address_id` is required ([#6548](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6548)) From d207eaa1ec2cb521198a7a679072b8c67ba03bd7 Mon Sep 17 00:00:00 2001 From: Tom Bamford Date: Thu, 14 May 2020 04:46:53 +0100 Subject: [PATCH 084/104] mysql_server: New attributes, flatten `storage_profile` block (#6833) create_mode, creation_source_server_id, infrastructure_encryption_enabled, ssl_minimal_tls_version_enforced Support replicas and point-in-time restores Use booleans for toggle properties, renaming auto_grow -> auto_grow_enabled geo_redundant_backup -> geo_redundant_backup_enabled ssl_enforcement -> ssl_enforcement_enabled Remove redundant storage_profile block and move all properties within to top level Fixes: #4756 Related: #6459 --- azurerm/helpers/azure/mysql.go | 15 - .../mysql/mysql_configuration_resource.go | 3 +- .../services/mysql/mysql_database_resource.go | 3 +- .../mysql/mysql_firewall_rule_resource.go | 3 +- .../services/mysql/mysql_server_resource.go | 521 +++++++++++++----- .../mysql_virtual_network_rule_resource.go | 26 +- .../internal/services/mysql/parse/mysql.go | 33 ++ .../services/mysql/parse/mysql_test.go | 68 +++ .../internal/services/mysql/registration.go | 2 +- .../mysql/tests/mysql_server_resource_test.go | 378 ++++++++----- ...ysql_virtual_network_rule_resource_test.go | 80 +-- .../internal/services/mysql/validate/mysql.go | 30 + .../services/mysql/validate/mysql_test.go | 106 ++++ .../services/postgres/parse/postgres_test.go | 2 +- .../postgres/postgresql_server_resource.go | 8 +- website/docs/r/mysql_server.html.markdown | 60 +- 16 files changed, 960 insertions(+), 378 deletions(-) delete mode 100644 azurerm/helpers/azure/mysql.go create mode 100644 azurerm/internal/services/mysql/parse/mysql.go create mode 100644 azurerm/internal/services/mysql/parse/mysql_test.go create mode 100644 azurerm/internal/services/mysql/validate/mysql.go create mode 100644 azurerm/internal/services/mysql/validate/mysql_test.go diff --git a/azurerm/helpers/azure/mysql.go b/azurerm/helpers/azure/mysql.go deleted file mode 100644 index 7d133e333be38..0000000000000 --- a/azurerm/helpers/azure/mysql.go +++ /dev/null @@ -1,15 +0,0 @@ -package azure - -import ( - "fmt" - - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" -) - -func ValidateMySqlServerName(i interface{}, k string) (_ []string, errors []error) { - if m, regexErrs := validate.RegExHelper(i, k, `^[0-9a-z]([-0-9a-z]{0,61}[0-9a-z])?$`); !m { - return nil, append(regexErrs, fmt.Errorf("%q can contain only lowercase letters, numbers, and '-', but can't start or end with '-' or have more than 63 characters.", k)) - } - - return nil, nil -} diff --git a/azurerm/internal/services/mysql/mysql_configuration_resource.go b/azurerm/internal/services/mysql/mysql_configuration_resource.go index ea1cd6e80ad2c..e7c1485a3b007 100644 --- a/azurerm/internal/services/mysql/mysql_configuration_resource.go +++ b/azurerm/internal/services/mysql/mysql_configuration_resource.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -43,7 +44,7 @@ func resourceArmMySQLConfiguration() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateMySqlServerName, + ValidateFunc: validate.MysqlServerServerName, }, "value": { diff --git a/azurerm/internal/services/mysql/mysql_database_resource.go b/azurerm/internal/services/mysql/mysql_database_resource.go index f1f96e5ad6b8e..1c7b8398cd555 100644 --- a/azurerm/internal/services/mysql/mysql_database_resource.go +++ b/azurerm/internal/services/mysql/mysql_database_resource.go @@ -12,6 +12,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -46,7 +47,7 @@ func resourceArmMySqlDatabase() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateMySqlServerName, + ValidateFunc: validate.MysqlServerServerName, }, "charset": { diff --git a/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go b/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go index cc21cf9c0f48f..b2435ced5e46e 100644 --- a/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go +++ b/azurerm/internal/services/mysql/mysql_firewall_rule_resource.go @@ -11,6 +11,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -46,7 +47,7 @@ func resourceArmMySqlFirewallRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateMySqlServerName, + ValidateFunc: validate.MysqlServerServerName, }, "start_ip_address": { diff --git a/azurerm/internal/services/mysql/mysql_server_resource.go b/azurerm/internal/services/mysql/mysql_server_resource.go index 54bab650e0f68..7cc3d8364401f 100644 --- a/azurerm/internal/services/mysql/mysql_server_resource.go +++ b/azurerm/internal/services/mysql/mysql_server_resource.go @@ -8,6 +8,8 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/mysql/mgmt/2017-12-01/mysql" + "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" @@ -15,6 +17,8 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" @@ -28,7 +32,18 @@ func resourceArmMySqlServer() *schema.Resource { Delete: resourceArmMySqlServerDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + if _, err := parse.MysqlServerServerID(d.Id()); err != nil { + return []*schema.ResourceData{d}, err + } + + d.Set("create_mode", "Default") + if v, ok := d.GetOk("create_mode"); ok && v.(string) != "" { + d.Set("create_mode", v) + } + + return []*schema.ResourceData{d}, nil + }, }, Timeouts: &schema.ResourceTimeout{ @@ -43,13 +58,89 @@ func resourceArmMySqlServer() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: azure.ValidateMySqlServerName, + ValidateFunc: validate.MysqlServerServerName, + }, + + "administrator_login": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + + "administrator_login_password": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + }, + + "auto_grow_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, // TODO: remove in 3.0 and default to true + ConflictsWith: []string{"storage_profile.0.auto_grow"}, + }, + + "backup_retention_days": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ConflictsWith: []string{"storage_profile.0.backup_retention_days"}, + ValidateFunc: validation.IntBetween(7, 35), + }, + + "create_mode": { + Type: schema.TypeString, + Optional: true, + Default: string(mysql.CreateModeDefault), + ValidateFunc: validation.StringInSlice([]string{ + string(mysql.CreateModeDefault), + string(mysql.CreateModeGeoRestore), + string(mysql.CreateModePointInTimeRestore), + string(mysql.CreateModeReplica), + }, false), + }, + + "creation_source_server_id": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validate.MysqlServerServerID, + }, + + "fqdn": { + Type: schema.TypeString, + Computed: true, + }, + + "geo_redundant_backup_enabled": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + ConflictsWith: []string{"storage_profile.0.geo_redundant_backup"}, + }, + + "infrastructure_encryption_enabled": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, }, "location": azure.SchemaLocation(), + "public_network_access_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + "resource_group_name": azure.SchemaResourceGroupName(), + "restore_point_in_time": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.IsRFC3339Time, + }, + "sku_name": { Type: schema.TypeString, Required: true, @@ -77,100 +168,129 @@ func resourceArmMySqlServer() *schema.Resource { }, false), }, - "administrator_login": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + "ssl_enforcement": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Deprecated: "this has been moved to the boolean attribute `ssl_enforcement_enabled` and will be removed in version 3.0 of the provider.", + ExactlyOneOf: []string{"ssl_enforcement", "ssl_enforcement_enabled"}, + ValidateFunc: validation.StringInSlice([]string{ + string(mysql.SslEnforcementEnumDisabled), + string(mysql.SslEnforcementEnumEnabled), + }, true), + DiffSuppressFunc: suppress.CaseDifference, }, - "administrator_login_password": { - Type: schema.TypeString, - Required: true, - Sensitive: true, + "ssl_enforcement_enabled": { + Type: schema.TypeBool, + Optional: true, // required in 3.0 + Computed: true, // remove computed in 3.0 + ExactlyOneOf: []string{"ssl_enforcement", "ssl_enforcement_enabled"}, }, - "version": { + "ssl_minimal_tls_version_enforced": { Type: schema.TypeString, - Required: true, + Optional: true, + Default: string(mysql.TLSEnforcementDisabled), ValidateFunc: validation.StringInSlice([]string{ - string(mysql.FiveFullStopSix), - string(mysql.FiveFullStopSeven), - string(mysql.EightFullStopZero), - }, true), - DiffSuppressFunc: suppress.CaseDifference, - ForceNew: true, + string(mysql.TLSEnforcementDisabled), + string(mysql.TLS10), + string(mysql.TLS11), + string(mysql.TLS12), + }, false), + }, + + "storage_mb": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ExactlyOneOf: []string{"storage_profile.0.storage_mb"}, + ValidateFunc: validation.All( + validation.IntBetween(5120, 4194304), + validation.IntDivisibleBy(1024), + ), }, "storage_profile": { - Type: schema.TypeList, - Required: true, - MaxItems: 1, + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Deprecated: "all storage_profile properties have been moved to the top level. This block will be removed in version 3.0 of the provider.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "storage_mb": { - Type: schema.TypeInt, - Required: true, - ValidateFunc: validation.All( - validation.IntBetween(5120, 4194304), - validation.IntDivisibleBy(1024), - ), + "auto_grow": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"auto_grow_enabled"}, + Deprecated: "this has been moved to the top level boolean attribute `auto_grow_enabled` and will be removed in version 3.0 of the provider.", + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(mysql.StorageAutogrowEnabled), + string(mysql.StorageAutogrowDisabled), + }, false), }, "backup_retention_days": { - Type: schema.TypeInt, - Optional: true, - ValidateFunc: validation.IntBetween(7, 35), + Type: schema.TypeInt, + Optional: true, + Computed: true, + ConflictsWith: []string{"backup_retention_days"}, + Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.", + ValidateFunc: validation.IntBetween(7, 35), }, "geo_redundant_backup": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"geo_redundant_backup_enabled"}, + Deprecated: "this has been moved to the top level boolean attribute `geo_redundant_backup_enabled` and will be removed in version 3.0 of the provider.", + DiffSuppressFunc: suppress.CaseDifference, ValidateFunc: validation.StringInSlice([]string{ "Enabled", "Disabled", }, true), - DiffSuppressFunc: suppress.CaseDifference, }, - "auto_grow": { - Type: schema.TypeString, - Optional: true, - Default: string(mysql.StorageAutogrowEnabled), - ValidateFunc: validation.StringInSlice([]string{ - string(mysql.StorageAutogrowEnabled), - string(mysql.StorageAutogrowDisabled), - }, false), + "storage_mb": { + Type: schema.TypeInt, + Optional: true, + ConflictsWith: []string{"storage_mb"}, + Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.", + ValidateFunc: validation.All( + validation.IntBetween(5120, 4194304), + validation.IntDivisibleBy(1024), + ), }, }, }, }, - "ssl_enforcement": { + "tags": tags.Schema(), + + "version": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(mysql.SslEnforcementEnumDisabled), - string(mysql.SslEnforcementEnumEnabled), + string(mysql.FiveFullStopSix), + string(mysql.FiveFullStopSeven), + string(mysql.EightFullStopZero), }, true), DiffSuppressFunc: suppress.CaseDifference, + ForceNew: true, }, - - "public_network_access_enabled": { - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - - "fqdn": { - Type: schema.TypeString, - Computed: true, - }, - - "tags": tags.Schema(), }, CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { tier, _ := diff.GetOk("sku_name") - storageMB, _ := diff.GetOk("storage_profile.0.storage_mb") - if strings.HasPrefix(tier.(string), "B_") && storageMB.(int) > 1048576 { + var storageMB int + if v, ok := diff.GetOk("storage_mb"); ok { + storageMB = v.(int) + } else if v, ok := diff.GetOk("storage_profile.0.storage_mb"); ok { + storageMB = v.(int) + } + + if strings.HasPrefix(tier.(string), "B_") && storageMB > 1048576 { return fmt.Errorf("basic pricing tier only supports upto 1,048,576 MB (1TB) of storage") } @@ -190,16 +310,11 @@ func resourceArmMySqlServerCreate(d *schema.ResourceData, meta interface{}) erro location := azure.NormalizeLocation(d.Get("location").(string)) resourceGroup := d.Get("resource_group_name").(string) - publicAccess := mysql.PublicNetworkAccessEnumEnabled - if v := d.Get("public_network_access_enabled").(bool); !v { - publicAccess = mysql.PublicNetworkAccessEnumDisabled - } - if features.ShouldResourcesBeImported() && d.IsNewResource() { existing, err := client.Get(ctx, resourceGroup, name) if err != nil { if !utils.ResponseWasNotFound(existing.Response) { - return fmt.Errorf("Error checking for presence of existing MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("checking for presence of existing MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) } } @@ -208,42 +323,131 @@ func resourceArmMySqlServerCreate(d *schema.ResourceData, meta interface{}) erro } } + mode := mysql.CreateMode(d.Get("create_mode").(string)) + tlsMin := mysql.MinimalTLSVersionEnum(d.Get("ssl_minimal_tls_version_enforced").(string)) + source := d.Get("creation_source_server_id").(string) + version := mysql.ServerVersion(d.Get("version").(string)) + sku, err := expandServerSkuName(d.Get("sku_name").(string)) if err != nil { - return fmt.Errorf("error expanding sku_name for MySQL Server %q (Resource Group %q): %v", name, resourceGroup, err) + return fmt.Errorf("expanding sku_name for MySQL Server %q (Resource Group %q): %v", name, resourceGroup, err) } - properties := mysql.ServerForCreate{ - Location: &location, - Properties: &mysql.ServerPropertiesForDefaultCreate{ - AdministratorLogin: utils.String(d.Get("administrator_login").(string)), - AdministratorLoginPassword: utils.String(d.Get("administrator_login_password").(string)), - Version: mysql.ServerVersion(d.Get("version").(string)), - SslEnforcement: mysql.SslEnforcementEnum(d.Get("ssl_enforcement").(string)), - StorageProfile: expandMySQLStorageProfile(d), - CreateMode: mysql.CreateMode("Default"), + infraEncrypt := mysql.InfrastructureEncryptionEnabled + if v := d.Get("infrastructure_encryption_enabled"); !v.(bool) { + infraEncrypt = mysql.InfrastructureEncryptionDisabled + } + + publicAccess := mysql.PublicNetworkAccessEnumEnabled + if v := d.Get("public_network_access_enabled"); !v.(bool) { + publicAccess = mysql.PublicNetworkAccessEnumDisabled + } + + ssl := mysql.SslEnforcementEnumEnabled + if v, ok := d.GetOk("ssl_enforcement"); ok && strings.EqualFold(v.(string), string(mysql.SslEnforcementEnumDisabled)) { + ssl = mysql.SslEnforcementEnumDisabled + } + if v, ok := d.GetOkExists("ssl_enforcement_enabled"); ok && !v.(bool) { + ssl = mysql.SslEnforcementEnumDisabled + } + + storage := expandMySQLStorageProfile(d) + + var props mysql.BasicServerPropertiesForCreate + switch mode { + case mysql.CreateModeDefault: + admin := d.Get("administrator_login").(string) + pass := d.Get("administrator_login_password").(string) + + if admin == "" { + return fmt.Errorf("`administrator_login` must not be empty when `create_mode` is `default`") + } + if pass == "" { + return fmt.Errorf("`administrator_login_password` must not be empty when `create_mode` is `default`") + } + + if _, ok := d.GetOk("restore_point_in_time"); ok { + return fmt.Errorf("`restore_point_in_time` cannot be set when `create_mode` is `default`") + } + + // check admin + props = &mysql.ServerPropertiesForDefaultCreate{ + AdministratorLogin: &admin, + AdministratorLoginPassword: &pass, + CreateMode: mode, + InfrastructureEncryption: infraEncrypt, PublicNetworkAccess: publicAccess, - }, - Sku: sku, - Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + MinimalTLSVersion: tlsMin, + SslEnforcement: ssl, + StorageProfile: storage, + Version: version, + } + case mysql.CreateModePointInTimeRestore: + v, ok := d.GetOk("restore_point_in_time") + if !ok || v.(string) == "" { + return fmt.Errorf("restore_point_in_time must be set when create_mode is PointInTimeRestore") + } + time, _ := time.Parse(time.RFC3339, v.(string)) // should be validated by the schema + + props = &mysql.ServerPropertiesForRestore{ + CreateMode: mode, + SourceServerID: &source, + RestorePointInTime: &date.Time{ + Time: time, + }, + InfrastructureEncryption: infraEncrypt, + PublicNetworkAccess: publicAccess, + MinimalTLSVersion: tlsMin, + SslEnforcement: ssl, + StorageProfile: storage, + Version: version, + } + case mysql.CreateModeGeoRestore: + props = &mysql.ServerPropertiesForGeoRestore{ + CreateMode: mode, + SourceServerID: &source, + InfrastructureEncryption: infraEncrypt, + PublicNetworkAccess: publicAccess, + MinimalTLSVersion: tlsMin, + SslEnforcement: ssl, + StorageProfile: storage, + Version: version, + } + case mysql.CreateModeReplica: + props = &mysql.ServerPropertiesForReplica{ + CreateMode: mode, + SourceServerID: &source, + InfrastructureEncryption: infraEncrypt, + PublicNetworkAccess: publicAccess, + MinimalTLSVersion: tlsMin, + SslEnforcement: ssl, + Version: version, + } + } + + server := mysql.ServerForCreate{ + Location: &location, + Properties: props, + Sku: sku, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - future, err := client.Create(ctx, resourceGroup, name, properties) + future, err := client.Create(ctx, resourceGroup, name, server) if err != nil { - return fmt.Errorf("Error creating MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("creating MySQL Server %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 MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("waiting for creation of MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) } read, err := client.Get(ctx, resourceGroup, name) if err != nil { - return fmt.Errorf("Error retrieving MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("retrieving MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read MySQL Server %q (Resource Group %q) ID", name, resourceGroup) + return fmt.Errorf("cannot read MySQL Server %q (Resource Group %q) ID", name, resourceGroup) } d.SetId(*read.ID) @@ -258,12 +462,14 @@ func resourceArmMySqlServerUpdate(d *schema.ResourceData, meta interface{}) erro log.Printf("[INFO] preparing arguments for AzureRM MySQL Server update.") - name := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) + id, err := parse.MysqlServerServerID(d.Id()) + if err != nil { + return fmt.Errorf("parsing MySQL Server ID : %v", err) + } sku, err := expandServerSkuName(d.Get("sku_name").(string)) if err != nil { - return fmt.Errorf("error expanding sku_name for MySQL Server %q (Resource Group %q): %v", name, resourceGroup, err) + return fmt.Errorf("expanding sku_name for MySQL Server %q (Resource Group %q): %v", id.Name, id.ResourceGroup, err) } publicAccess := mysql.PublicNetworkAccessEnumEnabled @@ -271,34 +477,44 @@ func resourceArmMySqlServerUpdate(d *schema.ResourceData, meta interface{}) erro publicAccess = mysql.PublicNetworkAccessEnumDisabled } + ssl := mysql.SslEnforcementEnumEnabled + if v := d.Get("ssl_enforcement"); strings.EqualFold(v.(string), string(mysql.SslEnforcementEnumDisabled)) { + ssl = mysql.SslEnforcementEnumDisabled + } + if v := d.Get("ssl_enforcement_enabled").(bool); !v { + ssl = mysql.SslEnforcementEnumDisabled + } + + storageProfile := expandMySQLStorageProfile(d) + properties := mysql.ServerUpdateParameters{ ServerUpdateParametersProperties: &mysql.ServerUpdateParametersProperties{ - StorageProfile: expandMySQLStorageProfile(d), AdministratorLoginPassword: utils.String(d.Get("administrator_login_password").(string)), - Version: mysql.ServerVersion(d.Get("version").(string)), - SslEnforcement: mysql.SslEnforcementEnum(d.Get("ssl_enforcement").(string)), PublicNetworkAccess: publicAccess, + SslEnforcement: ssl, + StorageProfile: storageProfile, + Version: mysql.ServerVersion(d.Get("version").(string)), }, Sku: sku, Tags: tags.Expand(d.Get("tags").(map[string]interface{})), } - future, err := client.Update(ctx, resourceGroup, name, properties) + future, err := client.Update(ctx, id.ResourceGroup, id.Name, properties) if err != nil { - return fmt.Errorf("Error updating MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("updating MySQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for MySQL Server %q (Resource Group %q) to finish updating: %+v", name, resourceGroup, err) + return fmt.Errorf("waiting for MySQL Server %q (Resource Group %q) to finish updating: %+v", id.Name, id.ResourceGroup, err) } - read, err := client.Get(ctx, resourceGroup, name) + read, err := client.Get(ctx, id.ResourceGroup, id.Name) if err != nil { - return fmt.Errorf("Error retrieving MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("retrieving MySQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read MySQL Server %q (Resource Group %q) ID", name, resourceGroup) + return fmt.Errorf("cannot read MySQL Server %q (Resource Group %q) ID", id.Name, id.ResourceGroup) } d.SetId(*read.ID) @@ -311,25 +527,24 @@ func resourceArmMySqlServerRead(d *schema.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.MysqlServerServerID(d.Id()) if err != nil { - return err + return fmt.Errorf("parsing MySQL Server ID : %v", err) } - resourceGroup := id.ResourceGroup - name := id.Path["servers"] - resp, err := client.Get(ctx, resourceGroup, name) + resp, err := client.Get(ctx, id.ResourceGroup, id.Name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[WARN] MySQL Server %q was not found (Resource Group %q)", id.Name, id.ResourceGroup) d.SetId("") return nil } - return fmt.Errorf("Error making Read request on Azure MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + return fmt.Errorf("making Read request on Azure MySQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } d.Set("name", resp.Name) - d.Set("resource_group_name", resourceGroup) + d.Set("resource_group_name", id.ResourceGroup) if location := resp.Location; location != nil { d.Set("location", azure.NormalizeLocation(*location)) @@ -339,17 +554,29 @@ func resourceArmMySqlServerRead(d *schema.ResourceData, meta interface{}) error d.Set("sku_name", sku.Name) } - d.Set("administrator_login", resp.AdministratorLogin) - d.Set("version", string(resp.Version)) - d.Set("ssl_enforcement", string(resp.SslEnforcement)) - d.Set("public_network_access_enabled", resp.PublicNetworkAccess != mysql.PublicNetworkAccessEnumDisabled) + if props := resp.ServerProperties; props != nil { + d.Set("administrator_login", props.AdministratorLogin) + d.Set("infrastructure_encryption_enabled", props.InfrastructureEncryption == mysql.InfrastructureEncryptionEnabled) + d.Set("public_network_access_enabled", props.PublicNetworkAccess == mysql.PublicNetworkAccessEnumEnabled) + d.Set("ssl_enforcement", string(props.SslEnforcement)) + d.Set("ssl_enforcement_enabled", props.SslEnforcement == mysql.SslEnforcementEnumEnabled) + d.Set("ssl_minimal_tls_version_enforced", props.MinimalTLSVersion) + d.Set("version", string(props.Version)) + + if err := d.Set("storage_profile", flattenMySQLStorageProfile(resp.StorageProfile)); err != nil { + return fmt.Errorf("setting `storage_profile`: %+v", err) + } - if err := d.Set("storage_profile", flattenMySQLStorageProfile(resp.StorageProfile)); err != nil { - return fmt.Errorf("Error setting `storage_profile`: %+v", err) - } + if storage := props.StorageProfile; storage != nil { + d.Set("auto_grow_enabled", storage.StorageAutogrow == mysql.StorageAutogrowEnabled) + d.Set("backup_retention_days", storage.BackupRetentionDays) + d.Set("geo_redundant_backup_enabled", storage.GeoRedundantBackup == mysql.Enabled) + d.Set("storage_mb", storage.StorageMB) + } - // Computed - d.Set("fqdn", resp.FullyQualifiedDomainName) + // Computed + d.Set("fqdn", props.FullyQualifiedDomainName) + } return tags.FlattenAndSet(d, resp.Tags) } @@ -359,20 +586,24 @@ func resourceArmMySqlServerDelete(d *schema.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + id, err := parse.MysqlServerServerID(d.Id()) if err != nil { - return err + return fmt.Errorf("parsing MySQL Server ID : %v", err) } - resourceGroup := id.ResourceGroup - name := id.Path["servers"] - future, err := client.Delete(ctx, resourceGroup, name) + future, err := client.Delete(ctx, id.ResourceGroup, id.Name) if err != nil { - return fmt.Errorf("Error deleting MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + if response.WasNotFound(future.Response()) { + return nil + } + return fmt.Errorf("deleting MySQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { - return fmt.Errorf("Error waiting for deletion of MySQL Server %q (Resource Group %q): %+v", name, resourceGroup, err) + if response.WasNotFound(future.Response()) { + return nil + } + return fmt.Errorf("waiting for deletion of MySQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } return nil @@ -410,36 +641,58 @@ func expandServerSkuName(skuName string) (*mysql.Sku, error) { } func expandMySQLStorageProfile(d *schema.ResourceData) *mysql.StorageProfile { - storageprofiles := d.Get("storage_profile").([]interface{}) - storageprofile := storageprofiles[0].(map[string]interface{}) + storage := mysql.StorageProfile{} + if v, ok := d.GetOk("storage_profile"); ok { + storageprofile := v.([]interface{})[0].(map[string]interface{}) + + storage.BackupRetentionDays = utils.Int32(int32(storageprofile["backup_retention_days"].(int))) + storage.GeoRedundantBackup = mysql.GeoRedundantBackup(storageprofile["geo_redundant_backup"].(string)) + storage.StorageAutogrow = mysql.StorageAutogrow(storageprofile["auto_grow"].(string)) + storage.StorageMB = utils.Int32(int32(storageprofile["storage_mb"].(int))) + } + + // now override whatever we may have from the block with the top level properties + if v, ok := d.GetOk("auto_grow_enabled"); ok { + storage.StorageAutogrow = mysql.StorageAutogrowDisabled + if v.(bool) { + storage.StorageAutogrow = mysql.StorageAutogrowEnabled + } + } + + if v, ok := d.GetOk("backup_retention_days"); ok { + storage.BackupRetentionDays = utils.Int32(int32(v.(int))) + } - backupRetentionDays := storageprofile["backup_retention_days"].(int) - geoRedundantBackup := storageprofile["geo_redundant_backup"].(string) - storageMB := storageprofile["storage_mb"].(int) - autoGrow := storageprofile["auto_grow"].(string) + if v, ok := d.GetOk("geo_redundant_backup_enabled"); ok { + storage.GeoRedundantBackup = mysql.Disabled + if v.(bool) { + storage.GeoRedundantBackup = mysql.Enabled + } + } - return &mysql.StorageProfile{ - BackupRetentionDays: utils.Int32(int32(backupRetentionDays)), - GeoRedundantBackup: mysql.GeoRedundantBackup(geoRedundantBackup), - StorageMB: utils.Int32(int32(storageMB)), - StorageAutogrow: mysql.StorageAutogrow(autoGrow), + if v, ok := d.GetOk("storage_mb"); ok { + storage.StorageMB = utils.Int32(int32(v.(int))) } + + return &storage } func flattenMySQLStorageProfile(resp *mysql.StorageProfile) []interface{} { values := map[string]interface{}{} - if storageMB := resp.StorageMB; storageMB != nil { - values["storage_mb"] = *storageMB - } + values["auto_grow"] = string(resp.StorageAutogrow) + values["backup_retention_days"] = nil if backupRetentionDays := resp.BackupRetentionDays; backupRetentionDays != nil { values["backup_retention_days"] = *backupRetentionDays } values["geo_redundant_backup"] = string(resp.GeoRedundantBackup) - values["auto_grow"] = string(resp.StorageAutogrow) + values["storage_mb"] = nil + if storageMB := resp.StorageMB; storageMB != nil { + values["storage_mb"] = *storageMB + } return []interface{}{values} } diff --git a/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go b/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go index 21a520afca60e..7399af29bc5e3 100644 --- a/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go +++ b/azurerm/internal/services/mysql/mysql_virtual_network_rule_resource.go @@ -10,22 +10,22 @@ import ( "github.com/hashicorp/go-azure-helpers/response" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" + azValidate "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func resourceArmMySqlVirtualNetworkRule() *schema.Resource { +func resourceArmMySSQLVirtualNetworkRule() *schema.Resource { return &schema.Resource{ - Create: resourceArmMySqlVirtualNetworkRuleCreateUpdate, - Read: resourceArmMySqlVirtualNetworkRuleRead, - Update: resourceArmMySqlVirtualNetworkRuleCreateUpdate, - Delete: resourceArmMySqlVirtualNetworkRuleDelete, + Create: resourceArmMySSQLVirtualNetworkRuleCreateUpdate, + Read: resourceArmMySSQLVirtualNetworkRuleRead, + Update: resourceArmMySSQLVirtualNetworkRuleCreateUpdate, + Delete: resourceArmMySSQLVirtualNetworkRuleDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, @@ -42,7 +42,7 @@ func resourceArmMySqlVirtualNetworkRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validate.VirtualNetworkRuleName, + ValidateFunc: azValidate.VirtualNetworkRuleName, }, "resource_group_name": azure.SchemaResourceGroupName(), @@ -51,7 +51,7 @@ func resourceArmMySqlVirtualNetworkRule() *schema.Resource { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: validation.StringIsNotEmpty, + ValidateFunc: validate.MysqlServerServerName, }, "subnet_id": { @@ -63,7 +63,7 @@ func resourceArmMySqlVirtualNetworkRule() *schema.Resource { } } -func resourceArmMySqlVirtualNetworkRuleCreateUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceArmMySSQLVirtualNetworkRuleCreateUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).MySQL.VirtualNetworkRulesClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -123,10 +123,10 @@ func resourceArmMySqlVirtualNetworkRuleCreateUpdate(d *schema.ResourceData, meta d.SetId(*resp.ID) - return resourceArmMySqlVirtualNetworkRuleRead(d, meta) + return resourceArmMySSQLVirtualNetworkRuleRead(d, meta) } -func resourceArmMySqlVirtualNetworkRuleRead(d *schema.ResourceData, meta interface{}) error { +func resourceArmMySSQLVirtualNetworkRuleRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).MySQL.VirtualNetworkRulesClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -162,7 +162,7 @@ func resourceArmMySqlVirtualNetworkRuleRead(d *schema.ResourceData, meta interfa return nil } -func resourceArmMySqlVirtualNetworkRuleDelete(d *schema.ResourceData, meta interface{}) error { +func resourceArmMySSQLVirtualNetworkRuleDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).MySQL.VirtualNetworkRulesClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() diff --git a/azurerm/internal/services/mysql/parse/mysql.go b/azurerm/internal/services/mysql/parse/mysql.go new file mode 100644 index 0000000000000..a8a370133682d --- /dev/null +++ b/azurerm/internal/services/mysql/parse/mysql.go @@ -0,0 +1,33 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type MysqlServerServerId struct { + ResourceGroup string + Name string +} + +func MysqlServerServerID(input string) (*MysqlServerServerId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse MySQL Server ID %q: %+v", input, err) + } + + server := MysqlServerServerId{ + ResourceGroup: id.ResourceGroup, + } + + if server.Name, err = id.PopSegment("servers"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &server, nil +} diff --git a/azurerm/internal/services/mysql/parse/mysql_test.go b/azurerm/internal/services/mysql/parse/mysql_test.go new file mode 100644 index 0000000000000..c3ccf38972ea8 --- /dev/null +++ b/azurerm/internal/services/mysql/parse/mysql_test.go @@ -0,0 +1,68 @@ +package parse + +import ( + "testing" +) + +func TestValidateMysqlServerServerID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *MysqlServerServerId + }{ + { + Name: "Empty resource ID", + Input: "", + Expected: nil, + }, + { + Name: "No resourceGroups segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No resource group name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource group", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/", + Expected: nil, + }, + { + Name: "Missing server name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/", + Expected: nil, + }, + { + Name: "Valid", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/test-mysql", + Expected: &MysqlServerServerId{ + Name: "test-mysql", + ResourceGroup: "test-rg", + }, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := MysqlServerServerID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/mysql/registration.go b/azurerm/internal/services/mysql/registration.go index cf8e58ead01b0..01c7dc617d45c 100644 --- a/azurerm/internal/services/mysql/registration.go +++ b/azurerm/internal/services/mysql/registration.go @@ -30,5 +30,5 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { "azurerm_mysql_database": resourceArmMySqlDatabase(), "azurerm_mysql_firewall_rule": resourceArmMySqlFirewallRule(), "azurerm_mysql_server": resourceArmMySqlServer(), - "azurerm_mysql_virtual_network_rule": resourceArmMySqlVirtualNetworkRule()} + "azurerm_mysql_virtual_network_rule": resourceArmMySSQLVirtualNetworkRule()} } diff --git a/azurerm/internal/services/mysql/tests/mysql_server_resource_test.go b/azurerm/internal/services/mysql/tests/mysql_server_resource_test.go index 833e6aa6ea719..645cd296f6a73 100644 --- a/azurerm/internal/services/mysql/tests/mysql_server_resource_test.go +++ b/azurerm/internal/services/mysql/tests/mysql_server_resource_test.go @@ -3,6 +3,7 @@ package tests import ( "fmt" "testing" + "time" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/terraform" @@ -20,7 +21,7 @@ func TestAccAzureRMMySQLServer_basicFiveSix(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicFiveSix(data), + Config: testAccAzureRMMySQLServer_basic(data, "5.6"), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), ), @@ -30,7 +31,7 @@ func TestAccAzureRMMySQLServer_basicFiveSix(t *testing.T) { }) } -func TestAccAzureRMMySQLServer_disablePublicNetworkAccess(t *testing.T) { +func TestAccAzureRMMySQLServer_basicFiveSixDeprecated(t *testing.T) { // remove in v3.0 data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") resource.ParallelTest(t, resource.TestCase{ @@ -39,7 +40,7 @@ func TestAccAzureRMMySQLServer_disablePublicNetworkAccess(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_disablePublicNetworkAccess(data), + Config: testAccAzureRMMySQLServer_basicDeprecated(data, "5.6"), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), ), @@ -49,7 +50,7 @@ func TestAccAzureRMMySQLServer_disablePublicNetworkAccess(t *testing.T) { }) } -func TestAccAzureRMMySQLServer_requiresImport(t *testing.T) { +func TestAccAzureRMMySQLServer_basicFiveSeven(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") resource.ParallelTest(t, resource.TestCase{ @@ -58,21 +59,38 @@ func TestAccAzureRMMySQLServer_requiresImport(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicFiveSevenUpdated(data), + Config: testAccAzureRMMySQLServer_basic(data, "5.7"), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + }, + }) +} + +func TestAccAzureRMMySQLServer_basicEightZero(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerDestroy, + Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_requiresImport(data), - ExpectError: acceptance.RequiresImportError("azurerm_mysql_server"), + Config: testAccAzureRMMySQLServer_basic(data, "8.0"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } -func TestAccAzureRMMySQLServer_basicFiveSeven(t *testing.T) { +func TestAccAzureRMMySQLServer_autogrowOnly(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + mysqlVersion := "5.7" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -80,7 +98,14 @@ func TestAccAzureRMMySQLServer_basicFiveSeven(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicFiveSeven(data), + Config: testAccAzureRMMySQLServer_autogrow(data, mysqlVersion), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMySQLServer_basic(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), ), @@ -90,8 +115,47 @@ func TestAccAzureRMMySQLServer_basicFiveSeven(t *testing.T) { }) } -func TestAccAzureRMMySQLServer_basicEightZero(t *testing.T) { +func TestAccAzureRMMySQLServer_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMySQLServer_basic(data, "5.7"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMMySQLServer_requiresImport), + }, + }) +} + +func TestAccAzureRMMySQLServer_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMySQLServer_complete(data, "8.0"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + }, + }) +} + +func TestAccAzureRMMySQLServer_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + mysqlVersion := "8.0" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -99,7 +163,21 @@ func TestAccAzureRMMySQLServer_basicEightZero(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicEightZero(data), + Config: testAccAzureRMMySQLServer_basic(data, mysqlVersion), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMySQLServer_complete(data, mysqlVersion), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMySQLServer_basic(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), ), @@ -109,8 +187,9 @@ func TestAccAzureRMMySQLServer_basicEightZero(t *testing.T) { }) } -func TestAccAzureRMMySqlServer_memoryOptimized(t *testing.T) { +func TestAccAzureRMMySQLServer_completeDeprecatedMigrate(t *testing.T) { // remove in v3.0 data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + mysqlVersion := "5.6" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -118,17 +197,26 @@ func TestAccAzureRMMySqlServer_memoryOptimized(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_memoryOptimizedGeoRedundant(data), + Config: testAccAzureRMMySQLServer_completeDeprecated(data, mysqlVersion), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMySQLServer_complete(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), ), - }, data.ImportStep("administrator_login_password"), // not returned as sensitive + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } -func TestAccAzureRMMySQLServer_basicFiveSevenUpdated(t *testing.T) { +func TestAccAzureRMMySQLServer_updateDeprecated(t *testing.T) { // remove in v3.0 data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + mysqlVersion := "5.6" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -136,23 +224,23 @@ func TestAccAzureRMMySQLServer_basicFiveSevenUpdated(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicFiveSeven(data), + Config: testAccAzureRMMySQLServer_basicDeprecated(data, mysqlVersion), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), // not returned as sensitive + { + Config: testAccAzureRMMySQLServer_completeDeprecated(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku_name", "GP_Gen5_2"), - resource.TestCheckResourceAttr(data.ResourceName, "version", "5.7"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "51200"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive { - Config: testAccAzureRMMySQLServer_basicFiveSevenUpdated(data), + Config: testAccAzureRMMySQLServer_basicDeprecated(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku_name", "GP_Gen5_4"), - resource.TestCheckResourceAttr(data.ResourceName, "version", "5.7"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "640000"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, data.ImportStep("administrator_login_password"), // not returned as sensitive @@ -169,29 +257,26 @@ func TestAccAzureRMMySQLServer_updateSKU(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicEightZero(data), + Config: testAccAzureRMMySQLServer_sku(data, "GP_Gen5_2"), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku_name", "GP_Gen5_2"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "51200"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive { - Config: testAccAzureRMMySQLServer_basicFiveSevenUpdated(data), + Config: testAccAzureRMMySQLServer_sku(data, "MO_Gen5_16"), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "sku_name", "GP_Gen5_4"), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.storage_mb", "4194304"), - resource.TestCheckResourceAttr(data.ResourceName, "administrator_login", "acctestun"), ), }, + data.ImportStep("administrator_login_password"), // not returned as sensitive }, }) } -func TestAccAzureRMMySQLServer_storageAutogrow(t *testing.T) { +func TestAccAzureRMMySQLServer_createReplica(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + mysqlVersion := "8.0" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, @@ -199,24 +284,53 @@ func TestAccAzureRMMySQLServer_storageAutogrow(t *testing.T) { CheckDestroy: testCheckAzureRMMySQLServerDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySQLServer_basicFiveSeven(data), + Config: testAccAzureRMMySQLServer_basic(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.auto_grow", "Enabled"), ), }, + data.ImportStep("administrator_login_password"), { - Config: testAccAzureRMMySQLServer_autogrow(data), + Config: testAccAzureRMMySQLServer_createReplica(data, mysqlVersion), Check: resource.ComposeTestCheckFunc( testCheckAzureRMMySQLServerExists(data.ResourceName), - resource.TestCheckResourceAttr(data.ResourceName, "storage_profile.0.auto_grow", "Disabled"), + testCheckAzureRMMySQLServerExists("azurerm_mysql_server.replica"), ), }, + data.ImportStep("administrator_login_password"), }, }) } -// +func TestAccAzureRMMySQLServer_createPointInTimeRestore(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mysql_server", "test") + restoreTime := time.Now().Add(11 * time.Minute) + mysqlVersion := "8.0" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMySQLServerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMySQLServer_basic(data, mysqlVersion), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), + { + PreConfig: func() { time.Sleep(restoreTime.Sub(time.Now().Add(-7 * time.Minute))) }, + Config: testAccAzureRMMySQLServer_createPointInTimeRestore(data, mysqlVersion, restoreTime.Format(time.RFC3339)), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMySQLServerExists(data.ResourceName), + testCheckAzureRMMySQLServerExists("azurerm_mysql_server.restore"), + ), + }, + data.ImportStep("administrator_login_password"), + }, + }) +} func testCheckAzureRMMySQLServerExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -273,7 +387,7 @@ func testCheckAzureRMMySQLServerDestroy(s *terraform.State) error { return nil } -func testAccAzureRMMySQLServer_basicFiveSix(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_basic(data acceptance.TestData, version string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -285,27 +399,20 @@ resource "azurerm_resource_group" "test" { } resource "azurerm_mysql_server" "test" { - name = "acctestmysqlsvr-%d" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - - sku_name = "GP_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } - + name = "acctestmysqlsvr-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku_name = "GP_Gen5_2" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "5.6" - ssl_enforcement = "Enabled" + ssl_enforcement_enabled = true + storage_mb = 51200 + version = "%s" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMySQLServer_disablePublicNetworkAccess(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_basicDeprecated(data acceptance.TestData, version string) string { // remove in v3.0 return fmt.Sprintf(` provider "azurerm" { features {} @@ -324,21 +431,18 @@ resource "azurerm_mysql_server" "test" { sku_name = "GP_Gen5_2" storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" + storage_mb = 51200 } - administrator_login = "acctestun" - administrator_login_password = "H@Sh1CoR3!" - version = "5.6" - ssl_enforcement = "Enabled" - public_network_access_enabled = false + administrator_login = "acctestun" + administrator_login_password = "H@Sh1CoR3!" + version = "%s" + ssl_enforcement = "Enabled" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMySQLServer_basicFiveSeven(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_complete(data acceptance.TestData, version string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -350,27 +454,24 @@ resource "azurerm_resource_group" "test" { } resource "azurerm_mysql_server" "test" { - name = "acctestmysqlsvr-%d" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name - - sku_name = "GP_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } - + name = "acctestmysqlsvr-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku_name = "GP_Gen5_2" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "5.7" - ssl_enforcement = "Enabled" + auto_grow_enabled = true + backup_retention_days = 7 + create_mode = "Default" + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 + version = "%s" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMySQLServer_basicEightZero(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_completeDeprecated(data acceptance.TestData, version string) string { // remove in v3.0 return fmt.Sprintf(` provider "azurerm" { features {} @@ -392,14 +493,15 @@ resource "azurerm_mysql_server" "test" { storage_mb = 51200 backup_retention_days = 7 geo_redundant_backup = "Disabled" + auto_grow = "Enabled" } administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "8.0" + version = "%s" ssl_enforcement = "Enabled" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } func testAccAzureRMMySQLServer_requiresImport(data acceptance.TestData) string { @@ -410,24 +512,20 @@ resource "azurerm_mysql_server" "import" { name = azurerm_mysql_server.test.name location = azurerm_mysql_server.test.location resource_group_name = azurerm_mysql_server.test.resource_group_name - - sku_name = "GP_Gen5_2" - - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } + sku_name = "GP_Gen5_2" + version = "5.7" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "5.7" - ssl_enforcement = "Enabled" + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, testAccAzureRMMySQLServer_basicFiveSevenUpdated(data)) +`, testAccAzureRMMySQLServer_basic(data, "5.7")) } -func testAccAzureRMMySQLServer_basicFiveSevenUpdated(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_sku(data acceptance.TestData, sku string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -442,24 +540,18 @@ resource "azurerm_mysql_server" "test" { name = "acctestmysqlsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + sku_name = "%s" + version = "5.7" - sku_name = "GP_Gen5_4" - - storage_profile { - storage_mb = 640000 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } - + storage_mb = 4194304 administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "5.7" - ssl_enforcement = "Enabled" + ssl_enforcement_enabled = true } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, sku) } -func testAccAzureRMMySQLServer_memoryOptimizedGeoRedundant(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_autogrow(data acceptance.TestData, version string) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -474,52 +566,54 @@ resource "azurerm_mysql_server" "test" { name = "acctestmysqlsvr-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name - - sku_name = "MO_Gen5_16" - - storage_profile { - storage_mb = 4194304 - backup_retention_days = 7 - geo_redundant_backup = "Enabled" - } + sku_name = "GP_Gen5_2" + version = "%s" administrator_login = "acctestun" administrator_login_password = "H@Sh1CoR3!" - version = "5.7" - ssl_enforcement = "Enabled" + auto_grow_enabled = true + backup_retention_days = 7 + geo_redundant_backup_enabled = false + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) } -func testAccAzureRMMySQLServer_autogrow(data acceptance.TestData) string { +func testAccAzureRMMySQLServer_createReplica(data acceptance.TestData, version string) string { return fmt.Sprintf(` -provider "azurerm" { - features {} -} - -resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" -} +%s -resource "azurerm_mysql_server" "test" { - name = "acctestmysqlsvr-%d" +resource "azurerm_mysql_server" "replica" { + name = "acctestmysqlsvr-%d-replica" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + sku_name = "GP_Gen5_2" + version = "%s" - sku_name = "GP_Gen5_2" + create_mode = "Replica" + creation_source_server_id = azurerm_mysql_server.test.id + ssl_enforcement_enabled = true +} +`, testAccAzureRMMySQLServer_basic(data, version), data.RandomInteger, version) +} - storage_profile { - storage_mb = 51200 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - auto_grow = "Disabled" - } +func testAccAzureRMMySQLServer_createPointInTimeRestore(data acceptance.TestData, version, restoreTime string) string { + return fmt.Sprintf(` +%s - administrator_login = "acctestun" - administrator_login_password = "H@Sh1CoR3!" - version = "5.7" - ssl_enforcement = "Enabled" +resource "azurerm_mysql_server" "restore" { + name = "acctestmysqlsvr-%d-restore" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku_name = "GP_Gen5_2" + version = "%s" + + create_mode = "PointInTimeRestore" + creation_source_server_id = azurerm_mysql_server.test.id + restore_point_in_time = "%s" + ssl_enforcement_enabled = true + storage_mb = 51200 } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, testAccAzureRMMySQLServer_basic(data, version), data.RandomInteger, version, restoreTime) } diff --git a/azurerm/internal/services/mysql/tests/mysql_virtual_network_rule_resource_test.go b/azurerm/internal/services/mysql/tests/mysql_virtual_network_rule_resource_test.go index 67824d6c074db..797aea463362f 100644 --- a/azurerm/internal/services/mysql/tests/mysql_virtual_network_rule_resource_test.go +++ b/azurerm/internal/services/mysql/tests/mysql_virtual_network_rule_resource_test.go @@ -13,66 +13,66 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func TestAccAzureRMMySqlVirtualNetworkRule_basic(t *testing.T) { +func TestAccAzureRMMySSQLVirtualNetworkRule_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMySqlVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMySSQLVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySqlVirtualNetworkRule_basic(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), ), }, }, }) } -func TestAccAzureRMMySqlVirtualNetworkRule_badsubnet(t *testing.T) { +func TestAccAzureRMMySSQLVirtualNetworkRule_badsubnet(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMySqlVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMySSQLVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySqlVirtualNetworkRule_badsubnet(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_badsubnet(data), /* Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), ),*/ }, }, }) } -func TestAccAzureRMMySqlVirtualNetworkRule_requiresImport(t *testing.T) { +func TestAccAzureRMMySSQLVirtualNetworkRule_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMySqlVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMySSQLVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySqlVirtualNetworkRule_basic(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), ), }, { - Config: testAccAzureRMMySqlVirtualNetworkRule_requiresImport(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_requiresImport(data), ExpectError: acceptance.RequiresImportError("azurerm_mysql_virtual_network_rule"), }, }, }) } -func TestAccAzureRMMySqlVirtualNetworkRule_switchSubnets(t *testing.T) { +func TestAccAzureRMMySSQLVirtualNetworkRule_switchSubnets(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_virtual_network_rule", "test") // Create regex strings that will ensure that one subnet name exists, but not the other @@ -82,19 +82,19 @@ func TestAccAzureRMMySqlVirtualNetworkRule_switchSubnets(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMySqlVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMySSQLVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySqlVirtualNetworkRule_subnetSwitchPre(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_subnetSwitchPre(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), resource.TestMatchResourceAttr(data.ResourceName, "subnet_id", preConfigRegex), ), }, { - Config: testAccAzureRMMySqlVirtualNetworkRule_subnetSwitchPost(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_subnetSwitchPost(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), resource.TestMatchResourceAttr(data.ResourceName, "subnet_id", postConfigRegex), ), }, @@ -102,19 +102,19 @@ func TestAccAzureRMMySqlVirtualNetworkRule_switchSubnets(t *testing.T) { }) } -func TestAccAzureRMMySqlVirtualNetworkRule_disappears(t *testing.T) { +func TestAccAzureRMMySSQLVirtualNetworkRule_disappears(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_virtual_network_rule", "test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMySqlVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMySSQLVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySqlVirtualNetworkRule_basic(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_basic(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), - testCheckAzureRMMySqlVirtualNetworkRuleDisappears(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleDisappears(data.ResourceName), ), ExpectNonEmptyPlan: true, }, @@ -122,7 +122,7 @@ func TestAccAzureRMMySqlVirtualNetworkRule_disappears(t *testing.T) { }) } -func TestAccAzureRMMySqlVirtualNetworkRule_multipleSubnets(t *testing.T) { +func TestAccAzureRMMySSQLVirtualNetworkRule_multipleSubnets(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_mysql_virtual_network_rule", "rule1") resourceName2 := "azurerm_mysql_virtual_network_rule.rule2" @@ -131,21 +131,21 @@ func TestAccAzureRMMySqlVirtualNetworkRule_multipleSubnets(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { acceptance.PreCheck(t) }, Providers: acceptance.SupportedProviders, - CheckDestroy: testCheckAzureRMMySqlVirtualNetworkRuleDestroy, + CheckDestroy: testCheckAzureRMMySSQLVirtualNetworkRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMMySqlVirtualNetworkRule_multipleSubnets(data), + Config: testAccAzureRMMySSQLVirtualNetworkRule_multipleSubnets(data), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMMySqlVirtualNetworkRuleExists(data.ResourceName), - testCheckAzureRMMySqlVirtualNetworkRuleExists(resourceName2), - testCheckAzureRMMySqlVirtualNetworkRuleExists(resourceName3), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(data.ResourceName), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(resourceName2), + testCheckAzureRMMySSQLVirtualNetworkRuleExists(resourceName3), ), }, }, }) } -func testCheckAzureRMMySqlVirtualNetworkRuleExists(resourceName string) resource.TestCheckFunc { +func testCheckAzureRMMySSQLVirtualNetworkRuleExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MySQL.VirtualNetworkRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -172,7 +172,7 @@ func testCheckAzureRMMySqlVirtualNetworkRuleExists(resourceName string) resource } } -func testCheckAzureRMMySqlVirtualNetworkRuleDestroy(s *terraform.State) error { +func testCheckAzureRMMySSQLVirtualNetworkRuleDestroy(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MySQL.VirtualNetworkRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -200,7 +200,7 @@ func testCheckAzureRMMySqlVirtualNetworkRuleDestroy(s *terraform.State) error { return nil } -func testCheckAzureRMMySqlVirtualNetworkRuleDisappears(resourceName string) resource.TestCheckFunc { +func testCheckAzureRMMySSQLVirtualNetworkRuleDisappears(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { client := acceptance.AzureProvider.Meta().(*clients.Client).MySQL.VirtualNetworkRulesClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -239,7 +239,7 @@ func testCheckAzureRMMySqlVirtualNetworkRuleDisappears(resourceName string) reso } } -func testAccAzureRMMySqlVirtualNetworkRule_basic(data acceptance.TestData) string { +func testAccAzureRMMySSQLVirtualNetworkRule_basic(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -292,7 +292,7 @@ resource "azurerm_mysql_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMySqlVirtualNetworkRule_badsubnet(data acceptance.TestData) string { +func testAccAzureRMMySSQLVirtualNetworkRule_badsubnet(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -345,7 +345,7 @@ resource "azurerm_mysql_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMySqlVirtualNetworkRule_requiresImport(data acceptance.TestData) string { +func testAccAzureRMMySSQLVirtualNetworkRule_requiresImport(data acceptance.TestData) string { return fmt.Sprintf(` %s @@ -355,10 +355,10 @@ resource "azurerm_mysql_virtual_network_rule" "import" { server_name = azurerm_mysql_virtual_network_rule.test.server_name subnet_id = azurerm_mysql_virtual_network_rule.test.subnet_id } -`, testAccAzureRMMySqlVirtualNetworkRule_basic(data)) +`, testAccAzureRMMySSQLVirtualNetworkRule_basic(data)) } -func testAccAzureRMMySqlVirtualNetworkRule_subnetSwitchPre(data acceptance.TestData) string { +func testAccAzureRMMySSQLVirtualNetworkRule_subnetSwitchPre(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -419,7 +419,7 @@ resource "azurerm_mysql_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMySqlVirtualNetworkRule_subnetSwitchPost(data acceptance.TestData) string { +func testAccAzureRMMySSQLVirtualNetworkRule_subnetSwitchPost(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -480,7 +480,7 @@ resource "azurerm_mysql_virtual_network_rule" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger, data.RandomInteger) } -func testAccAzureRMMySqlVirtualNetworkRule_multipleSubnets(data acceptance.TestData) string { +func testAccAzureRMMySSQLVirtualNetworkRule_multipleSubnets(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} diff --git a/azurerm/internal/services/mysql/validate/mysql.go b/azurerm/internal/services/mysql/validate/mysql.go new file mode 100644 index 0000000000000..e5abee8309ba8 --- /dev/null +++ b/azurerm/internal/services/mysql/validate/mysql.go @@ -0,0 +1,30 @@ +package validate + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mysql/parse" +) + +func MysqlServerServerID(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return warnings, errors + } + + if _, err := parse.MysqlServerServerID(v); err != nil { + errors = append(errors, fmt.Errorf("Can not parse %q as a MySQL Server resource id: %v", k, err)) + } + + return warnings, errors +} + +func MysqlServerServerName(i interface{}, k string) (_ []string, errors []error) { + if m, regexErrs := validate.RegExHelper(i, k, `^[0-9a-z][-0-9a-z]{1,61}[0-9a-z]$`); !m { + return nil, append(regexErrs, fmt.Errorf("%q can contain only lowercase letters, numbers, and '-', but can't start or end with '-', and must be at least 3 characters and no more than 63 characters long.", k)) + } + + return nil, nil +} diff --git a/azurerm/internal/services/mysql/validate/mysql_test.go b/azurerm/internal/services/mysql/validate/mysql_test.go new file mode 100644 index 0000000000000..3e919164fb376 --- /dev/null +++ b/azurerm/internal/services/mysql/validate/mysql_test.go @@ -0,0 +1,106 @@ +package validate + +import ( + "testing" +) + +func TestValidateMysqlServerServerID(t *testing.T) { + testData := []struct { + input string + expected bool + }{ + { + // empty + input: "", + expected: false, + }, + { + // invalid + input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", + expected: false, + }, + { + // valid + input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.DBforMySQL/servers/test-mysql", + expected: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q..", v.input) + + _, errors := MysqlServerServerID(v.input, "name") + actual := len(errors) == 0 + if v.expected != actual { + t.Fatalf("Expected %t but got %t", v.expected, actual) + } + } +} + +func TestValidateMysqlServerServerName(t *testing.T) { + testData := []struct { + input string + expected bool + }{ + { + // empty + input: "", + expected: false, + }, + { + // basic example + input: "ab-c", + expected: true, + }, + { + // can't contain upper case letter + input: "AbcD", + expected: false, + }, + { + // can't start with a hyphen + input: "-abc", + expected: false, + }, + { + // can't contain underscore + input: "ab_c", + expected: false, + }, + { + // can't end with hyphen + input: "abc-", + expected: false, + }, + { + // can not be shorter than 3 characters + input: "ab", + expected: false, + }, + { + // can not be shorter than 3 characters (catching bad regex) + input: "a", + expected: false, + }, + { + // 63 chars + input: "abcdefghijklmnopqrstuvwxyzabcdefabcdefghijklmnopqrstuvwxyzabcde", + expected: true, + }, + { + // 64 chars + input: "abcdefghijklmnopqrstuvwxyzabcdefabcdefghijklmnopqrstuvwxyzabcdef", + expected: false, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q..", v.input) + + _, errors := MysqlServerServerName(v.input, "name") + actual := len(errors) == 0 + if v.expected != actual { + t.Fatalf("Expected %t but got %t", v.expected, actual) + } + } +} diff --git a/azurerm/internal/services/postgres/parse/postgres_test.go b/azurerm/internal/services/postgres/parse/postgres_test.go index b3b2dcc1fb6b8..ae2dfa439205c 100644 --- a/azurerm/internal/services/postgres/parse/postgres_test.go +++ b/azurerm/internal/services/postgres/parse/postgres_test.go @@ -32,7 +32,7 @@ func TestAnalysisServicesServerId(t *testing.T) { }, { Name: "Missing Servers Value", - Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Web/servers/", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.DBforPostgreSQL/servers/", Expected: nil, }, { diff --git a/azurerm/internal/services/postgres/postgresql_server_resource.go b/azurerm/internal/services/postgres/postgresql_server_resource.go index 7f8cc2c45208a..f9d1eeb3e24f7 100644 --- a/azurerm/internal/services/postgres/postgresql_server_resource.go +++ b/azurerm/internal/services/postgres/postgresql_server_resource.go @@ -531,15 +531,15 @@ func resourceArmPostgreSQLServerRead(d *schema.ResourceData, meta interface{}) e d.Set("name", resp.Name) d.Set("resource_group_name", id.ResourceGroup) + if location := resp.Location; location != nil { + d.Set("location", azure.NormalizeLocation(*location)) + } + if sku := resp.Sku; sku != nil { d.Set("sku_name", sku.Name) } if props := resp.ServerProperties; props != nil { - if location := resp.Location; location != nil { - d.Set("location", azure.NormalizeLocation(*location)) - } - d.Set("administrator_login", props.AdministratorLogin) d.Set("ssl_enforcement", string(props.SslEnforcement)) d.Set("ssl_minimal_tls_version_enforced", props.MinimalTLSVersion) diff --git a/website/docs/r/mysql_server.html.markdown b/website/docs/r/mysql_server.html.markdown index 725ee963c2c62..c205512f5a124 100644 --- a/website/docs/r/mysql_server.html.markdown +++ b/website/docs/r/mysql_server.html.markdown @@ -14,28 +14,34 @@ Manages a MySQL Server. ## Example Usage ```hcl +provider "azurerm" { + features {} +} + resource "azurerm_resource_group" "example" { - name = "api-rg-pro" + name = "example-resources" location = "West Europe" } resource "azurerm_mysql_server" "example" { - name = "mysql-server-1" + name = "example-mysqlserver" location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name - sku_name = "B_Gen5_2" - - storage_profile { - storage_mb = 5120 - backup_retention_days = 7 - geo_redundant_backup = "Disabled" - } - administrator_login = "mysqladminun" administrator_login_password = "H@Sh1CoR3!" - version = "5.7" - ssl_enforcement = "Enabled" + + sku_name = "B_Gen5_2" + storage_mb = 5120 + version = "5.7" + + auto_grow_enabled = true + backup_retention_days = 7 + geo_redundant_backup_enabled = true + infrastructure_encryption_enabled = true + public_network_access_enabled = false + ssl_enforcement_enabled = true + ssl_minimal_tls_version_enforced = "TLS1_2" } ``` @@ -51,31 +57,35 @@ The following arguments are supported: * `sku_name` - (Required) Specifies the SKU Name for this MySQL Server. The name of the SKU, follows the `tier` + `family` + `cores` pattern (e.g. `B_Gen4_1`, `GP_Gen5_8`). For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mysql/servers/create#sku). -* `storage_profile` - (Required) A `storage_profile` block as defined below. +* `version` - (Required) Specifies the version of MySQL to use. Valid values are `5.6`, `5.7`, and `8.0`. Changing this forces a new resource to be created. + +* `administrator_login` - (Optional) The Administrator Login for the MySQL Server. Required when `create_mode` is `Default`. Changing this forces a new resource to be created. -* `administrator_login` - (Required) The Administrator Login for the MySQL Server. Changing this forces a new resource to be created. +* `administrator_login_password` - (Optional) The Password associated with the `administrator_login` for the MySQL Server. Required when `create_mode` is `Default`. -* `administrator_login_password` - (Required) The Password associated with the `administrator_login` for the MySQL Server. +* `auto_grow_enabled` - (Optional) Enable/Disable auto-growing of the storage. Storage auto-grow prevents your server from running out of storage and becoming read-only. If storage auto grow is enabled, the storage automatically grows without impacting the workload. The default value if not explicitly specified is `true`. -* `version` - (Required) Specifies the version of MySQL to use. Valid values are `5.6`, `5.7`, and `8.0`. Changing this forces a new resource to be created. +* `backup_retention_days` - (Optional) Backup retention days for the server, supported values are between `7` and `35` days. -* `ssl_enforcement` - (Required) Specifies if SSL should be enforced on connections. Possible values are `Enabled` and `Disabled`. +* `create_mode` - (Optional) The creation mode. Can be used to restore or replicate existing servers. Possible values are `Default`, `Replica`, `GeoRestore`, and `PointInTimeRestore`. Defaults to `Default`. -* `public_network_access_enabled` - (Optional) Should public network access be allowed for this server? Defaults to `true`. +* `creation_source_server_id` - (Optional) For creation modes other than `Default`, the source server ID to use. -* `tags` - (Optional) A mapping of tags to assign to the resource. +* `geo_redundant_backup_enabled` - (Optional) Turn Geo-redundant server backups on/off. This allows you to choose between locally redundant or geo-redundant backup storage in the General Purpose and Memory Optimized tiers. When the backups are stored in geo-redundant backup storage, they are not only stored within the region in which your server is hosted, but are also replicated to a paired data center. This provides better protection and ability to restore your server in a different region in the event of a disaster. This is not supported for the Basic tier. ---- +* `infrastructure_encryption_enabled` - (Optional) Whether or not infrastructure is encrypted for this server. Defaults to `false`. Changing this forces a new resource to be created. -`storage_profile` supports the following: +* `public_network_access_enabled` - (Optional) Whether or not public network access is allowed for this server. Defaults to `true`. -* `storage_mb` - (Required) Max storage allowed for a server. Possible values are between `5120` MB(5GB) and `1048576` MB(1TB) for the Basic SKU and between `5120` MB(5GB) and `4194304` MB(4TB) for General Purpose/Memory Optimized SKUs. For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mysql/servers/create#StorageProfile). +* `restore_point_in_time` - (Optional) When `create_mode` is `PointInTimeRestore`, specifies the point in time to restore from `creation_source_server_id`. -* `backup_retention_days` - (Optional) Backup retention days for the server, supported values are between `7` and `35` days. +* `ssl_enforcement_enabled` - (Required) Specifies if SSL should be enforced on connections. Possible values are `true` and `false`. + +* `ssl_minimal_tls_version_enforced` - (Optional) The minimum TLS version to support on the sever. Possible values are `TLSEnforcementDisabled`, `TLS1_0`, `TLS1_1`, and `TLS1_2`. Defaults to `TLSEnforcementDisabled`. -* `geo_redundant_backup` - (Optional) Enable Geo-redundant or not for server backup. Valid values for this property are `Enabled` or `Disabled`, not supported for the `basic` tier. +* `storage_mb` - (Required) Max storage allowed for a server. Possible values are between `5120` MB(5GB) and `1048576` MB(1TB) for the Basic SKU and between `5120` MB(5GB) and `4194304` MB(4TB) for General Purpose/Memory Optimized SKUs. For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/mysql/servers/create#StorageProfile). -* `auto_grow` - (Optional) Defines whether autogrow is enabled or disabled for the storage. Valid values are `Enabled` or `Disabled`. +* `tags` - (Optional) A mapping of tags to assign to the resource. ## Attributes Reference From 213688c0c43e754de4cb175fb426dd4c2337ad22 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 20:48:53 -0700 Subject: [PATCH 085/104] update CHANGELOG.md to include #6833 --- CHANGELOG.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68671fcfe5f9e..6a43c451d72b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,10 +20,14 @@ IMPROVEMENTS: * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] -* `azurerm_mysql_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6865] -* `azurerm_mysql_server` - support for the `public_network_access_enabled` property [GH-6865] -* `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6865] -* `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` [GH-6865] +* `azurerm_mariadb_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6865] +* `azurerm_mariadb_server` - support for the `public_network_access_enabled` property [GH-6865] +* `azurerm_mariadb_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6865] +* `azurerm_mariadb_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` +* `azurerm_mysql_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6833] +* `azurerm_mysql_server` - support for the `public_network_access_enabled` property [GH-6833] +* `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6833] +* `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` [GH-6833] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] @@ -39,7 +43,8 @@ BUG FIXES: * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] * `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] * `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` [GH-6911] -* `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6865] +* `azurerm_mariadb_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6865] +* `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6833] ## 2.9.0 (May 07, 2020) From 0a3962dfb2bfea11a4d1614703772f6c76216953 Mon Sep 17 00:00:00 2001 From: kt Date: Wed, 13 May 2020 21:13:06 -0700 Subject: [PATCH 086/104] add documentation for the source_image_reference block --- website/docs/r/linux_virtual_machine.html.markdown | 12 ++++++++++++ .../r/linux_virtual_machine_scale_set.html.markdown | 12 ++++++++++++ website/docs/r/windows_virtual_machine.html.markdown | 12 ++++++++++++ .../windows_virtual_machine_scale_set.html.markdown | 12 ++++++++++++ 4 files changed, 48 insertions(+) diff --git a/website/docs/r/linux_virtual_machine.html.markdown b/website/docs/r/linux_virtual_machine.html.markdown index 6f090d0df2b5b..ccbfd86e027e7 100644 --- a/website/docs/r/linux_virtual_machine.html.markdown +++ b/website/docs/r/linux_virtual_machine.html.markdown @@ -262,6 +262,18 @@ A `secret` block supports the following: * `key_vault_id` - (Required) The ID of the Key Vault from which all Secrets should be sourced. +--- + +`source_image_reference` supports the following: + +* `publisher` - (Optional) Specifies the publisher of the image used to create the virtual machines. + +* `offer` - (Optional) Specifies the offer of the image used to create the virtual machines. + +* `sku` - (Optional) Specifies the SKU of the image used to create the virtual machines. + +* `version` - (Optional) Specifies the version of the image used to create the virtual machines. + ## Attributes Reference In addition to all arguments above, the following attributes are exported: diff --git a/website/docs/r/linux_virtual_machine_scale_set.html.markdown b/website/docs/r/linux_virtual_machine_scale_set.html.markdown index 0e0d5bacf3af6..0447f66acc3b8 100644 --- a/website/docs/r/linux_virtual_machine_scale_set.html.markdown +++ b/website/docs/r/linux_virtual_machine_scale_set.html.markdown @@ -410,6 +410,18 @@ A `terminate_notification` block supports the following: ~> For more information about the terminate notification, please [refer to this doc](https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-terminate-notification). +--- + +`source_image_reference` supports the following: + +* `publisher` - (Optional) Specifies the publisher of the image used to create the virtual machines. + +* `offer` - (Optional) Specifies the offer of the image used to create the virtual machines. + +* `sku` - (Optional) Specifies the SKU of the image used to create the virtual machines. + +* `version` - (Optional) Specifies the version of the image used to create the virtual machines. + ## Attributes Reference In addition to all arguments above, the following attributes are exported: diff --git a/website/docs/r/windows_virtual_machine.html.markdown b/website/docs/r/windows_virtual_machine.html.markdown index 4628fce707635..1692577037b0e 100644 --- a/website/docs/r/windows_virtual_machine.html.markdown +++ b/website/docs/r/windows_virtual_machine.html.markdown @@ -289,6 +289,18 @@ An `identity` block exports the following: * `tenant_id` - The ID of the Tenant the System Managed Service Principal is assigned in. +--- + +`source_image_reference` supports the following: + +* `publisher` - (Optional) Specifies the publisher of the image used to create the virtual machines. + +* `offer` - (Optional) Specifies the offer of the image used to create the virtual machines. + +* `sku` - (Optional) Specifies the SKU of the image used to create the virtual machines. + +* `version` - (Optional) Specifies the version of the image used to create the virtual machines. + ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: diff --git a/website/docs/r/windows_virtual_machine_scale_set.html.markdown b/website/docs/r/windows_virtual_machine_scale_set.html.markdown index 654f0f89e0048..8a1e0cf949f65 100644 --- a/website/docs/r/windows_virtual_machine_scale_set.html.markdown +++ b/website/docs/r/windows_virtual_machine_scale_set.html.markdown @@ -412,6 +412,18 @@ A `winrm_listener` block supports the following: * `protocol` - (Required) The Protocol of the WinRM Listener. Possible values are `Http` and `Https`. +--- + +`source_image_reference` supports the following: + +* `publisher` - (Optional) Specifies the publisher of the image used to create the virtual machines. + +* `offer` - (Optional) Specifies the offer of the image used to create the virtual machines. + +* `sku` - (Optional) Specifies the SKU of the image used to create the virtual machines. + +* `version` - (Optional) Specifies the version of the image used to create the virtual machines. + ## Attributes Reference In addition to all arguments above, the following attributes are exported: From 40a653362e0b90f2b673890ce7fcb1d42d581cdf Mon Sep 17 00:00:00 2001 From: WS <20408400+WodansSon@users.noreply.github.com> Date: Wed, 13 May 2020 22:54:08 -0700 Subject: [PATCH 087/104] Fixes #6741 * Add support for frontdoor_id computed attribute * Updated name of new attribute --- azurerm/internal/services/frontdoor/frontdoor_resource.go | 6 ++++++ website/docs/r/frontdoor.html.markdown | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/azurerm/internal/services/frontdoor/frontdoor_resource.go b/azurerm/internal/services/frontdoor/frontdoor_resource.go index 50bca0d686ea1..5d3b63bdd4589 100644 --- a/azurerm/internal/services/frontdoor/frontdoor_resource.go +++ b/azurerm/internal/services/frontdoor/frontdoor_resource.go @@ -51,6 +51,11 @@ func resourceArmFrontDoor() *schema.Resource { Computed: true, }, + "header_frontdoor_id": { + Type: schema.TypeString, + Computed: true, + }, + "friendly_name": { Type: schema.TypeString, Optional: true, @@ -705,6 +710,7 @@ func resourceArmFrontDoorRead(d *schema.ResourceData, meta interface{}) error { } d.Set("cname", properties.Cname) + d.Set("header_frontdoor_id", properties.FrontdoorID) d.Set("load_balancer_enabled", properties.EnabledState == frontdoor.EnabledStateEnabled) d.Set("friendly_name", properties.FriendlyName) diff --git a/website/docs/r/frontdoor.html.markdown b/website/docs/r/frontdoor.html.markdown index 99bf7a1a1105b..8043625a7c7ce 100644 --- a/website/docs/r/frontdoor.html.markdown +++ b/website/docs/r/frontdoor.html.markdown @@ -294,12 +294,12 @@ The following attributes are exported: * `cname` - The host that each frontendEndpoint must CNAME to. +* `header_frontdoor_id` - The unique ID of the Front Door which is embedded into the incoming headers `X-Azure-FDID` attribute and maybe used to filter traffic sent by the Front Door to your backend. + * `id` - The ID of the FrontDoor. ## Timeouts - - The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: * `create` - (Defaults to 6 hours) Used when creating the FrontDoor. From 09236364805c457f30be12eff0754be84c9e1184 Mon Sep 17 00:00:00 2001 From: WS <20408400+WodansSon@users.noreply.github.com> Date: Wed, 13 May 2020 22:55:33 -0700 Subject: [PATCH 088/104] updating to include #6916 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a43c451d72b8..3a163d1687f8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ IMPROVEMENTS: * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] +* `azurerm_frontdoor` - Expose the `header_frontdoor_id` attribute [GH-6916] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] * `azurerm_mariadb_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6865] * `azurerm_mariadb_server` - support for the `public_network_access_enabled` property [GH-6865] From 02c1024814114cca96c7f142474c2c9cddaf356d Mon Sep 17 00:00:00 2001 From: Tobias Schug <4014687+HappyTobi@users.noreply.github.com> Date: Thu, 14 May 2020 11:01:25 +0200 Subject: [PATCH 089/104] fixes #5758 * Add resource migration for Storage Account * Update docs to show new behavior * Update config name to indicate it's a prepare step Co-authored-by: Jeffrey Cline <20408400+WodansSon@users.noreply.github.com> --- .../storage/resource_arm_storage_account.go | 27 ++++++- .../resource_arm_storage_account_test.go | 81 +++++++++++++++++++ website/docs/r/storage_account.html.markdown | 2 + 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/azurerm/internal/services/storage/resource_arm_storage_account.go b/azurerm/internal/services/storage/resource_arm_storage_account.go index 0256f22d33cd0..c52522ac52fec 100644 --- a/azurerm/internal/services/storage/resource_arm_storage_account.go +++ b/azurerm/internal/services/storage/resource_arm_storage_account.go @@ -66,7 +66,6 @@ func resourceArmStorageAccount() *schema.Resource { "account_kind": { Type: schema.TypeString, Optional: true, - ForceNew: true, ValidateFunc: validation.StringInSlice([]string{ string(storage.Storage), string(storage.BlobStorage), @@ -541,6 +540,20 @@ func resourceArmStorageAccount() *schema.Resource { }, }, }, + CustomizeDiff: func(d *schema.ResourceDiff, v interface{}) error { + if d.HasChange("account_kind") { + accountKind, changedKind := d.GetChange("account_kind") + + if accountKind != string(storage.Storage) && changedKind != string(storage.StorageV2) { + log.Printf("[DEBUG] recreate storage account, could't be migrated from %s to %s", accountKind, changedKind) + d.ForceNew("account_kind") + } else { + log.Printf("[DEBUG] storage account can be upgraded from %s to %s", accountKind, changedKind) + } + } + + return nil + }, } } @@ -787,6 +800,18 @@ func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) e d.SetPartial("account_replication_type") } + if d.HasChange("account_kind") { + opts := storage.AccountUpdateParameters{ + Kind: storage.Kind(accountKind), + } + + if _, err := client.Update(ctx, resourceGroupName, storageAccountName, opts); err != nil { + return fmt.Errorf("Error updating Azure Storage Account account_kind %q: %+v", storageAccountName, err) + } + + d.SetPartial("access_kind") + } + if d.HasChange("access_tier") { accessTier := d.Get("access_tier").(string) diff --git a/azurerm/internal/services/storage/tests/resource_arm_storage_account_test.go b/azurerm/internal/services/storage/tests/resource_arm_storage_account_test.go index 760e180e14575..b188a3fd01488 100644 --- a/azurerm/internal/services/storage/tests/resource_arm_storage_account_test.go +++ b/azurerm/internal/services/storage/tests/resource_arm_storage_account_test.go @@ -368,6 +368,33 @@ func TestAccAzureRMStorageAccount_storageV2WithUpdate(t *testing.T) { }) } +func TestAccAzureRMStorageAccount_storageV1ToV2Update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_storage_account", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMStorageAccountDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMStorageAccount_storageToV2Prep(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageAccountExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "account_kind", "Storage"), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMStorageAccount_storageToV2Update(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageAccountExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "account_kind", "StorageV2"), + ), + }, + }, + }) +} + func TestAccAzureRMStorageAccount_NonStandardCasing(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_storage_account", "test") @@ -1129,6 +1156,60 @@ resource "azurerm_storage_account" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomString) } +func testAccAzureRMStorageAccount_storageToV2Prep(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-storage-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "unlikely23exst2acct%s" + resource_group_name = azurerm_resource_group.test.name + + location = azurerm_resource_group.test.location + account_kind = "Storage" + account_tier = "Standard" + account_replication_type = "LRS" + + tags = { + environment = "production" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString) +} + +func testAccAzureRMStorageAccount_storageToV2Update(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-storage-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "unlikely23exst2acct%s" + resource_group_name = azurerm_resource_group.test.name + + location = azurerm_resource_group.test.location + account_kind = "StorageV2" + account_tier = "Standard" + account_replication_type = "LRS" + + tags = { + environment = "production" + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString) +} + func testAccAzureRMStorageAccount_nonStandardCasing(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { diff --git a/website/docs/r/storage_account.html.markdown b/website/docs/r/storage_account.html.markdown index 0635b65d28e8b..860722c3f48a6 100644 --- a/website/docs/r/storage_account.html.markdown +++ b/website/docs/r/storage_account.html.markdown @@ -86,6 +86,8 @@ The following arguments are supported: * `account_kind` - (Optional) Defines the Kind of account. Valid options are `BlobStorage`, `BlockBlobStorage`, `FileStorage`, `Storage` and `StorageV2`. Changing this forces a new resource to be created. Defaults to `StorageV2`. +-> **NOTE:** Changing the `account_kind` value from `Storage` to `StorageV2` will not trigger a force new on the storage account, it will only upgrade the existing storage account from `Storage` to `StorageV2` keeping the existing storage account in place. + * `account_tier` - (Required) Defines the Tier to use for this storage account. Valid options are `Standard` and `Premium`. For `FileStorage` accounts only `Premium` is valid. Changing this forces a new resource to be created. * `account_replication_type` - (Required) Defines the type of replication to use for this storage account. Valid options are `LRS`, `GRS`, `RAGRS` and `ZRS`. From 5fd5868ea160152f78927ecd1c0807df281d365b Mon Sep 17 00:00:00 2001 From: WS <20408400+WodansSon@users.noreply.github.com> Date: Thu, 14 May 2020 02:03:09 -0700 Subject: [PATCH 090/104] updating to include #6580 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a163d1687f8d..2b2707263ba36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ IMPROVEMENTS: * `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6833] * `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` [GH-6833] * `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] +* `azurerm_storage_account` - Enable migration of `account_kind` from `Storage` to `StorageV2` [GH-6580] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] BUG FIXES: From 7a4fe8b73a2a5865dea50a12a862b6ee93f544ae Mon Sep 17 00:00:00 2001 From: MrDanao Date: Thu, 14 May 2020 12:48:09 +0200 Subject: [PATCH 091/104] Fix azurerm_subnet_nat_gateway_association documentation title --- website/docs/r/subnet_nat_gateway_association.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/subnet_nat_gateway_association.html.markdown b/website/docs/r/subnet_nat_gateway_association.html.markdown index 90cb2c1c5761f..3bacbcfb12f08 100644 --- a/website/docs/r/subnet_nat_gateway_association.html.markdown +++ b/website/docs/r/subnet_nat_gateway_association.html.markdown @@ -6,7 +6,7 @@ description: |- Associates a [NAT Gateway](nat_gateway.html) with a [Subnet](subnet.html) within a [Virtual Network](virtual_network.html). --- -# azurerm_subnet_route_table_association +# azurerm_subnet_nat_gateway_association Associates a [NAT Gateway](nat_gateway.html) with a [Subnet](subnet.html) within a [Virtual Network](virtual_network.html). From dedb295688b018c5308fd8f46c47ceb31017b649 Mon Sep 17 00:00:00 2001 From: jackofallops Date: Thu, 14 May 2020 13:53:56 +0100 Subject: [PATCH 092/104] Added poller to check for consistency on role assignment creation --- .../authorization/role_assignment_resource.go | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/azurerm/internal/services/authorization/role_assignment_resource.go b/azurerm/internal/services/authorization/role_assignment_resource.go index c3ffb6b93ba32..b7770c61512eb 100644 --- a/azurerm/internal/services/authorization/role_assignment_resource.go +++ b/azurerm/internal/services/authorization/role_assignment_resource.go @@ -1,6 +1,7 @@ package authorization import ( + "context" "fmt" "log" "strings" @@ -156,7 +157,6 @@ func resourceArmRoleAssignmentCreate(d *schema.ResourceData, meta interface{}) e if err := resource.Retry(300*time.Second, retryRoleAssignmentsClient(d, scope, name, properties, meta)); err != nil { return err } - read, err := roleAssignmentsClient.Get(ctx, scope, name) if err != nil { return err @@ -165,6 +165,23 @@ func resourceArmRoleAssignmentCreate(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Cannot read Role Assignment ID for %q (Scope %q)", name, scope) } + stateConf := &resource.StateChangeConf{ + Pending: []string{ + "pending", + }, + Target: []string{ + "ready", + }, + Refresh: roleAssignmentCreateStateRefreshFunc(ctx, roleAssignmentsClient, *read.ID), + MinTimeout: 5 * time.Second, + ContinuousTargetOccurence: 5, + Timeout: d.Timeout(schema.TimeoutCreate), + } + + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf("failed waiting for Role Assignment %q: %+v", name, err) + } + d.SetId(*read.ID) return resourceArmRoleAssignmentRead(d, meta) } @@ -282,3 +299,16 @@ func parseRoleAssignmentId(input string) (*roleAssignmentId, error) { } return &id, nil } + +func roleAssignmentCreateStateRefreshFunc(ctx context.Context, client *authorization.RoleAssignmentsClient, roleID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + resp, err := client.GetByID(ctx, roleID) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return resp, "pending", nil + } + return resp, "failed", err + } + return resp, "ready", nil + } +} From f55c694e28a9a9c5e8340fedb5424fbf3bb504de Mon Sep 17 00:00:00 2001 From: Steve <11830746+jackofallops@users.noreply.github.com> Date: Thu, 14 May 2020 14:15:49 +0100 Subject: [PATCH 093/104] Update azurerm/internal/services/authorization/role_assignment_resource.go Co-authored-by: Tom Harvey --- .../internal/services/authorization/role_assignment_resource.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/internal/services/authorization/role_assignment_resource.go b/azurerm/internal/services/authorization/role_assignment_resource.go index b7770c61512eb..d4e39e1133826 100644 --- a/azurerm/internal/services/authorization/role_assignment_resource.go +++ b/azurerm/internal/services/authorization/role_assignment_resource.go @@ -179,7 +179,7 @@ func resourceArmRoleAssignmentCreate(d *schema.ResourceData, meta interface{}) e } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("failed waiting for Role Assignment %q: %+v", name, err) + return fmt.Errorf("failed waiting for Role Assignment %q to finish replicating: %+v", name, err) } d.SetId(*read.ID) From 0f78094debfbd8fdd8c41210a2793b695e6c5304 Mon Sep 17 00:00:00 2001 From: Steve <11830746+jackofallops@users.noreply.github.com> Date: Thu, 14 May 2020 15:15:39 +0100 Subject: [PATCH 094/104] Update for #6925 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b2707263ba36..0daa91e9c9efb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ BUG FIXES: * `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` [GH-6911] * `azurerm_mariadb_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6865] * `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6833] +* `azurerm_role_assignment` - added evential consistency check to assignment creation [GH-6925] ## 2.9.0 (May 07, 2020) From 7a6e8da23289ca27aafb8eec3cac3b3a22dea587 Mon Sep 17 00:00:00 2001 From: Tom Harvey Date: Thu, 14 May 2020 19:01:09 +0200 Subject: [PATCH 095/104] updating to include #6917 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0daa91e9c9efb..c0302977fc7a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,10 +44,12 @@ BUG FIXES: * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] * `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] +* `azurerm_linux_virtual_machine_scale_set` - support for updating the `do_not_run_extensions_on_overprovisioned_machines` property [GH-6917] * `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` [GH-6911] * `azurerm_mariadb_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6865] * `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6833] * `azurerm_role_assignment` - added evential consistency check to assignment creation [GH-6925] +* `azurerm_windows_virtual_machine_scale_set` - support for updating the `do_not_run_extensions_on_overprovisioned_machines` property [GH-6917] ## 2.9.0 (May 07, 2020) From a061bca1cf6e6acf46885ff7fa24daaeb6936b45 Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 14 May 2020 11:59:54 -0700 Subject: [PATCH 096/104] update CHANGELOG.md to include #6723 --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0302977fc7a6..c945fff2d8482 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,8 @@ IMPROVEMENTS: * All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] * Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] * `azurerm_api_management` - support for configuring the Developer Portal [GH-6724] -* `azurerm_api_managment` - support for user assigned managed identities [GH-6783] +* `azurerm_api_management` - support for user assigned managed identities [GH-6783] +* `azurerm_api_management` - support `key_vault_id` that do not have a version [GH-6723] * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] From 7a9a656cc6c7a876efc4948bc002cde3ad0fd8a1 Mon Sep 17 00:00:00 2001 From: Sune Keller Date: Thu, 14 May 2020 21:15:55 +0200 Subject: [PATCH 097/104] azurerm_api_management - support key_vault_id's without a version (#6723) Fixes #4408. --- azurerm/helpers/azure/key_vault_child.go | 53 ++++ azurerm/helpers/azure/key_vault_child_test.go | 137 +++++++++ .../apimanagement/api_management_resource.go | 2 +- .../tests/api_management_resource_test.go | 278 +++++++++++++++++- 4 files changed, 464 insertions(+), 6 deletions(-) diff --git a/azurerm/helpers/azure/key_vault_child.go b/azurerm/helpers/azure/key_vault_child.go index 386a4e7e89502..d352eda26aaec 100644 --- a/azurerm/helpers/azure/key_vault_child.go +++ b/azurerm/helpers/azure/key_vault_child.go @@ -42,6 +42,38 @@ func ParseKeyVaultChildID(id string) (*KeyVaultChildID, error) { return &childId, nil } +func ParseKeyVaultChildIDVersionOptional(id string) (*KeyVaultChildID, error) { + // example: https://tharvey-keyvault.vault.azure.net/type/bird/fdf067c93bbb4b22bff4d8b7a9a56217 + idURL, err := url.ParseRequestURI(id) + if err != nil { + return nil, fmt.Errorf("Cannot parse Azure KeyVault Child Id: %s", err) + } + + path := idURL.Path + + path = strings.TrimPrefix(path, "/") + path = strings.TrimSuffix(path, "/") + + components := strings.Split(path, "/") + + if len(components) != 2 && len(components) != 3 { + return nil, fmt.Errorf("Azure KeyVault Child Id should have 2 or 3 segments, got %d: '%s'", len(components), path) + } + + version := "" + if len(components) == 3 { + version = components[2] + } + + childId := KeyVaultChildID{ + KeyVaultBaseUrl: fmt.Sprintf("%s://%s/", idURL.Scheme, idURL.Host), + Name: components[1], + Version: version, + } + + return &childId, nil +} + func ValidateKeyVaultChildName(v interface{}, k string) (warnings []string, errors []error) { value := v.(string) @@ -72,3 +104,24 @@ func ValidateKeyVaultChildId(i interface{}, k string) (warnings []string, errors return warnings, errors } + +// Unfortunately this can't (easily) go in the Validate package +// since there's a circular reference on this package +func ValidateKeyVaultChildIdVersionOptional(i interface{}, k string) (warnings []string, errors []error) { + if warnings, errors = validation.StringIsNotEmpty(i, k); len(errors) > 0 { + return warnings, errors + } + + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("Expected %s to be a string!", k)) + return warnings, errors + } + + if _, err := ParseKeyVaultChildIDVersionOptional(v); err != nil { + errors = append(errors, fmt.Errorf("Error parsing Key Vault Child ID: %s", err)) + return warnings, errors + } + + return warnings, errors +} diff --git a/azurerm/helpers/azure/key_vault_child_test.go b/azurerm/helpers/azure/key_vault_child_test.go index b8b1e8998aafe..2e5951cc7659a 100644 --- a/azurerm/helpers/azure/key_vault_child_test.go +++ b/azurerm/helpers/azure/key_vault_child_test.go @@ -55,6 +55,59 @@ func TestAccAzureRMValidateKeyVaultChildID(t *testing.T) { } } +func TestAccAzureRMValidateKeyVaultChildIDVersionOptional(t *testing.T) { + cases := []struct { + Input string + ExpectError bool + }{ + { + Input: "", + ExpectError: true, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets", + ExpectError: true, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets/bird", + ExpectError: false, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets/bird/fdf067c93bbb4b22bff4d8b7a9a56217", + ExpectError: false, + }, + { + Input: "https://my-keyvault.vault.azure.net/certificates/hello/world", + ExpectError: false, + }, + { + Input: "https://my-keyvault.vault.azure.net/keys/castle/1492", + ExpectError: false, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets/bird/fdf067c93bbb4b22bff4d8b7a9a56217/XXX", + ExpectError: true, + }, + } + + for _, tc := range cases { + warnings, err := ValidateKeyVaultChildIdVersionOptional(tc.Input, "example") + if err != nil { + if !tc.ExpectError { + t.Fatalf("Got error for input %q: %+v", tc.Input, err) + } + + return + } + + if tc.ExpectError && len(warnings) == 0 { + t.Fatalf("Got no errors for input %q but expected some", tc.Input) + } else if !tc.ExpectError && len(warnings) > 0 { + t.Fatalf("Got %d errors for input %q when didn't expect any", len(warnings), tc.Input) + } + } +} + func TestAccAzureRMKeyVaultChild_parseID(t *testing.T) { cases := []struct { Input string @@ -134,6 +187,90 @@ func TestAccAzureRMKeyVaultChild_parseID(t *testing.T) { } } +func TestAccAzureRMKeyVaultChild_parseIDVersionOptional(t *testing.T) { + cases := []struct { + Input string + Expected KeyVaultChildID + ExpectError bool + }{ + { + Input: "", + ExpectError: true, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets", + ExpectError: true, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets/bird", + ExpectError: false, + Expected: KeyVaultChildID{ + Name: "bird", + KeyVaultBaseUrl: "https://my-keyvault.vault.azure.net/", + Version: "", + }, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets/bird/fdf067c93bbb4b22bff4d8b7a9a56217", + ExpectError: false, + Expected: KeyVaultChildID{ + Name: "bird", + KeyVaultBaseUrl: "https://my-keyvault.vault.azure.net/", + Version: "fdf067c93bbb4b22bff4d8b7a9a56217", + }, + }, + { + Input: "https://my-keyvault.vault.azure.net/certificates/hello/world", + ExpectError: false, + Expected: KeyVaultChildID{ + Name: "hello", + KeyVaultBaseUrl: "https://my-keyvault.vault.azure.net/", + Version: "world", + }, + }, + { + Input: "https://my-keyvault.vault.azure.net/keys/castle/1492", + ExpectError: false, + Expected: KeyVaultChildID{ + Name: "castle", + KeyVaultBaseUrl: "https://my-keyvault.vault.azure.net/", + Version: "1492", + }, + }, + { + Input: "https://my-keyvault.vault.azure.net/secrets/bird/fdf067c93bbb4b22bff4d8b7a9a56217/XXX", + ExpectError: true, + }, + } + + for _, tc := range cases { + secretId, err := ParseKeyVaultChildIDVersionOptional(tc.Input) + if err != nil { + if !tc.ExpectError { + t.Fatalf("Got error for ID '%s': %+v", tc.Input, err) + } + + return + } + + if secretId == nil { + t.Fatalf("Expected a SecretID to be parsed for ID '%s', got nil.", tc.Input) + } + + if tc.Expected.KeyVaultBaseUrl != secretId.KeyVaultBaseUrl { + t.Fatalf("Expected 'KeyVaultBaseUrl' to be '%s', got '%s' for ID '%s'", tc.Expected.KeyVaultBaseUrl, secretId.KeyVaultBaseUrl, tc.Input) + } + + if tc.Expected.Name != secretId.Name { + t.Fatalf("Expected 'Version' to be '%s', got '%s' for ID '%s'", tc.Expected.Name, secretId.Name, tc.Input) + } + + if tc.Expected.Version != secretId.Version { + t.Fatalf("Expected 'Version' to be '%s', got '%s' for ID '%s'", tc.Expected.Version, secretId.Version, tc.Input) + } + } +} + func TestAccAzureRMKeyVaultChild_validateName(t *testing.T) { cases := []struct { Input string diff --git a/azurerm/internal/services/apimanagement/api_management_resource.go b/azurerm/internal/services/apimanagement/api_management_resource.go index d75305d26b80f..75c373d17bb6e 100644 --- a/azurerm/internal/services/apimanagement/api_management_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_resource.go @@ -1139,7 +1139,7 @@ func apiManagementResourceHostnameSchema(schemaName string) map[string]*schema.S "key_vault_id": { Type: schema.TypeString, Optional: true, - ValidateFunc: azure.ValidateKeyVaultChildId, + ValidateFunc: azure.ValidateKeyVaultChildIdVersionOptional, ConflictsWith: []string{ fmt.Sprintf("hostname_configuration.0.%s.0.certificate", schemaName), fmt.Sprintf("hostname_configuration.0.%s.0.certificate_password", schemaName), diff --git a/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go b/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go index 959578090643b..09ccdcf49f668 100644 --- a/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go +++ b/azurerm/internal/services/apimanagement/tests/api_management_resource_test.go @@ -191,6 +191,58 @@ func TestAccAzureRMApiManagement_virtualNetworkInternal(t *testing.T) { }) } +func TestAccAzureRMApiManagement_identitySystemAssignedUpdateHostnameConfigurationsVersionedKeyVaultId(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUpdateHostnameConfigurationsVersionedKeyVaultId(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMApiManagement_identitySystemAssignedUpdateHostnameConfigurationsVersionlessKeyVaultId(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagement_identitySystemAssigned(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagement_identitySystemAssignedUpdateHostnameConfigurationsVersionlessKeyVaultId(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + func testCheckAzureRMApiManagementDestroy(s *terraform.State) error { conn := acceptance.AzureProvider.Meta().(*clients.Client).ApiManagement.ServiceClient ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext @@ -889,21 +941,17 @@ func testAccAzureRMApiManagement_identitySystemAssigned(data acceptance.TestData provider "azurerm" { features {} } - resource "azurerm_resource_group" "test" { name = "acctestRG-%d" location = "%s" } - resource "azurerm_api_management" "test" { name = "acctestAM-%d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name publisher_name = "pub1" publisher_email = "pub1@email.com" - - sku_name = "Developer_1" - + sku_name = "Developer_1" identity { type = "SystemAssigned" } @@ -973,3 +1021,223 @@ resource "azurerm_api_management" "test" { } `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } + +func testAccAzureRMApiManagement_identitySystemAssignedUpdateHostnameConfigurationsVersionlessKeyVaultId(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%[2]s" +} +data "azurerm_client_config" "current" {} +resource "azurerm_key_vault" "test" { + name = "acctestKV-%[3]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" +} +resource "azurerm_key_vault_access_policy" "test" { + key_vault_id = azurerm_key_vault.test.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + certificate_permissions = [ + "Create", + "Delete", + "Deleteissuers", + "Get", + "Getissuers", + "Import", + "List", + "Listissuers", + "Managecontacts", + "Manageissuers", + "Setissuers", + "Update", + ] + secret_permissions = [ + "Delete", + "Get", + "List", + "Purge", + ] +} +resource "azurerm_key_vault_access_policy" "test2" { + key_vault_id = azurerm_key_vault.test.id + tenant_id = azurerm_api_management.test.identity[0].tenant_id + object_id = azurerm_api_management.test.identity[0].principal_id + secret_permissions = [ + "Get", + "List", + ] +} +resource "azurerm_key_vault_certificate" "test" { + depends_on = [azurerm_key_vault_access_policy.test] + name = "acctestKVCert-%[3]d" + key_vault_id = azurerm_key_vault.test.id + certificate_policy { + issuer_parameters { + name = "Self" + } + key_properties { + exportable = true + key_size = 2048 + key_type = "RSA" + reuse_key = true + } + secret_properties { + content_type = "application/x-pkcs12" + } + x509_certificate_properties { + # Server Authentication = 1.3.6.1.5.5.7.3.1 + # Client Authentication = 1.3.6.1.5.5.7.3.2 + extended_key_usage = ["1.3.6.1.5.5.7.3.1"] + key_usage = [ + "cRLSign", + "dataEncipherment", + "digitalSignature", + "keyAgreement", + "keyCertSign", + "keyEncipherment", + ] + subject_alternative_names { + dns_names = ["api.terraform.io"] + } + subject = "CN=api.terraform.io" + validity_in_months = 1 + } + } +} +resource "azurerm_api_management" "test" { + name = "acctestAM-%[3]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + publisher_name = "pub1" + publisher_email = "pub1@email.com" + sku_name = "Developer_1" + identity { + type = "SystemAssigned" + } + hostname_configuration { + proxy { + host_name = "api.terraform.io" + key_vault_id = "${azurerm_key_vault.test.vault_uri}secrets/${azurerm_key_vault_certificate.test.name}" + default_ssl_binding = true + negotiate_client_certificate = false + } + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + +func testAccAzureRMApiManagement_identitySystemAssignedUpdateHostnameConfigurationsVersionedKeyVaultId(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} +resource "azurerm_resource_group" "test" { + name = "acctestRG-%[1]d" + location = "%[2]s" +} +data "azurerm_client_config" "current" {} +resource "azurerm_key_vault" "test" { + name = "acctestKV-%[3]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + sku_name = "standard" +} +resource "azurerm_key_vault_access_policy" "test" { + key_vault_id = azurerm_key_vault.test.id + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + certificate_permissions = [ + "Create", + "Delete", + "Deleteissuers", + "Get", + "Getissuers", + "Import", + "List", + "Listissuers", + "Managecontacts", + "Manageissuers", + "Setissuers", + "Update", + ] + secret_permissions = [ + "Delete", + "Get", + "List", + "Purge", + ] +} +resource "azurerm_key_vault_access_policy" "test2" { + key_vault_id = azurerm_key_vault.test.id + tenant_id = azurerm_api_management.test.identity[0].tenant_id + object_id = azurerm_api_management.test.identity[0].principal_id + secret_permissions = [ + "Get", + "List", + ] +} +resource "azurerm_key_vault_certificate" "test" { + depends_on = [azurerm_key_vault_access_policy.test] + name = "acctestKVCert-%[3]d" + key_vault_id = azurerm_key_vault.test.id + certificate_policy { + issuer_parameters { + name = "Self" + } + key_properties { + exportable = true + key_size = 2048 + key_type = "RSA" + reuse_key = true + } + secret_properties { + content_type = "application/x-pkcs12" + } + x509_certificate_properties { + # Server Authentication = 1.3.6.1.5.5.7.3.1 + # Client Authentication = 1.3.6.1.5.5.7.3.2 + extended_key_usage = ["1.3.6.1.5.5.7.3.1"] + key_usage = [ + "cRLSign", + "dataEncipherment", + "digitalSignature", + "keyAgreement", + "keyCertSign", + "keyEncipherment", + ] + subject_alternative_names { + dns_names = ["api.terraform.io"] + } + subject = "CN=api.terraform.io" + validity_in_months = 1 + } + } +} +resource "azurerm_api_management" "test" { + name = "acctestAM-%[3]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + publisher_name = "pub1" + publisher_email = "pub1@email.com" + sku_name = "Developer_1" + identity { + type = "SystemAssigned" + } + hostname_configuration { + proxy { + host_name = "api.terraform.io" + key_vault_id = azurerm_key_vault_certificate.test.secret_id + default_ssl_binding = true + negotiate_client_certificate = false + } + } +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} From e1d441856b43820ee20f468af6bd9f8b37b0baef Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 14 May 2020 13:10:25 -0700 Subject: [PATCH 098/104] azurerm_postgres_server - support for threat_detection_policy (#6721) --- ...l_server_security_alert_policy_resource.go | 2 + ...ver_security_alert_policy_resource_test.go | 4 +- .../services/postgres/client/client.go | 25 ++- .../postgres/postgresql_server_resource.go | 204 +++++++++++++++++- .../tests/postgresql_server_resource_test.go | 83 ++++++- .../docs/r/postgresql_server.html.markdown | 21 ++ 6 files changed, 310 insertions(+), 29 deletions(-) diff --git a/azurerm/internal/services/mssql/mssql_server_security_alert_policy_resource.go b/azurerm/internal/services/mssql/mssql_server_security_alert_policy_resource.go index bb8ce87b02772..4f2e9fc649fed 100644 --- a/azurerm/internal/services/mssql/mssql_server_security_alert_policy_resource.go +++ b/azurerm/internal/services/mssql/mssql_server_security_alert_policy_resource.go @@ -14,6 +14,8 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) +// todo 3.0 - this may want to be put into the mssql_server resource now that it exists. + func resourceArmMssqlServerSecurityAlertPolicy() *schema.Resource { return &schema.Resource{ Create: resourceArmMssqlServerSecurityAlertPolicyCreateUpdate, diff --git a/azurerm/internal/services/mssql/tests/mssql_server_security_alert_policy_resource_test.go b/azurerm/internal/services/mssql/tests/mssql_server_security_alert_policy_resource_test.go index 53a8304b71448..a2c063ec9e3d7 100644 --- a/azurerm/internal/services/mssql/tests/mssql_server_security_alert_policy_resource_test.go +++ b/azurerm/internal/services/mssql/tests/mssql_server_security_alert_policy_resource_test.go @@ -184,9 +184,9 @@ resource "azurerm_sql_server" "test" { resource "azurerm_storage_account" "test" { name = "accsa%d" resource_group_name = azurerm_resource_group.test.name - location = "%s" + location = azurerm_resource_group.test.location account_tier = "Standard" account_replication_type = "GRS" } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.Locations.Primary) +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger) } diff --git a/azurerm/internal/services/postgres/client/client.go b/azurerm/internal/services/postgres/client/client.go index 50975fc5276c3..0dd71d9cc3044 100644 --- a/azurerm/internal/services/postgres/client/client.go +++ b/azurerm/internal/services/postgres/client/client.go @@ -6,11 +6,12 @@ import ( ) type Client struct { - ConfigurationsClient *postgresql.ConfigurationsClient - DatabasesClient *postgresql.DatabasesClient - FirewallRulesClient *postgresql.FirewallRulesClient - ServersClient *postgresql.ServersClient - VirtualNetworkRulesClient *postgresql.VirtualNetworkRulesClient + ConfigurationsClient *postgresql.ConfigurationsClient + DatabasesClient *postgresql.DatabasesClient + FirewallRulesClient *postgresql.FirewallRulesClient + ServersClient *postgresql.ServersClient + ServerSecurityAlertPoliciesClient *postgresql.ServerSecurityAlertPoliciesClient + VirtualNetworkRulesClient *postgresql.VirtualNetworkRulesClient } func NewClient(o *common.ClientOptions) *Client { @@ -26,14 +27,18 @@ func NewClient(o *common.ClientOptions) *Client { serversClient := postgresql.NewServersClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&serversClient.Client, o.ResourceManagerAuthorizer) + serverSecurityAlertPoliciesClient := postgresql.NewServerSecurityAlertPoliciesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&serverSecurityAlertPoliciesClient.Client, o.ResourceManagerAuthorizer) + virtualNetworkRulesClient := postgresql.NewVirtualNetworkRulesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&virtualNetworkRulesClient.Client, o.ResourceManagerAuthorizer) return &Client{ - ConfigurationsClient: &configurationsClient, - DatabasesClient: &databasesClient, - FirewallRulesClient: &firewallRulesClient, - ServersClient: &serversClient, - VirtualNetworkRulesClient: &virtualNetworkRulesClient, + ConfigurationsClient: &configurationsClient, + DatabasesClient: &databasesClient, + FirewallRulesClient: &firewallRulesClient, + ServersClient: &serversClient, + ServerSecurityAlertPoliciesClient: &serverSecurityAlertPoliciesClient, + VirtualNetworkRulesClient: &virtualNetworkRulesClient, } } diff --git a/azurerm/internal/services/postgres/postgresql_server_resource.go b/azurerm/internal/services/postgres/postgresql_server_resource.go index f9d1eeb3e24f7..2009022523f99 100644 --- a/azurerm/internal/services/postgres/postgresql_server_resource.go +++ b/azurerm/internal/services/postgres/postgresql_server_resource.go @@ -277,6 +277,70 @@ func resourceArmPostgreSQLServer() *schema.Resource { DiffSuppressFunc: suppress.CaseDifference, }, + "threat_detection_policy": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + }, + + "disabled_alerts": { + Type: schema.TypeSet, + Optional: true, + Set: schema.HashString, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + "Sql_Injection", + "Sql_Injection_Vulnerability", + "Access_Anomaly", + "Data_Exfiltration", + "Unsafe_Action", + }, false), + }, + }, + + "email_account_admins": { + Type: schema.TypeBool, + Optional: true, + }, + + "email_addresses": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + // todo email validation in code + }, + Set: schema.HashString, + }, + + "retention_days": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntAtLeast(0), + }, + + "storage_account_access_key": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "storage_endpoint": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + }, + }, + }, + "fqdn": { Type: schema.TypeString, Computed: true, @@ -289,6 +353,7 @@ func resourceArmPostgreSQLServer() *schema.Resource { func resourceArmPostgreSQLServerCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).Postgres.ServersClient + securityClient := meta.(*clients.Client).Postgres.ServerSecurityAlertPoliciesClient ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -339,7 +404,7 @@ func resourceArmPostgreSQLServerCreate(d *schema.ResourceData, meta interface{}) ssl = postgresql.SslEnforcementEnumDisabled } - storage := expandAzureRmPostgreSQLStorageProfile(d) + storage := expandPostgreSQLStorageProfile(d) var props postgresql.BasicServerPropertiesForCreate switch mode { @@ -440,11 +505,26 @@ func resourceArmPostgreSQLServerCreate(d *schema.ResourceData, meta interface{}) d.SetId(*read.ID) + if v, ok := d.GetOk("threat_detection_policy"); ok { + alert := expandSecurityAlertPolicy(v) + if alert != nil { + future, err := securityClient.CreateOrUpdate(ctx, resourceGroup, name, *alert) + if err != nil { + return fmt.Errorf("error updataing postgres server security alert policy: %v", err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("error waiting for creation/update of postgrest server security alert policy (server %q, resource group %q): %+v", name, resourceGroup, err) + } + } + } + return resourceArmPostgreSQLServerRead(d, meta) } func resourceArmPostgreSQLServerUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).Postgres.ServersClient + securityClient := meta.(*clients.Client).Postgres.ServerSecurityAlertPoliciesClient ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() @@ -478,7 +558,7 @@ func resourceArmPostgreSQLServerUpdate(d *schema.ResourceData, meta interface{}) AdministratorLoginPassword: utils.String(d.Get("administrator_login_password").(string)), PublicNetworkAccess: publicAccess, SslEnforcement: ssl, - StorageProfile: expandAzureRmPostgreSQLStorageProfile(d), + StorageProfile: expandPostgreSQLStorageProfile(d), Version: postgresql.ServerVersion(d.Get("version").(string)), }, Sku: sku, @@ -494,21 +574,26 @@ func resourceArmPostgreSQLServerUpdate(d *schema.ResourceData, meta interface{}) return fmt.Errorf("waiting for update of PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) } - read, err := client.Get(ctx, id.ResourceGroup, id.Name) - if err != nil { - return fmt.Errorf("retrieving PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err) - } - if read.ID == nil { - return fmt.Errorf("Cannot read PostgreSQL Server %s (resource group %s) ID", id.Name, id.ResourceGroup) - } + if v, ok := d.GetOk("threat_detection_policy"); ok { + alert := expandSecurityAlertPolicy(v) + if alert != nil { + future, err := securityClient.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, *alert) + if err != nil { + return fmt.Errorf("error updataing mssql server security alert policy: %v", err) + } - d.SetId(*read.ID) + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("error waiting for creation/update of postgrest server security alert policy (server %q, resource group %q): %+v", id.Name, id.ResourceGroup, err) + } + } + } return resourceArmPostgreSQLServerRead(d, meta) } func resourceArmPostgreSQLServerRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).Postgres.ServersClient + securityClient := meta.(*clients.Client).Postgres.ServerSecurityAlertPoliciesClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -563,6 +648,19 @@ func resourceArmPostgreSQLServerRead(d *schema.ResourceData, meta interface{}) e // Computed d.Set("fqdn", props.FullyQualifiedDomainName) } + + secResp, err := securityClient.Get(ctx, id.ResourceGroup, id.Name) + if err != nil && !utils.ResponseWasNotFound(secResp.Response) { + return fmt.Errorf("error making read request to postgres server security alert policy: %+v", err) + } + + if !utils.ResponseWasNotFound(secResp.Response) { + block := flattenSecurityAlertPolicy(secResp.SecurityAlertPolicyProperties, d.Get("threat_detection_policy.0.storage_account_access_key").(string)) + if err := d.Set("threat_detection_policy", block); err != nil { + return fmt.Errorf("setting `threat_detection_policy`: %+v", err) + } + } + return tags.FlattenAndSet(d, resp.Tags) } @@ -627,7 +725,7 @@ func expandServerSkuName(skuName string) (*postgresql.Sku, error) { }, nil } -func expandAzureRmPostgreSQLStorageProfile(d *schema.ResourceData) *postgresql.StorageProfile { +func expandPostgreSQLStorageProfile(d *schema.ResourceData) *postgresql.StorageProfile { storage := postgresql.StorageProfile{} if v, ok := d.GetOk("storage_profile"); ok { storageprofile := v.([]interface{})[0].(map[string]interface{}) @@ -682,3 +780,87 @@ func flattenPostgreSQLStorageProfile(resp *postgresql.StorageProfile) []interfac return []interface{}{values} } + +func expandSecurityAlertPolicy(i interface{}) *postgresql.ServerSecurityAlertPolicy { + slice := i.([]interface{}) + if len(slice) == 0 { + return nil + } + + block := slice[0].(map[string]interface{}) + + state := postgresql.ServerSecurityAlertPolicyStateEnabled + if !block["enabled"].(bool) { + state = postgresql.ServerSecurityAlertPolicyStateDisabled + } + + props := &postgresql.SecurityAlertPolicyProperties{ + State: state, + } + + if v, ok := block["disabled_alerts"]; ok { + props.DisabledAlerts = utils.ExpandStringSlice(v.(*schema.Set).List()) + } + + if v, ok := block["email_addresses"]; ok { + props.EmailAddresses = utils.ExpandStringSlice(v.(*schema.Set).List()) + } + + if v, ok := block["email_account_admins"]; ok { + props.EmailAccountAdmins = utils.Bool(v.(bool)) + } + + if v, ok := block["retention_days"]; ok { + props.RetentionDays = utils.Int32(int32(v.(int))) + } + + if v, ok := block["storage_account_access_key"]; ok && v.(string) != "" { + props.StorageAccountAccessKey = utils.String(v.(string)) + } + + if v, ok := block["storage_endpoint"]; ok && v.(string) != "" { + props.StorageEndpoint = utils.String(v.(string)) + } + + return &postgresql.ServerSecurityAlertPolicy{ + SecurityAlertPolicyProperties: props, + } +} + +func flattenSecurityAlertPolicy(props *postgresql.SecurityAlertPolicyProperties, accessKey string) interface{} { + if props == nil { + return nil + } + + // check if its an empty block as in its never been set before + if props.DisabledAlerts != nil && len(*props.DisabledAlerts) == 1 && (*props.DisabledAlerts)[0] == "" && + props.EmailAddresses != nil && len(*props.EmailAddresses) == 1 && (*props.EmailAddresses)[0] == "" && + props.StorageAccountAccessKey != nil && *props.StorageAccountAccessKey == "" && + props.StorageEndpoint != nil && *props.StorageEndpoint == "" && + props.RetentionDays != nil && *props.RetentionDays == 0 && + props.EmailAccountAdmins != nil && !*props.EmailAccountAdmins && + props.State == postgresql.ServerSecurityAlertPolicyStateDisabled { + return nil + } + + block := map[string]interface{}{} + + block["enabled"] = props.State == postgresql.ServerSecurityAlertPolicyStateEnabled + + block["disabled_alerts"] = utils.FlattenStringSlice(props.DisabledAlerts) + block["email_addresses"] = utils.FlattenStringSlice(props.EmailAddresses) + + if v := props.EmailAccountAdmins; v != nil { + block["email_account_admins"] = *v + } + if v := props.RetentionDays; v != nil { + block["retention_days"] = *v + } + if v := props.StorageEndpoint; v != nil { + block["storage_endpoint"] = *v + } + + block["storage_account_access_key"] = accessKey + + return []interface{}{block} +} diff --git a/azurerm/internal/services/postgres/tests/postgresql_server_resource_test.go b/azurerm/internal/services/postgres/tests/postgresql_server_resource_test.go index f0d93a0a0d0d0..5e59542454709 100644 --- a/azurerm/internal/services/postgres/tests/postgresql_server_resource_test.go +++ b/azurerm/internal/services/postgres/tests/postgresql_server_resource_test.go @@ -225,6 +225,13 @@ func TestAccAzureRMPostgreSQLServer_updated(t *testing.T) { ), }, data.ImportStep("administrator_login_password"), + { + Config: testAccAzureRMPostgreSQLServer_complete2(data, "9.6"), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPostgreSQLServerExists(data.ResourceName), + ), + }, + data.ImportStep("administrator_login_password"), { Config: testAccAzureRMPostgreSQLServer_basic(data, "9.6"), Check: resource.ComposeTestCheckFunc( @@ -501,7 +508,7 @@ resource "azurerm_postgresql_server" "import" { sku_name = azurerm_postgresql_server.test.sku_name version = azurerm_postgresql_server.test.version - storage_mb = azurerm_postgresql_server.test.storage_profile.storage_mb + storage_mb = azurerm_postgresql_server.test.storage_mb ssl_enforcement_enabled = azurerm_postgresql_server.test.ssl_enforcement_enabled } @@ -553,12 +560,12 @@ provider "azurerm" { } resource "azurerm_resource_group" "test" { - name = "acctestRG-psql-%d" - location = "%s" + name = "acctestRG-psql-%[1]d" + location = "%[2]s" } resource "azurerm_postgresql_server" "test" { - name = "acctest-psql-server-%d" + name = "acctest-psql-server-%[1]d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name @@ -566,7 +573,7 @@ resource "azurerm_postgresql_server" "test" { administrator_login_password = "H@Sh1CoR3!updated" sku_name = "GP_Gen5_4" - version = "%s" + version = "%[3]s" storage_mb = 640000 backup_retention_days = 7 @@ -577,8 +584,72 @@ resource "azurerm_postgresql_server" "test" { public_network_access_enabled = false ssl_enforcement_enabled = true ssl_minimal_tls_version_enforced = "TLS1_2" + + threat_detection_policy { + enabled = true + disabled_alerts = ["Sql_Injection", "Data_Exfiltration"] + email_account_admins = true + email_addresses = ["kt@example.com", "admin@example.com"] + + retention_days = 7 + } } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, version) +`, data.RandomInteger, data.Locations.Primary, version) +} + +func testAccAzureRMPostgreSQLServer_complete2(data acceptance.TestData, version string) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-psql-%[1]d" + location = "%[2]s" +} + +resource "azurerm_storage_account" "test" { + name = "accsa%[1]d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "GRS" +} + +resource "azurerm_postgresql_server" "test" { + name = "acctest-psql-server-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + + administrator_login = "acctestun" + administrator_login_password = "H@Sh1CoR3!updated" + + sku_name = "GP_Gen5_4" + version = "%[3]s" + storage_mb = 640000 + + backup_retention_days = 14 + geo_redundant_backup_enabled = false + auto_grow_enabled = false + + infrastructure_encryption_enabled = false + public_network_access_enabled = true + ssl_enforcement_enabled = false + ssl_minimal_tls_version_enforced = "TLS1_1" + + threat_detection_policy { + enabled = true + disabled_alerts = ["Sql_Injection"] + email_account_admins = true + email_addresses = ["kt@example.com"] + + retention_days = 7 + + storage_endpoint = azurerm_storage_account.test.primary_blob_endpoint + storage_account_access_key = azurerm_storage_account.test.primary_access_key + } +} +`, data.RandomInteger, data.Locations.Primary, version) } func testAccAzureRMPostgreSQLServer_sku(data acceptance.TestData, version, sku string) string { diff --git a/website/docs/r/postgresql_server.html.markdown b/website/docs/r/postgresql_server.html.markdown index 7aa92293383df..25fe6491314c9 100644 --- a/website/docs/r/postgresql_server.html.markdown +++ b/website/docs/r/postgresql_server.html.markdown @@ -87,8 +87,29 @@ The following arguments are supported: * `storage_mb` - (Optional) Max storage allowed for a server. Possible values are between `5120` MB(5GB) and `1048576` MB(1TB) for the Basic SKU and between `5120` MB(5GB) and `4194304` MB(4TB) for General Purpose/Memory Optimized SKUs. For more information see the [product documentation](https://docs.microsoft.com/en-us/rest/api/postgresql/servers/create#StorageProfile). +* `threat_detection_policy` - (Optional) Threat detection policy configuration, known in the API as Server Security Alerts Policy. The `threat_detection_policy` block supports fields documented below. + * `tags` - (Optional) A mapping of tags to assign to the resource. +--- + +a `threat_detection_policy` block supports the following: + +* `enabled` - (Required) Is the policy enabled? + +* `disabled_alerts` - (Optional) Specifies a list of alerts which should be disabled. Possible values include `Access_Anomaly`, `Sql_Injection` and `Sql_Injection_Vulnerability`. + +* `email_account_admins` - (Optional) Should the account administrators be emailed when this alert is triggered? + +* `email_addresses` - (Optional) A list of email addresses which alerts should be sent to. + +* `retention_days` - (Optional) Specifies the number of days to keep in the Threat Detection audit logs. + +* `storage_account_access_key` - (Optional) Specifies the identifier key of the Threat Detection audit storage account. + +* `storage_endpoint` - (Optional) Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection audit logs. + + ## Attributes Reference The following attributes are exported: From 0e33974d7dca00acb8159ffb70a6041116141a15 Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 14 May 2020 13:11:30 -0700 Subject: [PATCH 099/104] update CHANGEloG.md to include #6721 --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c945fff2d8482..c4e764ad0e4b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ IMPROVEMENTS: * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] -* `azurerm_frontdoor` - Expose the `header_frontdoor_id` attribute [GH-6916] +* `azurerm_frontdoor` - expose the `header_frontdoor_id` attribute [GH-6916] * `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] * `azurerm_mariadb_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6865] * `azurerm_mariadb_server` - support for the `public_network_access_enabled` property [GH-6865] @@ -30,8 +30,9 @@ IMPROVEMENTS: * `azurerm_mysql_server` - support for the `public_network_access_enabled` property [GH-6833] * `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6833] * `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` [GH-6833] -* `azurerm_mssql_server` - add support for `azuread_administrator` [GH-6822] -* `azurerm_storage_account` - Enable migration of `account_kind` from `Storage` to `StorageV2` [GH-6580] +* `azurerm_mssql_server` - add support for the `azuread_administrator` property [GH-6822] +* `azurerm_postgres_server` - support for the `threat_detection_policy` property [GH-6721] +* `azurerm_storage_account` - enable migration of `account_kind` from `Storage` to `StorageV2` [GH-6580] * `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] BUG FIXES: From 38d4961e1ca662e43c636b015069a837641c3aad Mon Sep 17 00:00:00 2001 From: Chang Li Date: Fri, 15 May 2020 05:28:43 +0800 Subject: [PATCH 100/104] Fix duplicate provider configuration in storage tests (#6748) --- .../resource_arm_storage_container_test.go | 27 ++++++++++++++++--- .../tests/resource_arm_storage_queue_test.go | 26 +++++++++++++++--- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/azurerm/internal/services/storage/tests/resource_arm_storage_container_test.go b/azurerm/internal/services/storage/tests/resource_arm_storage_container_test.go index eba09c032ebc0..54e39dcaa5a82 100644 --- a/azurerm/internal/services/storage/tests/resource_arm_storage_container_test.go +++ b/azurerm/internal/services/storage/tests/resource_arm_storage_container_test.go @@ -313,14 +313,35 @@ resource "azurerm_storage_container" "test" { } func testAccAzureRMStorageContainer_basicAzureADAuth(data acceptance.TestData) string { - template := testAccAzureRMStorageContainer_basic(data) return fmt.Sprintf(` provider "azurerm" { storage_use_azuread = true + features {} } -%s -`, template) +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestacc%s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" + + tags = { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + storage_account_name = azurerm_storage_account.test.name + container_access_type = "private" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString) } func testAccAzureRMStorageContainer_requiresImport(data acceptance.TestData) string { diff --git a/azurerm/internal/services/storage/tests/resource_arm_storage_queue_test.go b/azurerm/internal/services/storage/tests/resource_arm_storage_queue_test.go index 7f15ce810aa76..9a60448534965 100644 --- a/azurerm/internal/services/storage/tests/resource_arm_storage_queue_test.go +++ b/azurerm/internal/services/storage/tests/resource_arm_storage_queue_test.go @@ -226,14 +226,34 @@ resource "azurerm_storage_queue" "test" { } func testAccAzureRMStorageQueue_basicAzureADAuth(data acceptance.TestData) string { - template := testAccAzureRMStorageQueue_basic(data) return fmt.Sprintf(` provider "azurerm" { storage_use_azuread = true + features {} } -%s -`, template) +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestacc%s" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + account_tier = "Standard" + account_replication_type = "LRS" + + tags = { + environment = "staging" + } +} + +resource "azurerm_storage_queue" "test" { + name = "mysamplequeue-%d" + storage_account_name = azurerm_storage_account.test.name +} +`, data.RandomInteger, data.Locations.Primary, data.RandomString, data.RandomInteger) } func testAccAzureRMStorageQueue_requiresImport(data acceptance.TestData) string { From 00aaff23a22bb72e2d0fd71901dadd672b90b7a7 Mon Sep 17 00:00:00 2001 From: Yuping Wei <56525716+yupwei68@users.noreply.github.com> Date: Fri, 15 May 2020 07:28:01 +0800 Subject: [PATCH 101/104] `azurerm_api_management_diagnostic` - support required property `api_management_logger_id` (#6682) fix #6619 This will be a breaking change for it adds a required field "logger_id" === RUN TestAccAzureRMApiManagementDiagnostic_basic === PAUSE TestAccAzureRMApiManagementDiagnostic_basic === CONT TestAccAzureRMApiManagementDiagnostic_basic --- PASS: TestAccAzureRMApiManagementDiagnostic_basic (2498.17s) === RUN TestAccAzureRMApiManagementDiagnostic_update === PAUSE TestAccAzureRMApiManagementDiagnostic_update === CONT TestAccAzureRMApiManagementDiagnostic_update --- PASS: TestAccAzureRMApiManagementDiagnostic_update (2566.13s) === RUN TestAccAzureRMApiManagementDiagnostic_requiresImport === PAUSE TestAccAzureRMApiManagementDiagnostic_requiresImport === CONT TestAccAzureRMApiManagementDiagnostic_requiresImport --- PASS: TestAccAzureRMApiManagementDiagnostic_requiresImport (2330.79s) PASS (also fixes #6104) --- .../api_management_diagnostic_resource.go | 48 ++--- .../apimanagement/parse/apimanagement.go | 69 +++++++ .../apimanagement/parse/apimanagement_test.go | 169 ++++++++++++++++++ ...api_management_diagnostic_resource_test.go | 127 ++++++++++--- .../apimanagement/validate/apimanagement.go | 21 +++ .../r/api_management_diagnostic.html.markdown | 42 +++-- .../r/eventgrid_domain_topic.html.markdown | 2 +- 7 files changed, 424 insertions(+), 54 deletions(-) create mode 100644 azurerm/internal/services/apimanagement/parse/apimanagement.go create mode 100644 azurerm/internal/services/apimanagement/parse/apimanagement_test.go create mode 100644 azurerm/internal/services/apimanagement/validate/apimanagement.go diff --git a/azurerm/internal/services/apimanagement/api_management_diagnostic_resource.go b/azurerm/internal/services/apimanagement/api_management_diagnostic_resource.go index 20f99daab0171..6caf484963099 100644 --- a/azurerm/internal/services/apimanagement/api_management_diagnostic_resource.go +++ b/azurerm/internal/services/apimanagement/api_management_diagnostic_resource.go @@ -11,6 +11,9 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/apimanagement/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/apimanagement/validate" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -21,9 +24,11 @@ func resourceArmApiManagementDiagnostic() *schema.Resource { Read: resourceArmApiManagementDiagnosticRead, Update: resourceArmApiManagementDiagnosticCreateUpdate, Delete: resourceArmApiManagementDiagnosticDelete, - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, + + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.ApiManagementDiagnosticID(id) + return err + }), Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(30 * time.Minute), @@ -46,6 +51,12 @@ func resourceArmApiManagementDiagnostic() *schema.Resource { "api_management_name": azure.SchemaApiManagementName(), + "api_management_logger_id": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validate.ApiManagementLoggerID, + }, + "enabled": { Type: schema.TypeBool, Optional: true, @@ -78,7 +89,9 @@ func resourceArmApiManagementDiagnosticCreateUpdate(d *schema.ResourceData, meta } parameters := apimanagement.DiagnosticContract{ - DiagnosticContractProperties: &apimanagement.DiagnosticContractProperties{}, + DiagnosticContractProperties: &apimanagement.DiagnosticContractProperties{ + LoggerID: utils.String(d.Get("api_management_logger_id").(string)), + }, } if _, err := client.CreateOrUpdate(ctx, resourceGroup, serviceName, diagnosticId, parameters, ""); err != nil { @@ -90,7 +103,7 @@ func resourceArmApiManagementDiagnosticCreateUpdate(d *schema.ResourceData, meta return fmt.Errorf("retrieving Diagnostic %q (Resource Group %q / API Management Service %q): %+v", diagnosticId, resourceGroup, serviceName, err) } if resp.ID == nil { - return fmt.Errorf("Cannot read ID for Diagnostic %q (Resource Group %q / API Management Service %q)", diagnosticId, resourceGroup, serviceName) + return fmt.Errorf("reading ID for Diagnostic %q (Resource Group %q / API Management Service %q): ID is empty", diagnosticId, resourceGroup, serviceName) } d.SetId(*resp.ID) @@ -102,28 +115,26 @@ func resourceArmApiManagementDiagnosticRead(d *schema.ResourceData, meta interfa ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + diagnosticId, err := parse.ApiManagementDiagnosticID(d.Id()) if err != nil { return err } - resourceGroup := id.ResourceGroup - serviceName := id.Path["service"] - diagnosticId := id.Path["diagnostics"] - resp, err := client.Get(ctx, resourceGroup, serviceName, diagnosticId) + resp, err := client.Get(ctx, diagnosticId.ResourceGroup, diagnosticId.ServiceName, diagnosticId.Name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { - log.Printf("[DEBUG] Diagnostic %q (Resource Group %q / API Management Service %q) was not found - removing from state!", diagnosticId, resourceGroup, serviceName) + log.Printf("[DEBUG] Diagnostic %q (Resource Group %q / API Management Service %q) was not found - removing from state!", diagnosticId.Name, diagnosticId.ResourceGroup, diagnosticId.ServiceName) d.SetId("") return nil } - return fmt.Errorf("making Read request for Diagnostic %q (Resource Group %q / API Management Service %q): %+v", diagnosticId, resourceGroup, serviceName, err) + return fmt.Errorf("making Read request for Diagnostic %q (Resource Group %q / API Management Service %q): %+v", diagnosticId.Name, diagnosticId.ResourceGroup, diagnosticId.ServiceName, err) } d.Set("identifier", resp.Name) - d.Set("resource_group_name", resourceGroup) - d.Set("api_management_name", serviceName) + d.Set("resource_group_name", diagnosticId.ResourceGroup) + d.Set("api_management_name", diagnosticId.ServiceName) + d.Set("api_management_logger_id", resp.LoggerID) return nil } @@ -133,17 +144,14 @@ func resourceArmApiManagementDiagnosticDelete(d *schema.ResourceData, meta inter ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := azure.ParseAzureResourceID(d.Id()) + diagnosticId, err := parse.ApiManagementDiagnosticID(d.Id()) if err != nil { return err } - resourceGroup := id.ResourceGroup - serviceName := id.Path["service"] - diagnosticId := id.Path["diagnostics"] - if resp, err := client.Delete(ctx, resourceGroup, serviceName, diagnosticId, ""); err != nil { + if resp, err := client.Delete(ctx, diagnosticId.ResourceGroup, diagnosticId.ServiceName, diagnosticId.Name, ""); err != nil { if !utils.ResponseWasNotFound(resp) { - return fmt.Errorf("deleting Diagnostic %q (Resource Group %q / API Management Service %q): %+v", diagnosticId, resourceGroup, serviceName, err) + return fmt.Errorf("deleting Diagnostic %q (Resource Group %q / API Management Service %q): %+v", diagnosticId.Name, diagnosticId.ResourceGroup, diagnosticId.ServiceName, err) } } diff --git a/azurerm/internal/services/apimanagement/parse/apimanagement.go b/azurerm/internal/services/apimanagement/parse/apimanagement.go new file mode 100644 index 0000000000000..048d60a45ec15 --- /dev/null +++ b/azurerm/internal/services/apimanagement/parse/apimanagement.go @@ -0,0 +1,69 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type ApiManagementLoggerId struct { + ResourceGroup string + ServiceName string + Name string +} + +func ApiManagementLoggerID(input string) (*ApiManagementLoggerId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("parsing Api Management Logger ID %q: %+v", input, err) + } + + logger := ApiManagementLoggerId{ + ResourceGroup: id.ResourceGroup, + } + + if logger.ServiceName, err = id.PopSegment("service"); err != nil { + return nil, err + } + + if logger.Name, err = id.PopSegment("loggers"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &logger, nil +} + +type ApiManagementDiagnosticId struct { + ResourceGroup string + ServiceName string + Name string +} + +func ApiManagementDiagnosticID(input string) (*ApiManagementDiagnosticId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("parsing Api Management Diagnostic ID %q: %+v", input, err) + } + + diagnostic := ApiManagementDiagnosticId{ + ResourceGroup: id.ResourceGroup, + } + + if diagnostic.ServiceName, err = id.PopSegment("service"); err != nil { + return nil, err + } + + if diagnostic.Name, err = id.PopSegment("diagnostics"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &diagnostic, nil +} diff --git a/azurerm/internal/services/apimanagement/parse/apimanagement_test.go b/azurerm/internal/services/apimanagement/parse/apimanagement_test.go new file mode 100644 index 0000000000000..b60734df3c876 --- /dev/null +++ b/azurerm/internal/services/apimanagement/parse/apimanagement_test.go @@ -0,0 +1,169 @@ +package parse + +import "testing" + +func TestApiManagementLoggerID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *ApiManagementLoggerId + }{ + { + Name: "Empty", + Input: "", + Expected: nil, + }, + { + Name: "No Resource Groups Segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No Resource Groups Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/", + Expected: nil, + }, + { + Name: "Missing Service Name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/", + Expected: nil, + }, + { + Name: "Missing Logger", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1", + Expected: nil, + }, + { + Name: "Missing Logger Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1/loggers", + Expected: nil, + }, + { + Name: "Logger ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1/loggers/logger1", + Expected: &ApiManagementLoggerId{ + Name: "logger1", + ServiceName: "service1", + ResourceGroup: "resGroup1", + }, + }, + { + Name: "Wrong Casing", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1/Loggers/logger1", + Expected: nil, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := ApiManagementLoggerID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ServiceName != v.Expected.ServiceName { + t.Fatalf("Expected %q but got %q for Service Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} + +func TestApiManagementDiagnosticID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *ApiManagementDiagnosticId + }{ + { + Name: "Empty", + Input: "", + Expected: nil, + }, + { + Name: "No Resource Groups Segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No Resource Groups Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/", + Expected: nil, + }, + { + Name: "Missing Service Name", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/", + Expected: nil, + }, + { + Name: "Missing Diagnostic", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1", + Expected: nil, + }, + { + Name: "Missing Diagnostic Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1/diagnostics", + Expected: nil, + }, + { + Name: "Diagnostic ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1/diagnostics/diagnostic1", + Expected: &ApiManagementDiagnosticId{ + Name: "diagnostic1", + ServiceName: "service1", + ResourceGroup: "resGroup1", + }, + }, + { + Name: "Wrong Casing", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.ApiManagement/service/service1/Diagnostics/diagnostic1", + Expected: nil, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := ApiManagementDiagnosticID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ServiceName != v.Expected.ServiceName { + t.Fatalf("Expected %q but got %q for Service Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/apimanagement/tests/api_management_diagnostic_resource_test.go b/azurerm/internal/services/apimanagement/tests/api_management_diagnostic_resource_test.go index 2728778fcbc67..c11dc02228d52 100644 --- a/azurerm/internal/services/apimanagement/tests/api_management_diagnostic_resource_test.go +++ b/azurerm/internal/services/apimanagement/tests/api_management_diagnostic_resource_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/apimanagement/parse" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -30,6 +31,32 @@ func TestAccAzureRMApiManagementDiagnostic_basic(t *testing.T) { }) } +func TestAccAzureRMApiManagementDiagnostic_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_api_management_diagnostic", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMApiManagementDiagnosticDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMApiManagementDiagnostic_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementDiagnosticExists(data.ResourceName), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMApiManagementDiagnostic_update(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMApiManagementDiagnosticExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + func TestAccAzureRMApiManagementDiagnostic_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_api_management_diagnostic", "test") @@ -58,11 +85,11 @@ func testCheckAzureRMApiManagementDiagnosticDestroy(s *terraform.State) error { continue } - identifier := rs.Primary.Attributes["identifier"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - serviceName := rs.Primary.Attributes["api_management_name"] - - resp, err := client.Get(ctx, resourceGroup, serviceName, identifier) + diagnosticId, err := parse.ApiManagementDiagnosticID(rs.Primary.ID) + if err != nil { + return err + } + resp, err := client.Get(ctx, diagnosticId.ResourceGroup, diagnosticId.ServiceName, diagnosticId.Name) if err != nil { if !utils.ResponseWasNotFound(resp.Response) { @@ -85,35 +112,43 @@ func testCheckAzureRMApiManagementDiagnosticExists(resourceName string) resource return fmt.Errorf("Not found: %s", resourceName) } - identifier := rs.Primary.Attributes["identifier"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - serviceName := rs.Primary.Attributes["api_management_name"] + diagnosticId, err := parse.ApiManagementDiagnosticID(rs.Primary.ID) + if err != nil { + return err + } - resp, err := client.Get(ctx, resourceGroup, serviceName, identifier) + resp, err := client.Get(ctx, diagnosticId.ResourceGroup, diagnosticId.ServiceName, diagnosticId.Name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { - return fmt.Errorf("Bad: API Management Diagnostic %q (Resource Group %q / API Management Service %q) does not exist", identifier, resourceGroup, serviceName) + return fmt.Errorf("bad: API Management Diagnostic %q (Resource Group %q / API Management Service %q) does not exist", diagnosticId.Name, diagnosticId.ResourceGroup, diagnosticId.ServiceName) } - return fmt.Errorf("Bad: Get on apiManagementDiagnosticClient: %+v", err) + return fmt.Errorf("bad: Get on apiManagementDiagnosticClient: %+v", err) } return nil } } -func testAccAzureRMApiManagementDiagnostic_basic(data acceptance.TestData) string { +func testAccAzureRMApiManagementDiagnostic_template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} } resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" - location = "%s" + name = "acctestRG-%[1]d" + location = "%[2]s" +} + +resource "azurerm_application_insights" "test" { + name = "acctestappinsights-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + application_type = "web" } resource "azurerm_api_management" "test" { - name = "acctestAM-%d" + name = "acctestAM-%[1]d" location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name publisher_name = "pub1" @@ -121,13 +156,61 @@ resource "azurerm_api_management" "test" { sku_name = "Developer_1" } +resource "azurerm_api_management_logger" "test" { + name = "acctestapimnglogger-%[1]d" + api_management_name = azurerm_api_management.test.name + resource_group_name = azurerm_resource_group.test.name + + application_insights { + instrumentation_key = azurerm_application_insights.test.instrumentation_key + } +} +`, data.RandomInteger, data.Locations.Primary) +} + +func testAccAzureRMApiManagementDiagnostic_basic(data acceptance.TestData) string { + config := testAccAzureRMApiManagementDiagnostic_template(data) + return fmt.Sprintf(` +%s + resource "azurerm_api_management_diagnostic" "test" { - identifier = "applicationinsights" + identifier = "applicationinsights" + resource_group_name = azurerm_resource_group.test.name + api_management_name = azurerm_api_management.test.name + api_management_logger_id = azurerm_api_management_logger.test.id +} +`, config) +} + +func testAccAzureRMApiManagementDiagnostic_update(data acceptance.TestData) string { + config := testAccAzureRMApiManagementDiagnostic_template(data) + return fmt.Sprintf(` +%[1]s + +resource "azurerm_application_insights" "test2" { + name = "acctestappinsightsUpdate-%[2]d" + location = azurerm_resource_group.test.location resource_group_name = azurerm_resource_group.test.name + application_type = "web" +} + +resource "azurerm_api_management_logger" "test2" { + name = "acctestapimngloggerUpdate-%[2]d" api_management_name = azurerm_api_management.test.name - enabled = true + resource_group_name = azurerm_resource_group.test.name + + application_insights { + instrumentation_key = azurerm_application_insights.test2.instrumentation_key + } +} + +resource "azurerm_api_management_diagnostic" "test" { + identifier = "applicationinsights" + resource_group_name = azurerm_resource_group.test.name + api_management_name = azurerm_api_management.test.name + api_management_logger_id = azurerm_api_management_logger.test2.id } -`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +`, config, data.RandomInteger) } func testAccAzureRMApiManagementDiagnostic_requiresImport(data acceptance.TestData) string { @@ -136,10 +219,10 @@ func testAccAzureRMApiManagementDiagnostic_requiresImport(data acceptance.TestDa %s resource "azurerm_api_management_diagnostic" "import" { - identifier = azurerm_api_management_diagnostic.test.identifier - resource_group_name = azurerm_api_management_diagnostic.test.resource_group_name - api_management_name = azurerm_api_management_diagnostic.test.api_management_name - enabled = azurerm_api_management_diagnostic.test.enabled + identifier = azurerm_api_management_diagnostic.test.identifier + resource_group_name = azurerm_api_management_diagnostic.test.resource_group_name + api_management_name = azurerm_api_management_diagnostic.test.api_management_name + api_management_logger_id = azurerm_api_management_diagnostic.test.api_management_logger_id } `, template) } diff --git a/azurerm/internal/services/apimanagement/validate/apimanagement.go b/azurerm/internal/services/apimanagement/validate/apimanagement.go new file mode 100644 index 0000000000000..13ffe7e595432 --- /dev/null +++ b/azurerm/internal/services/apimanagement/validate/apimanagement.go @@ -0,0 +1,21 @@ +package validate + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/apimanagement/parse" +) + +func ApiManagementLoggerID(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return warnings, errors + } + + if _, err := parse.ApiManagementLoggerID(v); err != nil { + errors = append(errors, fmt.Errorf("can not parse %q as a Api Management Logger id: %v", k, err)) + } + + return warnings, errors +} diff --git a/website/docs/r/api_management_diagnostic.html.markdown b/website/docs/r/api_management_diagnostic.html.markdown index 7fd8e3af40762..37aede8b600ba 100644 --- a/website/docs/r/api_management_diagnostic.html.markdown +++ b/website/docs/r/api_management_diagnostic.html.markdown @@ -13,25 +13,45 @@ Manages an API Management Service Diagnostic. ## Example Usage ```hcl -resource "azurerm_resource_group" "test" { +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "example" { name = "example-resources" location = "West Europe" } -resource "azurerm_api_management" "test" { +resource "azurerm_application_insights" "example" { + name = "example-appinsights" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + application_type = "web" +} + +resource "azurerm_api_management" "example" { name = "example-apim" - location = azurerm_resource_group.test.location - resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name publisher_name = "My Company" publisher_email = "company@terraform.io" sku_name = "Developer_1" } +resource "azurerm_api_management_logger" "example" { + name = "example-apimlogger" + api_management_name = azurerm_api_management.example.name + resource_group_name = azurerm_resource_group.example.name + + application_insights { + instrumentation_key = azurerm_application_insights.example.instrumentation_key + } +} -resource "azurerm_api_management_diagnostic" "test" { - identifier = "applicationinsights" - resource_group_name = azurerm_resource_group.test.name - api_management_name = azurerm_api_management.test.name - enabled = true +resource "azurerm_api_management_diagnostic" "example" { + identifier = "applicationinsights" + resource_group_name = azurerm_resource_group.example.name + api_management_name = azurerm_api_management.example.name + api_management_logger_id = azurerm_api_management_logger.example.id } ``` @@ -45,7 +65,7 @@ The following arguments are supported: * `resource_group_name` - (Required) The Name of the Resource Group where the API Management Service exists. Changing this forces a new resource to be created. -* `enabled` - (Required) Indicates whether a Diagnostic should receive data or not. +* `api_management_logger_id` - (Required) The id of the target API Management Logger where the API Management Diagnostic should be saved. --- @@ -69,5 +89,5 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d API Management Diagnostics can be imported using the `resource id`, e.g. ```shell -terraform import azurerm_api_management_diagnostic.test /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.ApiManagement/service/instance1/diagnostics/applicationinsights +terraform import azurerm_api_management_diagnostic.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.ApiManagement/service/instance1/diagnostics/applicationinsights ``` diff --git a/website/docs/r/eventgrid_domain_topic.html.markdown b/website/docs/r/eventgrid_domain_topic.html.markdown index 1a1f45ede7dc9..53189127e20a1 100644 --- a/website/docs/r/eventgrid_domain_topic.html.markdown +++ b/website/docs/r/eventgrid_domain_topic.html.markdown @@ -63,4 +63,4 @@ EventGrid Domain Topics can be imported using the `resource id`, e.g. ```shell terraform import azurerm_eventgrid_domain_topic.topic1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.EventGrid/domains/domain1/topics/topic1 -``` \ No newline at end of file +``` From c8ec0d84e30227c1bfac0a94a439b2da08d12069 Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 14 May 2020 16:30:59 -0700 Subject: [PATCH 102/104] update CHANGELOG.md to include #6682 --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4e764ad0e4b1..edd10f0f28d62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ IMPROVEMENTS: * `azurerm_api_management` - support for configuring the Developer Portal [GH-6724] * `azurerm_api_management` - support for user assigned managed identities [GH-6783] * `azurerm_api_management` - support `key_vault_id` that do not have a version [GH-6723] +* `azurerm_api_management_diagnostic` - support required property `api_management_logger_id` [GH-6682] * `azurerm_application_gateway` - support for WAF policies [GH-6105] * `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] * `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] @@ -33,7 +34,7 @@ IMPROVEMENTS: * `azurerm_mssql_server` - add support for the `azuread_administrator` property [GH-6822] * `azurerm_postgres_server` - support for the `threat_detection_policy` property [GH-6721] * `azurerm_storage_account` - enable migration of `account_kind` from `Storage` to `StorageV2` [GH-6580] -* `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can no be updated [GH-6846] +* `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can now be updated [GH-6846] BUG FIXES: @@ -42,6 +43,7 @@ BUG FIXES: * Data Source: `azurerm_mysql_server` - remove `administrator_login_password` property as it is not returned from the api [GH-6865] * `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] * `azurerm_api_management` - only sending the `hostname_configuration` properties if they are not empty [GH-6850] +* `azurerm_api_management_diagnostic` - can now be provision again by supporting `api_management_logger_id` [GH-6682] * `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true [GH-6834] * `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] * `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] From 69e017588a2447071b52705ce4f7f6392f498327 Mon Sep 17 00:00:00 2001 From: tf-release-bot Date: Thu, 14 May 2020 23:38:37 +0000 Subject: [PATCH 103/104] v2.10.0 --- CHANGELOG.md | 86 ++++++++++++++++++++++++++-------------------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edd10f0f28d62..431eca7d601b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,59 +1,59 @@ -## 2.10.0 (Unreleased) +## 2.10.0 (May 14, 2020) DEPENDENCIES: -* updating `eventgrid` to `2020-04-01-preview` [GH-6837] -* updating `iothub` to `2019-03-22-preview` [GH-6875] +* updating `eventgrid` to `2020-04-01-preview` ([#6837](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6837)) +* updating `iothub` to `2019-03-22-preview` ([#6875](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6875)) FEATURES: -* **New Data Source:** `azurerm_eventhub` [GH-6841] -* **New Resource:** `azurerm_eventgrid_domain_topic` [GH-6859] +* **New Data Source:** `azurerm_eventhub` ([#6841](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6841)) +* **New Resource:** `azurerm_eventgrid_domain_topic` ([#6859](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6859)) IMPROVEMENTS: -* All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required [GH-6864] -* Data Source: `azurerm_virtual_machine` - export `identity` attribute [GH-6826] -* `azurerm_api_management` - support for configuring the Developer Portal [GH-6724] -* `azurerm_api_management` - support for user assigned managed identities [GH-6783] -* `azurerm_api_management` - support `key_vault_id` that do not have a version [GH-6723] -* `azurerm_api_management_diagnostic` - support required property `api_management_logger_id` [GH-6682] -* `azurerm_application_gateway` - support for WAF policies [GH-6105] -* `azurerm_app_service_environment` - support specifying explicit resource group [GH-6821] -* `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction [GH-6601] -* `azurerm_frontdoor` - expose the `header_frontdoor_id` attribute [GH-6916] -* `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier [GH-6844] -* `azurerm_mariadb_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6865] -* `azurerm_mariadb_server` - support for the `public_network_access_enabled` property [GH-6865] -* `azurerm_mariadb_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6865] +* All Data Sources: adding validation for the `resource_group_name` field to not be empty where it's Required ([#6864](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6864)) +* Data Source: `azurerm_virtual_machine` - export `identity` attribute ([#6826](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6826)) +* `azurerm_api_management` - support for configuring the Developer Portal ([#6724](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6724)) +* `azurerm_api_management` - support for user assigned managed identities ([#6783](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6783)) +* `azurerm_api_management` - support `key_vault_id` that do not have a version ([#6723](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6723)) +* `azurerm_api_management_diagnostic` - support required property `api_management_logger_id` ([#6682](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6682)) +* `azurerm_application_gateway` - support for WAF policies ([#6105](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6105)) +* `azurerm_app_service_environment` - support specifying explicit resource group ([#6821](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6821)) +* `azurerm_express_route_circuit` - de-provision and re-provision circuit when changing the bandwidth reduction ([#6601](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6601)) +* `azurerm_frontdoor` - expose the `header_frontdoor_id` attribute ([#6916](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6916)) +* `azurerm_log_analytics_workspace` - add support for `rentention_in_days` for Free Tier ([#6844](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6844)) +* `azurerm_mariadb_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors ([#6865](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6865)) +* `azurerm_mariadb_server` - support for the `public_network_access_enabled` property ([#6865](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6865)) +* `azurerm_mariadb_server` - all properties in the `storage_profile` block have been moved to the top level ([#6865](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6865)) * `azurerm_mariadb_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` -* `azurerm_mysql_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors [GH-6833] -* `azurerm_mysql_server` - support for the `public_network_access_enabled` property [GH-6833] -* `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level [GH-6833] -* `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` [GH-6833] -* `azurerm_mssql_server` - add support for the `azuread_administrator` property [GH-6822] -* `azurerm_postgres_server` - support for the `threat_detection_policy` property [GH-6721] -* `azurerm_storage_account` - enable migration of `account_kind` from `Storage` to `StorageV2` [GH-6580] -* `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can now be updated [GH-6846] +* `azurerm_mysql_server` - support for the `create_mode` property allowing the creation of replicas, point in time restores, and geo restors ([#6833](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6833)) +* `azurerm_mysql_server` - support for the `public_network_access_enabled` property ([#6833](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6833)) +* `azurerm_mysql_server` - all properties in the `storage_profile` block have been moved to the top level ([#6833](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6833)) +* `azurerm_mysql_server` - the following properties were renamed and changed to a boolean type: `ssl_enforcement` to `ssl_enforcement_enabled`, `geo_redundant_backup` to `geo_redundant_backup_enabled`, and `auto_grow` to `auto_grow_enabled` ([#6833](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6833)) +* `azurerm_mssql_server` - add support for the `azuread_administrator` property ([#6822](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6822)) +* `azurerm_postgres_server` - support for the `threat_detection_policy` property ([#6721](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6721)) +* `azurerm_storage_account` - enable migration of `account_kind` from `Storage` to `StorageV2` ([#6580](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6580)) +* `azurerm_windows_virtual_machine` - the `os_disk.disk_encryption_set_id` can now be updated ([#6846](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6846)) BUG FIXES: -* Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info [GH-6848] -* Data Source: `azurerm_security_group` - fixing crash where id is nil [GH-6910] -* Data Source: `azurerm_mysql_server` - remove `administrator_login_password` property as it is not returned from the api [GH-6865] -* `azurerm_api_management` - fixing a crash when `policy` is nil [GH-6862] -* `azurerm_api_management` - only sending the `hostname_configuration` properties if they are not empty [GH-6850] -* `azurerm_api_management_diagnostic` - can now be provision again by supporting `api_management_logger_id` [GH-6682] -* `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true [GH-6834] -* `azurerm_application_insights` - `retention_in_days` defaults to 90 [GH-6851] -* `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References [GH-6871] -* `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error [GH-6534] -* `azurerm_linux_virtual_machine_scale_set` - support for updating the `do_not_run_extensions_on_overprovisioned_machines` property [GH-6917] -* `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` [GH-6911] -* `azurerm_mariadb_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6865] -* `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled [GH-6833] -* `azurerm_role_assignment` - added evential consistency check to assignment creation [GH-6925] -* `azurerm_windows_virtual_machine_scale_set` - support for updating the `do_not_run_extensions_on_overprovisioned_machines` property [GH-6917] +* Data Source: `azurerm_automation_account` - using the ID of the Automation Account, rather than the ID of the Automation Account's Registration Info ([#6848](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6848)) +* Data Source: `azurerm_security_group` - fixing crash where id is nil ([#6910](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6910)) +* Data Source: `azurerm_mysql_server` - remove `administrator_login_password` property as it is not returned from the api ([#6865](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6865)) +* `azurerm_api_management` - fixing a crash when `policy` is nil ([#6862](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6862)) +* `azurerm_api_management` - only sending the `hostname_configuration` properties if they are not empty ([#6850](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6850)) +* `azurerm_api_management_diagnostic` - can now be provision again by supporting `api_management_logger_id` ([#6682](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6682)) +* `azurerm_api_management_named_value` - fix the non empty plan when `secret` is true ([#6834](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6834)) +* `azurerm_application_insights` - `retention_in_days` defaults to 90 ([#6851](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6851)) +* `azurerm_data_factory_trigger_schedule` - setting the `type` required for Pipeline References ([#6871](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6871)) +* `azurerm_kubernetes_cluster` - fixes the `InvalidLoadbalancerProfile` error ([#6534](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6534)) +* `azurerm_linux_virtual_machine_scale_set` - support for updating the `do_not_run_extensions_on_overprovisioned_machines` property ([#6917](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6917)) +* `azurerm_monitor_diagnostic_setting` - fix possible crash with `retention_policy` ([#6911](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6911)) +* `azurerm_mariadb_server` - the `storage_mb` property is now optional when `auto_grow` is enabled ([#6865](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6865)) +* `azurerm_mysql_server` - the `storage_mb` property is now optional when `auto_grow` is enabled ([#6833](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6833)) +* `azurerm_role_assignment` - added evential consistency check to assignment creation ([#6925](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6925)) +* `azurerm_windows_virtual_machine_scale_set` - support for updating the `do_not_run_extensions_on_overprovisioned_machines` property ([#6917](https://github.com/terraform-providers/terraform-provider-azurerm/issues/6917)) ## 2.9.0 (May 07, 2020) From 5e53ba67e213398fceb9554d4a4171017cf4d89c Mon Sep 17 00:00:00 2001 From: tf-release-bot Date: Thu, 14 May 2020 23:57:47 +0000 Subject: [PATCH 104/104] Cleanup after v2.10.0 release --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 431eca7d601b2..3f6054f21d9a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ +## 2.11.0 (Unreleased) ## 2.10.0 (May 14, 2020) DEPENDENCIES: