From 8c0d13420fd3de96826cdfe9c951807d5b5623cf Mon Sep 17 00:00:00 2001 From: Tony Fortes Ramos Date: Tue, 23 Oct 2018 13:16:16 +0200 Subject: [PATCH 01/14] azurerm_log_analytics_linked_service: Add client --- azurerm/config.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/azurerm/config.go b/azurerm/config.go index 420af3f3bd7f..58351536b4a0 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -108,7 +108,6 @@ type ArmClient struct { eventHubConsumerGroupClient eventhub.ConsumerGroupsClient eventHubNamespacesClient eventhub.NamespacesClient - workspacesClient operationalinsights.WorkspacesClient solutionsClient operationsmanagement.SolutionsClient redisClient redis.Client @@ -197,6 +196,10 @@ type ArmClient struct { keyVaultClient keyvault.VaultsClient keyVaultManagementClient keyVault.BaseClient + // LogServices + linkedServicesClient operationalinsights.LinkedServicesClient + workspacesClient operationalinsights.WorkspacesClient + // Logic logicWorkflowsClient logic.WorkflowsClient @@ -996,6 +999,10 @@ func (c *ArmClient) registerOperationalInsightsClients(endpoint, subscriptionId solutionsClient := operationsmanagement.NewSolutionsClientWithBaseURI(endpoint, subscriptionId, "Microsoft.OperationsManagement", "solutions", "testing") c.configureClient(&solutionsClient.Client, auth) c.solutionsClient = solutionsClient + + lsClient := operationalinsights.NewLinkedServicesClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&lsClient.Client, auth) + c.linkedServicesClient = lsClient } func (c *ArmClient) registerRecoveryServiceClients(endpoint, subscriptionId string, auth autorest.Authorizer) { From ec496afdede5c7bcede0504a8c205e76347fc5c0 Mon Sep 17 00:00:00 2001 From: Tony Fortes Ramos Date: Tue, 23 Oct 2018 13:17:05 +0200 Subject: [PATCH 02/14] azurerm_log_analytics_linked_service: Add linked service resource --- azurerm/provider.go | 197 +++++++++--------- ...source_arm_log_analytics_linked_service.go | 178 ++++++++++++++++ 2 files changed, 277 insertions(+), 98 deletions(-) create mode 100644 azurerm/resource_arm_log_analytics_linked_service.go diff --git a/azurerm/provider.go b/azurerm/provider.go index afb1c3b2195e..927955bfb974 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -130,104 +130,105 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ - "azurerm_azuread_application": resourceArmActiveDirectoryApplication(), - "azurerm_azuread_service_principal": resourceArmActiveDirectoryServicePrincipal(), - "azurerm_azuread_service_principal_password": resourceArmActiveDirectoryServicePrincipalPassword(), - "azurerm_api_management": resourceArmApiManagementService(), - "azurerm_application_gateway": resourceArmApplicationGateway(), - "azurerm_application_insights": resourceArmApplicationInsights(), - "azurerm_application_security_group": resourceArmApplicationSecurityGroup(), - "azurerm_app_service": resourceArmAppService(), - "azurerm_app_service_plan": resourceArmAppServicePlan(), - "azurerm_app_service_active_slot": resourceArmAppServiceActiveSlot(), - "azurerm_app_service_custom_hostname_binding": resourceArmAppServiceCustomHostnameBinding(), - "azurerm_app_service_slot": resourceArmAppServiceSlot(), - "azurerm_automation_account": resourceArmAutomationAccount(), - "azurerm_automation_credential": resourceArmAutomationCredential(), - "azurerm_automation_dsc_configuration": resourceArmAutomationDscConfiguration(), - "azurerm_automation_dsc_nodeconfiguration": resourceArmAutomationDscNodeConfiguration(), - "azurerm_automation_module": resourceArmAutomationModule(), - "azurerm_automation_runbook": resourceArmAutomationRunbook(), - "azurerm_automation_schedule": resourceArmAutomationSchedule(), - "azurerm_autoscale_setting": resourceArmAutoScaleSetting(), - "azurerm_availability_set": resourceArmAvailabilitySet(), - "azurerm_cdn_endpoint": resourceArmCdnEndpoint(), - "azurerm_cdn_profile": resourceArmCdnProfile(), - "azurerm_cognitive_account": resourceArmCognitiveAccount(), - "azurerm_container_registry": resourceArmContainerRegistry(), - "azurerm_container_service": resourceArmContainerService(), - "azurerm_container_group": resourceArmContainerGroup(), - "azurerm_cosmosdb_account": resourceArmCosmosDBAccount(), - "azurerm_databricks_workspace": resourceArmDatabricksWorkspace(), - "azurerm_data_lake_analytics_account": resourceArmDataLakeAnalyticsAccount(), - "azurerm_data_lake_analytics_firewall_rule": resourceArmDataLakeAnalyticsFirewallRule(), - "azurerm_data_lake_store": resourceArmDataLakeStore(), - "azurerm_data_lake_store_file": resourceArmDataLakeStoreFile(), - "azurerm_data_lake_store_firewall_rule": resourceArmDataLakeStoreFirewallRule(), - "azurerm_dev_test_lab": resourceArmDevTestLab(), - "azurerm_dev_test_policy": resourceArmDevTestPolicy(), - "azurerm_dev_test_linux_virtual_machine": resourceArmDevTestLinuxVirtualMachine(), - "azurerm_dev_test_virtual_network": resourceArmDevTestVirtualNetwork(), - "azurerm_dev_test_windows_virtual_machine": resourceArmDevTestWindowsVirtualMachine(), - "azurerm_dns_a_record": resourceArmDnsARecord(), - "azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(), - "azurerm_dns_caa_record": resourceArmDnsCaaRecord(), - "azurerm_dns_cname_record": resourceArmDnsCNameRecord(), - "azurerm_dns_mx_record": resourceArmDnsMxRecord(), - "azurerm_dns_ns_record": resourceArmDnsNsRecord(), - "azurerm_dns_ptr_record": resourceArmDnsPtrRecord(), - "azurerm_dns_srv_record": resourceArmDnsSrvRecord(), - "azurerm_dns_txt_record": resourceArmDnsTxtRecord(), - "azurerm_dns_zone": resourceArmDnsZone(), - "azurerm_eventgrid_topic": resourceArmEventGridTopic(), - "azurerm_eventhub": resourceArmEventHub(), - "azurerm_eventhub_authorization_rule": resourceArmEventHubAuthorizationRule(), - "azurerm_eventhub_consumer_group": resourceArmEventHubConsumerGroup(), - "azurerm_eventhub_namespace": resourceArmEventHubNamespace(), - "azurerm_eventhub_namespace_authorization_rule": resourceArmEventHubNamespaceAuthorizationRule(), - "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), - "azurerm_express_route_circuit_authorization": resourceArmExpressRouteCircuitAuthorization(), - "azurerm_express_route_circuit_peering": resourceArmExpressRouteCircuitPeering(), - "azurerm_firewall": resourceArmFirewall(), - "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), - "azurerm_function_app": resourceArmFunctionApp(), - "azurerm_image": resourceArmImage(), - "azurerm_iothub": resourceArmIotHub(), - "azurerm_key_vault": resourceArmKeyVault(), - "azurerm_key_vault_access_policy": resourceArmKeyVaultAccessPolicy(), - "azurerm_key_vault_certificate": resourceArmKeyVaultCertificate(), - "azurerm_key_vault_key": resourceArmKeyVaultKey(), - "azurerm_key_vault_secret": resourceArmKeyVaultSecret(), - "azurerm_kubernetes_cluster": resourceArmKubernetesCluster(), - "azurerm_lb": resourceArmLoadBalancer(), - "azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(), - "azurerm_lb_nat_rule": resourceArmLoadBalancerNatRule(), - "azurerm_lb_nat_pool": resourceArmLoadBalancerNatPool(), - "azurerm_lb_probe": resourceArmLoadBalancerProbe(), - "azurerm_lb_rule": resourceArmLoadBalancerRule(), - "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), - "azurerm_log_analytics_solution": resourceArmLogAnalyticsSolution(), - "azurerm_log_analytics_workspace": resourceArmLogAnalyticsWorkspace(), - "azurerm_logic_app_action_custom": resourceArmLogicAppActionCustom(), - "azurerm_logic_app_action_http": resourceArmLogicAppActionHTTP(), - "azurerm_logic_app_trigger_custom": resourceArmLogicAppTriggerCustom(), - "azurerm_logic_app_trigger_http_request": resourceArmLogicAppTriggerHttpRequest(), - "azurerm_logic_app_trigger_recurrence": resourceArmLogicAppTriggerRecurrence(), - "azurerm_logic_app_workflow": resourceArmLogicAppWorkflow(), - "azurerm_managed_disk": resourceArmManagedDisk(), - "azurerm_management_lock": resourceArmManagementLock(), - "azurerm_management_group": resourceArmManagementGroup(), - "azurerm_metric_alertrule": resourceArmMetricAlertRule(), - "azurerm_monitor_action_group": resourceArmMonitorActionGroup(), - "azurerm_monitor_activity_log_alert": resourceArmMonitorActivityLogAlert(), - "azurerm_monitor_log_profile": resourceArmMonitorLogProfile(), - "azurerm_monitor_metric_alert": resourceArmMonitorMetricAlert(), - "azurerm_mysql_configuration": resourceArmMySQLConfiguration(), - "azurerm_mysql_database": resourceArmMySqlDatabase(), - "azurerm_mysql_firewall_rule": resourceArmMySqlFirewallRule(), - "azurerm_mysql_server": resourceArmMySqlServer(), - "azurerm_mysql_virtual_network_rule": resourceArmMySqlVirtualNetworkRule(), - "azurerm_network_interface": resourceArmNetworkInterface(), + "azurerm_azuread_application": resourceArmActiveDirectoryApplication(), + "azurerm_azuread_service_principal": resourceArmActiveDirectoryServicePrincipal(), + "azurerm_azuread_service_principal_password": resourceArmActiveDirectoryServicePrincipalPassword(), + "azurerm_api_management": resourceArmApiManagementService(), + "azurerm_application_gateway": resourceArmApplicationGateway(), + "azurerm_application_insights": resourceArmApplicationInsights(), + "azurerm_application_security_group": resourceArmApplicationSecurityGroup(), + "azurerm_app_service": resourceArmAppService(), + "azurerm_app_service_plan": resourceArmAppServicePlan(), + "azurerm_app_service_active_slot": resourceArmAppServiceActiveSlot(), + "azurerm_app_service_custom_hostname_binding": resourceArmAppServiceCustomHostnameBinding(), + "azurerm_app_service_slot": resourceArmAppServiceSlot(), + "azurerm_automation_account": resourceArmAutomationAccount(), + "azurerm_automation_credential": resourceArmAutomationCredential(), + "azurerm_automation_dsc_configuration": resourceArmAutomationDscConfiguration(), + "azurerm_automation_dsc_nodeconfiguration": resourceArmAutomationDscNodeConfiguration(), + "azurerm_automation_module": resourceArmAutomationModule(), + "azurerm_automation_runbook": resourceArmAutomationRunbook(), + "azurerm_automation_schedule": resourceArmAutomationSchedule(), + "azurerm_autoscale_setting": resourceArmAutoScaleSetting(), + "azurerm_availability_set": resourceArmAvailabilitySet(), + "azurerm_cdn_endpoint": resourceArmCdnEndpoint(), + "azurerm_cdn_profile": resourceArmCdnProfile(), + "azurerm_cognitive_account": resourceArmCognitiveAccount(), + "azurerm_container_registry": resourceArmContainerRegistry(), + "azurerm_container_service": resourceArmContainerService(), + "azurerm_container_group": resourceArmContainerGroup(), + "azurerm_cosmosdb_account": resourceArmCosmosDBAccount(), + "azurerm_databricks_workspace": resourceArmDatabricksWorkspace(), + "azurerm_data_lake_analytics_account": resourceArmDataLakeAnalyticsAccount(), + "azurerm_data_lake_analytics_firewall_rule": resourceArmDataLakeAnalyticsFirewallRule(), + "azurerm_data_lake_store": resourceArmDataLakeStore(), + "azurerm_data_lake_store_file": resourceArmDataLakeStoreFile(), + "azurerm_data_lake_store_firewall_rule": resourceArmDataLakeStoreFirewallRule(), + "azurerm_dev_test_lab": resourceArmDevTestLab(), + "azurerm_dev_test_policy": resourceArmDevTestPolicy(), + "azurerm_dev_test_linux_virtual_machine": resourceArmDevTestLinuxVirtualMachine(), + "azurerm_dev_test_virtual_network": resourceArmDevTestVirtualNetwork(), + "azurerm_dev_test_windows_virtual_machine": resourceArmDevTestWindowsVirtualMachine(), + "azurerm_dns_a_record": resourceArmDnsARecord(), + "azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(), + "azurerm_dns_caa_record": resourceArmDnsCaaRecord(), + "azurerm_dns_cname_record": resourceArmDnsCNameRecord(), + "azurerm_dns_mx_record": resourceArmDnsMxRecord(), + "azurerm_dns_ns_record": resourceArmDnsNsRecord(), + "azurerm_dns_ptr_record": resourceArmDnsPtrRecord(), + "azurerm_dns_srv_record": resourceArmDnsSrvRecord(), + "azurerm_dns_txt_record": resourceArmDnsTxtRecord(), + "azurerm_dns_zone": resourceArmDnsZone(), + "azurerm_eventgrid_topic": resourceArmEventGridTopic(), + "azurerm_eventhub": resourceArmEventHub(), + "azurerm_eventhub_authorization_rule": resourceArmEventHubAuthorizationRule(), + "azurerm_eventhub_consumer_group": resourceArmEventHubConsumerGroup(), + "azurerm_eventhub_namespace": resourceArmEventHubNamespace(), + "azurerm_eventhub_namespace_authorization_rule": resourceArmEventHubNamespaceAuthorizationRule(), + "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), + "azurerm_express_route_circuit_authorization": resourceArmExpressRouteCircuitAuthorization(), + "azurerm_express_route_circuit_peering": resourceArmExpressRouteCircuitPeering(), + "azurerm_firewall": resourceArmFirewall(), + "azurerm_firewall_network_rule_collection": resourceArmFirewallNetworkRuleCollection(), + "azurerm_function_app": resourceArmFunctionApp(), + "azurerm_image": resourceArmImage(), + "azurerm_iothub": resourceArmIotHub(), + "azurerm_key_vault": resourceArmKeyVault(), + "azurerm_key_vault_access_policy": resourceArmKeyVaultAccessPolicy(), + "azurerm_key_vault_certificate": resourceArmKeyVaultCertificate(), + "azurerm_key_vault_key": resourceArmKeyVaultKey(), + "azurerm_key_vault_secret": resourceArmKeyVaultSecret(), + "azurerm_kubernetes_cluster": resourceArmKubernetesCluster(), + "azurerm_lb": resourceArmLoadBalancer(), + "azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(), + "azurerm_lb_nat_rule": resourceArmLoadBalancerNatRule(), + "azurerm_lb_nat_pool": resourceArmLoadBalancerNatPool(), + "azurerm_lb_probe": resourceArmLoadBalancerProbe(), + "azurerm_lb_rule": resourceArmLoadBalancerRule(), + "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), + "azurerm_log_analytics_linked_service": resourceArmLogAnalyticsLinkedService(), + "azurerm_log_analytics_solution": resourceArmLogAnalyticsSolution(), + "azurerm_log_analytics_workspace": resourceArmLogAnalyticsWorkspace(), + "azurerm_logic_app_action_custom": resourceArmLogicAppActionCustom(), + "azurerm_logic_app_action_http": resourceArmLogicAppActionHTTP(), + "azurerm_logic_app_trigger_custom": resourceArmLogicAppTriggerCustom(), + "azurerm_logic_app_trigger_http_request": resourceArmLogicAppTriggerHttpRequest(), + "azurerm_logic_app_trigger_recurrence": resourceArmLogicAppTriggerRecurrence(), + "azurerm_logic_app_workflow": resourceArmLogicAppWorkflow(), + "azurerm_managed_disk": resourceArmManagedDisk(), + "azurerm_management_lock": resourceArmManagementLock(), + "azurerm_management_group": resourceArmManagementGroup(), + "azurerm_metric_alertrule": resourceArmMetricAlertRule(), + "azurerm_monitor_action_group": resourceArmMonitorActionGroup(), + "azurerm_monitor_activity_log_alert": resourceArmMonitorActivityLogAlert(), + "azurerm_monitor_log_profile": resourceArmMonitorLogProfile(), + "azurerm_monitor_metric_alert": resourceArmMonitorMetricAlert(), + "azurerm_mysql_configuration": resourceArmMySQLConfiguration(), + "azurerm_mysql_database": resourceArmMySqlDatabase(), + "azurerm_mysql_firewall_rule": resourceArmMySqlFirewallRule(), + "azurerm_mysql_server": resourceArmMySqlServer(), + "azurerm_mysql_virtual_network_rule": resourceArmMySqlVirtualNetworkRule(), + "azurerm_network_interface": resourceArmNetworkInterface(), "azurerm_network_interface_application_gateway_backend_address_pool_association": resourceArmNetworkInterfaceApplicationGatewayBackendAddressPoolAssociation(), "azurerm_network_interface_backend_address_pool_association": resourceArmNetworkInterfaceBackendAddressPoolAssociation(), "azurerm_network_interface_nat_rule_association": resourceArmNetworkInterfaceNatRuleAssociation(), diff --git a/azurerm/resource_arm_log_analytics_linked_service.go b/azurerm/resource_arm_log_analytics_linked_service.go new file mode 100644 index 000000000000..611c35e4968a --- /dev/null +++ b/azurerm/resource_arm_log_analytics_linked_service.go @@ -0,0 +1,178 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights" + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmLogAnalyticsLinkedService() *schema.Resource { + return &schema.Resource{ + Create: resourceArmLogAnalyticsLinkedServiceCreateUpdate, + Read: resourceArmLogAnalyticsLinkedServiceRead, + Update: resourceArmLogAnalyticsLinkedServiceCreateUpdate, + Delete: resourceArmLogAnalyticsLinkedServiceDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "resource_group_name": resourceGroupNameDiffSuppressSchema(), + + "workspace_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "linked_service_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: "automation", + }, + + "linked_service_properties": { + Type: schema.TypeMap, + Required: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "resource_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + }, + }, + + "tags": tagsSchema(), + + // Exported properties + "name": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceArmLogAnalyticsLinkedServiceCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).linkedServicesClient + ctx := meta.(*ArmClient).StopContext + log.Printf("[INFO] preparing arguments for AzureRM Log Analytics linked services creation.") + + resGroup := d.Get("resource_group_name").(string) + + workspaceName := d.Get("workspace_name").(string) + lsName := d.Get("linked_service_name").(string) + + props := d.Get("linked_service_properties").(map[string]interface{}) + resourceID := props["resource_id"].(string) + + tags := d.Get("tags").(map[string]interface{}) + + parameters := operationalinsights.LinkedService{ + // Name: &name, + Tags: expandTags(tags), + LinkedServiceProperties: &operationalinsights.LinkedServiceProperties{ + ResourceID: &resourceID, + }, + } + + _, err := client.CreateOrUpdate(ctx, resGroup, workspaceName, lsName, parameters) + if err != nil { + return err + } + + read, err := client.Get(ctx, resGroup, workspaceName, lsName) + if err != nil { + return err + } + + if read.ID == nil { + return fmt.Errorf("Cannot read Log Analytics Linked Service '%s' (resource group %s) ID", lsName, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmLogAnalyticsLinkedServiceRead(d, meta) + +} + +func resourceArmLogAnalyticsLinkedServiceRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).linkedServicesClient + ctx := meta.(*ArmClient).StopContext + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + workspaceName := id.Path["workspaces"] + lsName := id.Path["linkedservices"] + + resp, err := client.Get(ctx, resGroup, workspaceName, lsName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return nil + } + return fmt.Errorf("Error making Read request on AzureRM Log Analytics Linked Service '%s': %+v", lsName, err) + } + if resp.ID == nil { + d.SetId("") + return nil + } + + d.Set("name", *resp.Name) + d.Set("resource_group_name", resGroup) + d.Set("workspace_name", workspaceName) + d.Set("linked_service_name", lsName) + + linkedServiceProperties := flattenLogAnalyticsLinkedServiceProperties(resp.LinkedServiceProperties) + if err := d.Set("linked_service_properties", linkedServiceProperties); err != nil { + return fmt.Errorf("Error flattening Log Analytics Linked Service Properties: %+v", err) + } + + flattenAndSetTags(d, resp.Tags) + return nil +} + +func flattenLogAnalyticsLinkedServiceProperties(input *operationalinsights.LinkedServiceProperties) interface{} { + properties := make(map[string]interface{}, 0) + + // resource id linked service + if resourceID := input.ResourceID; resourceID != nil { + properties["resource_id"] = interface{}(*resourceID) + } + + return interface{}(properties) +} + +func resourceArmLogAnalyticsLinkedServiceDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).linkedServicesClient + ctx := meta.(*ArmClient).StopContext + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + workspaceName := id.Path["workspaces"] + lsName := id.Path["linkedservices"] + + resp, err := client.Delete(ctx, resGroup, workspaceName, lsName) + + if err != nil { + if utils.ResponseWasNotFound(resp) { + return nil + } + + return fmt.Errorf("Error issuing AzureRM delete request for Log Analytics Linked Service '%s': %+v", lsName, err) + } + + return nil +} From 4ac5edf80673f629ce97a0f92ddabf96f8005ece Mon Sep 17 00:00:00 2001 From: Tony Fortes Ramos Date: Tue, 23 Oct 2018 23:30:34 +0200 Subject: [PATCH 03/14] azurerm_log_analytics_linked_service: add acceptance tests --- ...e_arm_log_analytics_linked_service_test.go | 202 ++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 azurerm/resource_arm_log_analytics_linked_service_test.go diff --git a/azurerm/resource_arm_log_analytics_linked_service_test.go b/azurerm/resource_arm_log_analytics_linked_service_test.go new file mode 100644 index 000000000000..889ac17ce7b2 --- /dev/null +++ b/azurerm/resource_arm_log_analytics_linked_service_test.go @@ -0,0 +1,202 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMLogAnalyticsLinkedService_requiredOnly(t *testing.T) { + resourceName := "azurerm_log_analytics_linked_service.test" + ri := acctest.RandInt() + config := testAccAzureRMLogAnalyticsLinkedServiceRequiredOnly(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMLogAnalyticsLinkedServiceDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLogAnalyticsLinkedServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("acctestworkspace-%d/Automation", ri)), + resource.TestCheckResourceAttr(resourceName, "workspace_name", fmt.Sprintf("acctestworkspace-%d", ri)), + resource.TestCheckResourceAttr(resourceName, "linked_service_name", "automation"), + ), + }, + }, + }) +} + +func TestAccAzureRMLogAnalyticsLinkedService_optionalArguments(t *testing.T) { + resourceName := "azurerm_log_analytics_linked_service.test" + ri := acctest.RandInt() + config := testAccAzureRMLogAnalyticsLinkedServiceOptionalArguments(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMLogAnalyticsLinkedServiceDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLogAnalyticsLinkedServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "linked_service_name", "automation"), + ), + }, + }, + }) +} + +func testCheckAzureRMLogAnalyticsLinkedServiceDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).linkedServicesClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_log_analytics_linked_service" { + continue + } + + resourceGroup := rs.Primary.Attributes["resource_group_name"] + workspaceName := rs.Primary.Attributes["workspace_name"] + lsName := rs.Primary.Attributes["linked_service_name"] + + resp, err := conn.Get(ctx, resourceGroup, workspaceName, lsName) + + if err != nil { + return nil + } + + if resp.ID == nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Log Analytics Linked Service still exists:\n%#v", resp) + } + } + + return nil +} + +func testCheckAzureRMLogAnalyticsLinkedServiceExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + workspaceName := rs.Primary.Attributes["workspace_name"] + lsName := rs.Primary.Attributes["linked_service_name"] + name := rs.Primary.Attributes["name"] + + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for Log Analytics Linked Service: '%s'", name) + } + + conn := testAccProvider.Meta().(*ArmClient).linkedServicesClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + resp, err := conn.Get(ctx, resourceGroup, workspaceName, lsName) + if err != nil { + return fmt.Errorf("Bad: Get on Log Analytics Linked Service Client: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Log Analytics Linked Service '%s' (resource group: '%s') does not exist", name, resourceGroup) + } + + return nil + } +} + +func testAccAzureRMLogAnalyticsLinkedServiceRequiredOnly(rInt int, location string) string { + return fmt.Sprintf(` + resource "azurerm_resource_group" "test" { + name = "acctestresourcegroup-%d" + location = "%v" + } + + resource "azurerm_automation_account" "test" { + name = "acctestautomation-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + + sku { + name = "Basic" + } + + tags { + environment = "development" + } + } + + resource "azurerm_log_analytics_workspace" "test" { + name = "acctestworkspace-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "PerGB2018" + retention_in_days = 30 + } + + resource "azurerm_log_analytics_linked_service" "test" { + resource_group_name = "${azurerm_resource_group.test.name}" + workspace_name = "${azurerm_log_analytics_workspace.test.name}" + + linked_service_properties { + resource_id = "${azurerm_automation_account.test.id}" + } + } + +`, rInt, location, rInt, rInt) +} + +func testAccAzureRMLogAnalyticsLinkedServiceOptionalArguments(rInt int, location string) string { + return fmt.Sprintf(` + resource "azurerm_resource_group" "test" { + name = "acctestresourcegroup-%d" + location = "%v" + } + + resource "azurerm_automation_account" "test" { + name = "acctestautomation-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + + sku { + name = "Basic" + } + + tags { + environment = "development" + } + } + + resource "azurerm_log_analytics_workspace" "test" { + name = "acctestworkspace-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "PerGB2018" + retention_in_days = 30 + } + + resource "azurerm_log_analytics_linked_service" "test" { + resource_group_name = "${azurerm_resource_group.test.name}" + workspace_name = "${azurerm_log_analytics_workspace.test.name}" + linked_service_name = "automation" + + linked_service_properties { + resource_id = "${azurerm_automation_account.test.id}" + } + } + +`, rInt, location, rInt, rInt) +} From 053cf1544ab5a8682e9473f40dac54fbdd784ebf Mon Sep 17 00:00:00 2001 From: Tony Fortes Ramos Date: Wed, 24 Oct 2018 00:26:10 +0200 Subject: [PATCH 04/14] azurerm_log_analytics_linked_service: add import tests --- ...t_arm_log_analytics_linked_service_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 azurerm/import_arm_log_analytics_linked_service_test.go diff --git a/azurerm/import_arm_log_analytics_linked_service_test.go b/azurerm/import_arm_log_analytics_linked_service_test.go new file mode 100644 index 000000000000..d83e26c1329d --- /dev/null +++ b/azurerm/import_arm_log_analytics_linked_service_test.go @@ -0,0 +1,56 @@ +package azurerm + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMLogAnalyticsLinkedService_importRequiredOnly(t *testing.T) { + resourceName := "azurerm_log_analytics_linked_service.test" + + ri := acctest.RandInt() + config := testAccAzureRMLogAnalyticsLinkedServiceRequiredOnly(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMLogAnalyticsLinkedServiceDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMLogAnalyticsLinkedService_importOptionalArguments(t *testing.T) { + resourceName := "azurerm_log_analytics_linked_service.test" + + ri := acctest.RandInt() + config := testAccAzureRMLogAnalyticsLinkedServiceOptionalArguments(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMLogAnalyticsLinkedServiceDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} From 94f966795cc1a49c7976d3373a03f8b39a598896 Mon Sep 17 00:00:00 2001 From: Tony Fortes Ramos Date: Wed, 24 Oct 2018 00:48:34 +0200 Subject: [PATCH 05/14] azurerm_log_analytics_linked_service: add documentation --- website/azurerm.erb | 4 + ...log_analytics_linked_service.html.markdown | 86 +++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 website/docs/r/log_analytics_linked_service.html.markdown diff --git a/website/azurerm.erb b/website/azurerm.erb index 3ad2f05d931e..b3117efbf304 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -993,6 +993,10 @@ > OMS Resources