func testAccCheckAzureDataDiskDestroy(s *terraform.State) error { vmDiskClient := testAccProvider.Meta().(*Client).vmDiskClient for _, rs := range s.RootModule().Resources { if rs.Type != "azure_data_disk" { continue } if rs.Primary.ID == "" { return fmt.Errorf("No Disk ID is set") } vm := rs.Primary.Attributes["virtual_machine"] lun, err := strconv.Atoi(rs.Primary.Attributes["lun"]) if err != nil { return err } _, err = vmDiskClient.GetDataDisk(vm, vm, vm, lun) if err == nil { return fmt.Errorf("Data disk %s still exists", rs.Primary.ID) } if !management.IsResourceNotFoundError(err) { return err } } return nil }
func testAccCheckAzureDnsServerDestroy(s *terraform.State) error { vnetClient := testAccProvider.Meta().(*Client).vnetClient for _, resource := range s.RootModule().Resources { if resource.Type != "azure_dns_server" { continue } if resource.Primary.ID == "" { return fmt.Errorf("No DNS Server ID is set.") } netConf, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { // This is desirable - if there is no network config there can't be any DNS Servers if management.IsResourceNotFoundError(err) { continue } return fmt.Errorf("Error retrieving networking configuration from Azure: %s", err) } for _, dns := range netConf.Configuration.DNS.DNSServers { if dns.Name == resource.Primary.ID { return fmt.Errorf("Azure DNS Server still exists.") } } } return nil }
func testAccCheckAzureInstanceDestroyed(hostedServiceName string) resource.TestCheckFunc { return func(s *terraform.State) error { hostedServiceClient := testAccProvider.Meta().(*Client).hostedServiceClient for _, rs := range s.RootModule().Resources { if rs.Type != "azure_instance" { continue } if rs.Primary.ID == "" { return fmt.Errorf("No instance ID is set") } // if not hosted service was provided; it means that we expect it // to be identical with the name of the instance; which is in the ID. var serviceName string if hostedServiceName == "" { serviceName = rs.Primary.ID } else { serviceName = hostedServiceName } _, err := hostedServiceClient.GetHostedService(serviceName) if err == nil { return fmt.Errorf("Instance %s still exists", rs.Primary.ID) } if !management.IsResourceNotFoundError(err) { return err } } return nil } }
func resourceAzureDataDiskRead(d *schema.ResourceData, meta interface{}) error { vmDiskClient := meta.(*Client).vmDiskClient lun := d.Get("lun").(int) vm := d.Get("virtual_machine").(string) log.Printf("[DEBUG] Retrieving data disk: %s", d.Id()) datadisk, err := vmDiskClient.GetDataDisk(vm, vm, vm, lun) if err != nil { if management.IsResourceNotFoundError(err) { d.SetId("") return nil } return fmt.Errorf("Error retrieving data disk %s: %s", d.Id(), err) } d.Set("name", datadisk.DiskName) d.Set("label", datadisk.DiskLabel) d.Set("lun", datadisk.Lun) d.Set("size", datadisk.LogicalDiskSizeInGB) d.Set("caching", datadisk.HostCaching) d.Set("media_link", datadisk.MediaLink) log.Printf("[DEBUG] Retrieving disk: %s", d.Id()) disk, err := vmDiskClient.GetDisk(d.Id()) if err != nil { return fmt.Errorf("Error retrieving disk %s: %s", d.Id(), err) } d.Set("virtual_machine", disk.AttachedTo.RoleName) return nil }
// resourceAzureHostedServiceRead does all the necessary API calls // to read the state of a hosted service from Azure. func resourceAzureHostedServiceRead(d *schema.ResourceData, meta interface{}) error { hostedServiceClient := meta.(*Client).hostedServiceClient log.Println("[INFO] Querying for hosted service info.") serviceName := d.Get("name").(string) hostedService, err := hostedServiceClient.GetHostedService(serviceName) if err != nil { if management.IsResourceNotFoundError(err) { // it means the hosted service was deleted in the meantime, // so we must remove it here: d.SetId("") return nil } else { return fmt.Errorf("Failed to get hosted service: %s", err) } } log.Println("[DEBUG] Reading hosted service query result data.") d.Set("name", hostedService.ServiceName) d.Set("url", hostedService.URL) d.Set("location", hostedService.Location) d.Set("description", hostedService.Description) d.Set("label", hostedService.Label) d.Set("status", hostedService.Status) d.Set("reverse_dns_fqdn", hostedService.ReverseDNSFqdn) d.Set("default_certificate_thumbprint", hostedService.DefaultWinRmCertificateThumbprint) return nil }
func testAccCheckAzureVirtualNetworkDestroy(s *terraform.State) error { vnetClient := testAccProvider.Meta().(*Client).vnetClient for _, rs := range s.RootModule().Resources { if rs.Type != "azure_virtual_network" { continue } if rs.Primary.ID == "" { return fmt.Errorf("No Virtual Network ID is set") } nc, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { if management.IsResourceNotFoundError(err) { // This is desirable - no configuration = no networks continue } return fmt.Errorf("Error retrieving Virtual Network Configuration: %s", err) } for _, n := range nc.Configuration.VirtualNetworkSites { if n.Name == rs.Primary.ID { return fmt.Errorf("Virtual Network %s still exists", rs.Primary.ID) } } } return nil }
// testAccAzureLocalNetworkConnectionDestroyed checks whether the local network // connection has been destroyed on Azure or not. func testAccAzureLocalNetworkConnectionDestroyed(s *terraform.State) error { vnetClient := testAccProvider.Meta().(*Client).vnetClient for _, resource := range s.RootModule().Resources { if resource.Type != "azure_local_network_connection" { continue } if resource.Primary.ID == "" { return fmt.Errorf("Azure Local Network Connection ID not set.") } netConf, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { // This is desirable - if there is no network config there can be no gateways if management.IsResourceNotFoundError(err) { continue } return err } for _, lnet := range netConf.Configuration.LocalNetworkSites { if lnet.Name == resource.Primary.ID { return fmt.Errorf("Azure Local Network Connection still exists.") } } } return nil }
// resourceAzureSecurityGroupRuleExists does all the necessary API calls to // check for the existence of the network security group rule on Azure. func resourceAzureSecurityGroupRuleExists(d *schema.ResourceData, meta interface{}) (bool, error) { secGroupClient := meta.(*Client).secGroupClient secGroupName := d.Get("security_group_name").(string) // get info on the network security group and search for our rule: log.Println("[INFO] Sending network security group rule query for existence check to Azure.") secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if !management.IsResourceNotFoundError(err) { return false, fmt.Errorf("Error issuing network security group rules query: %s", err) } else { // it meants that the network security group this rule belonged to has // been deleted; so we must remove this resource from the schema: d.SetId("") return false, nil } } // try and find our security group rule: name := d.Get("name").(string) for _, rule := range secgroup.Rules { if rule.Name == name { return true, nil } } // if here; it means the resource has been deleted in the // meantime and must be removed from the schema: d.SetId("") return false, nil }
func testAccCheckAzureSecurityGroupRuleDeleted(groups []string) resource.TestCheckFunc { return func(s *terraform.State) error { for _, resource := range s.RootModule().Resources { if resource.Type != "azure_security_group_rule" { continue } if resource.Primary.ID == "" { return fmt.Errorf("Azure network security group ID not set.") } secGroupClient := testAccProvider.Meta().(*Client).secGroupClient for _, groupName := range groups { secGroup, err := secGroupClient.GetNetworkSecurityGroup(groupName) if err != nil { if !management.IsResourceNotFoundError(err) { return fmt.Errorf("Failed getting network security group details for %q: %s", groupName, err) } } for _, rule := range secGroup.Rules { if rule.Name == resource.Primary.ID { return fmt.Errorf("Azure network security group rule still exists!") } } } } return nil } }
// resourceAzureStorageServiceRead does all the necessary API calls to // read the state of the storage service off Azure. func resourceAzureStorageServiceRead(d *schema.ResourceData, meta interface{}) error { storageServiceClient := meta.(*Client).storageServiceClient // get our storage service: log.Println("[INFO] Sending query about storage service to Azure.") name := d.Get("name").(string) storsvc, err := storageServiceClient.GetStorageService(name) if err != nil { if !management.IsResourceNotFoundError(err) { return fmt.Errorf("Failed to query about Azure about storage service: %s", err) } else { // it means that the resource has been deleted from Azure // in the meantime and we must remove its associated Resource. d.SetId("") return nil } } // read values: d.Set("url", storsvc.URL) log.Println("[INFO] Querying keys of Azure storage service.") keys, err := storageServiceClient.GetStorageServiceKeys(name) if err != nil { return fmt.Errorf("Failed querying keys for Azure storage service: %s", err) } d.Set("primary_key", keys.PrimaryKey) d.Set("secondary_key", keys.SecondaryKey) return nil }
// testAccResourceDestroyedErrorFilter tests whether the given error is an azure ResourceNotFound // error and properly annotates it if otherwise: func testAccResourceDestroyedErrorFilter(resource string, err error) error { switch { case err == nil: return fmt.Errorf("Azure %s still exists.", resource) case err != nil && management.IsResourceNotFoundError(err): return nil default: return err } }
func resourceAzureDataDiskRead(d *schema.ResourceData, meta interface{}) error { vmDiskClient := meta.(*Client).vmDiskClient vmClient := meta.(*Client).vmClient lun := d.Get("lun").(int) vm := d.Get("virtual_machine").(string) cloudServiceName := d.Get("cloud_service_name").(string) if cloudServiceName == "" { cloudServiceName = vm } deploymentName := d.Get("deployment_name").(string) if deploymentName == "" { deptName, err := vmClient.GetDeploymentName(cloudServiceName) if err != nil { return fmt.Errorf("Error reading data disk %d for instance %s while getting deployment name from cloud service %s: %s", lun, vm, cloudServiceName, err) } deploymentName = deptName } if deploymentName == "" { return fmt.Errorf("Error reading data disk %d for instance %s while getting deployment name from cloud service %s: Deployment Name is blank", lun, vm, cloudServiceName) } log.Printf("[DEBUG] Retrieving data disk: %s", d.Id()) datadisk, err := vmDiskClient.GetDataDisk(cloudServiceName, deploymentName, vm, lun) if err != nil { if management.IsResourceNotFoundError(err) { d.SetId("") return nil } return fmt.Errorf("Error retrieving data disk %s: %s", d.Id(), err) } d.Set("name", datadisk.DiskName) d.Set("label", datadisk.DiskLabel) d.Set("lun", datadisk.Lun) d.Set("size", datadisk.LogicalDiskSizeInGB) d.Set("caching", datadisk.HostCaching) d.Set("media_link", datadisk.MediaLink) log.Printf("[DEBUG] Retrieving disk: %s", d.Id()) disk, err := vmDiskClient.GetDisk(d.Id()) if err != nil { return fmt.Errorf("Error retrieving disk %s: %s", d.Id(), err) } d.Set("virtual_machine", disk.AttachedTo.RoleName) d.Set("deployment_name", disk.AttachedTo.DeploymentName) d.Set("cloud_service_name", disk.AttachedTo.HostedServiceName) return nil }
func resourceAzureVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error { ac := meta.(*Client) vnetClient := ac.vnetClient secGroupClient := ac.secGroupClient nc, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { return fmt.Errorf(virtualNetworkRetrievalError, err) } for _, n := range nc.Configuration.VirtualNetworkSites { if n.Name == d.Id() { d.Set("address_space", n.AddressSpace.AddressPrefix) d.Set("location", n.Location) // Create a new set to hold all configured subnets subnets := &schema.Set{ F: resourceAzureSubnetHash, } // Loop through all endpoints for _, s := range n.Subnets { subnet := map[string]interface{}{} // Get the associated (if any) security group sg, err := secGroupClient.GetNetworkSecurityGroupForSubnet(s.Name, d.Id()) if err != nil && !management.IsResourceNotFoundError(err) { return fmt.Errorf( "Error retrieving Network Security Group associations of subnet %s: %s", s.Name, err) } // Update the values subnet["name"] = s.Name subnet["address_prefix"] = s.AddressPrefix subnet["security_group"] = sg.Name subnets.Add(subnet) } d.Set("subnet", subnets) return nil } } log.Printf("[DEBUG] Virtual Network %s does no longer exist", d.Id()) d.SetId("") return nil }
// sourceAzureLocalNetworkConnectionCreate issues all the necessary API calls // to create a virtual network on Azure. func resourceAzureLocalNetworkConnectionCreate(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) mgmtClient := azureClient.mgmtClient vnetClient := azureClient.vnetClient log.Println("[INFO] Fetching current network configuration from Azure.") azureClient.vnetMutex.Lock() defer azureClient.vnetMutex.Unlock() netConf, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { if management.IsResourceNotFoundError(err) { // if no network config exists yet; create a new one now: netConf = virtualnetwork.NetworkConfiguration{} } else { return fmt.Errorf("Failed to get the current network configuration from Azure: %s", err) } } // get provided configuration: name := d.Get("name").(string) vpnGateway := d.Get("vpn_gateway_address").(string) var prefixes []string for _, prefix := range d.Get("address_space_prefixes").([]interface{}) { prefixes = append(prefixes, prefix.(string)) } // add configuration to network config: netConf.Configuration.LocalNetworkSites = append(netConf.Configuration.LocalNetworkSites, virtualnetwork.LocalNetworkSite{ Name: name, VPNGatewayAddress: vpnGateway, AddressSpace: virtualnetwork.AddressSpace{ AddressPrefix: prefixes, }, }) // send the configuration back to Azure: log.Println("[INFO] Sending updated network configuration back to Azure.") reqID, err := vnetClient.SetVirtualNetworkConfiguration(netConf) if err != nil { return fmt.Errorf("Failed setting updated network configuration: %s", err) } err = mgmtClient.WaitForOperation(reqID, nil) if err != nil { return fmt.Errorf("Failed updating the network configuration: %s", err) } d.SetId(name) return nil }
func resourceAzureVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error { ac := meta.(*Client) mc := ac.mgmtClient vnetClient := ac.vnetClient name := d.Get("name").(string) // Lock the client just before we get the virtual network configuration and immediately // set an defer to unlock the client again whenever this function exits ac.mutex.Lock() defer ac.mutex.Unlock() nc, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { if management.IsResourceNotFoundError(err) { // if no network config exists yet; create a new one now: nc = virtualnetwork.NetworkConfiguration{} } else { return fmt.Errorf(virtualNetworkRetrievalError, err) } } for _, n := range nc.Configuration.VirtualNetworkSites { if n.Name == name { return fmt.Errorf("Virtual Network %s already exists!", name) } } network := createVirtualNetwork(d) nc.Configuration.VirtualNetworkSites = append(nc.Configuration.VirtualNetworkSites, network) req, err := vnetClient.SetVirtualNetworkConfiguration(nc) if err != nil { return fmt.Errorf("Error creating Virtual Network %s: %s", name, err) } // Wait until the virtual network is created if err := mc.WaitForOperation(req, nil); err != nil { return fmt.Errorf("Error waiting for Virtual Network %s to be created: %s", name, err) } d.SetId(name) if err := associateSecurityGroups(d, meta); err != nil { return err } return resourceAzureVirtualNetworkRead(d, meta) }
// resourceAzureSecurityGroupRuleRead does all the necessary API calls to // read the state of a network security group ruke off Azure. func resourceAzureSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) secGroupClient := azureClient.secGroupClient var found bool name := d.Get("name").(string) secGroups := d.Get("security_group_names").(*schema.Set).List() remaining := schema.NewSet(schema.HashString, nil) // for each of our security groups; check for our rule: for _, sg := range secGroups { secGroupName := sg.(string) // get info on the network security group and check its rules for this one: log.Printf("[INFO] Sending Azure network security group rule query for security group %s.", secGroupName) secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if !management.IsResourceNotFoundError(err) { return fmt.Errorf("Error issuing network security group rules query for security group %q: %s", secGroupName, err) } else { // it meants that the network security group this rule belonged to has // been deleted; so we skip this iteration: continue } } // find our security rule: for _, rule := range secgroup.Rules { if rule.Name == name { // note the fact that this rule still apllies to this security group: found = true remaining.Add(secGroupName) break } } } // check to see if there is any security group still having this rule: if !found { d.SetId("") return nil } // now; we must update the set of security groups still having this rule: d.Set("security_group_names", remaining) return nil }
// resourceAzureSecurityGroupRuleRead does all the necessary API calls to // read the state of a network security group ruke off Azure. func resourceAzureSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) secGroupClient := azureClient.secGroupClient secGroupName := d.Get("security_group_name").(string) // get info on the network security group and check its rules for this one: log.Println("[INFO] Sending network security group rule query to Azure.") secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if !management.IsResourceNotFoundError(err) { return fmt.Errorf("Error issuing network security group rules query: %s", err) } else { // it meants that the network security group this rule belonged to has // been deleted; so we must remove this resource from the schema: d.SetId("") return nil } } // find our security rule: var found bool name := d.Get("name").(string) for _, rule := range secgroup.Rules { if rule.Name == name { found = true log.Println("[DEBUG] Reading state of Azure network security group rule.") d.Set("type", rule.Type) d.Set("priority", rule.Priority) d.Set("action", rule.Action) d.Set("source_address_prefix", rule.SourceAddressPrefix) d.Set("source_port_range", rule.SourcePortRange) d.Set("destination_address_prefix", rule.DestinationAddressPrefix) d.Set("destination_port_range", rule.DestinationPortRange) d.Set("protocol", rule.Protocol) break } } // check if the rule still exists, and is not, remove the resource: if !found { d.SetId("") } return nil }
func resourceAzureSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { secGroupClient := meta.(*Client).secGroupClient sg, err := secGroupClient.GetNetworkSecurityGroup(d.Id()) if err != nil { if management.IsResourceNotFoundError(err) { d.SetId("") return nil } return fmt.Errorf("Error retrieving Network Security Group %s: %s", d.Id(), err) } d.Set("label", sg.Label) d.Set("location", sg.Location) return nil }
// resourceAzureSecurityGroupRuleDelete does all the necessary API calls to // delete a network security group rule off Azure. func resourceAzureSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) mgmtClient := azureClient.mgmtClient secGroupClient := azureClient.secGroupClient azureClient.secGroupMutex.Lock() defer azureClient.secGroupMutex.Unlock() name := d.Get("name").(string) secGroupNames := d.Get("security_group_names").(*schema.Set).List() for _, sg := range secGroupNames { secGroupName := sg.(string) // get info on the network security group and search for our rule: log.Printf("[INFO] Sending network security group rule query for security group %q.", secGroupName) secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if management.IsResourceNotFoundError(err) { // it means that this network security group this rule belonged to has // been deleted; so we need not do anything more here: continue } else { return fmt.Errorf("Error issuing Azure network security group rules query for security group %q: %s", secGroupName, err) } } // check if the rule has been deleted in the meantime: for _, rule := range secgroup.Rules { if rule.Name == name { // if not; we shall issue the delete: reqID, err := secGroupClient.DeleteNetworkSecurityGroupRule(secGroupName, name) if err != nil { return fmt.Errorf("Error sending network security group rule delete request to Azure: %s", err) } err = mgmtClient.WaitForOperation(reqID, nil) if err != nil { return fmt.Errorf("Error deleting network security group rule off Azure: %s", err) } } break } } return nil }
// TestIsResourceNotFoundError tests IsResourceNotFoundError with the // set of given test cases. func TestIsResourceNotFoundError(t *testing.T) { // isResourceNotFoundTestCases is a set of structs comprising of the error // IsResourceNotFoundError should test and the expected result. var isResourceNotFoundTestCases = []struct { err error expected bool }{ {nil, false}, {fmt.Errorf("Some other random error."), false}, {management.AzureError{Code: "ResourceNotFound"}, true}, {management.AzureError{Code: "NotAResourceNotFound"}, false}, } for i, testCase := range isResourceNotFoundTestCases { if res := management.IsResourceNotFoundError(testCase.err); res != testCase.expected { t.Fatalf("Test %d: error %s - expected %t - got %t", i+1, testCase.err, testCase.expected, res) } } }
// resourceAzureAffinityGroupExists does all the necessary API calls to // check for the existence of the affinity group on Azure. func resourceAzureAffinityGroupExists(d *schema.ResourceData, meta interface{}) (bool, error) { affinityGroupClient := meta.(*Client).affinityGroupClient log.Println("[INFO] Issuing Azure Affinity Group get request.") name := d.Get("name").(string) _, err := affinityGroupClient.GetAffinityGroup(name) if err != nil { if management.IsResourceNotFoundError(err) { // it means that the affinity group has been deleted in the // meantime, so we must untrack it from the schema: d.SetId("") return false, nil } else { return false, fmt.Errorf("Error getting Affinity Group off Azure: %s", err) } } return true, nil }
// resourceAzureDnsServerCreate does all the necessary API calls // to create a new DNS server definition on Azure. func resourceAzureDnsServerCreate(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) mgmtClient := azureClient.mgmtClient vnetClient := azureClient.vnetClient log.Println("[INFO] Fetching current network configuration from Azure.") azureClient.vnetMutex.Lock() defer azureClient.vnetMutex.Unlock() netConf, err := vnetClient.GetVirtualNetworkConfiguration() if err != nil { if management.IsResourceNotFoundError(err) { // if no network configuration exists yet; create one now: netConf = virtualnetwork.NetworkConfiguration{} } else { return fmt.Errorf("Failed to get the current network configuration from Azure: %s", err) } } log.Println("[DEBUG] Adding new DNS server definition to Azure.") name := d.Get("name").(string) address := d.Get("dns_address").(string) netConf.Configuration.DNS.DNSServers = append( netConf.Configuration.DNS.DNSServers, virtualnetwork.DNSServer{ Name: name, IPAddress: address, }) // send the configuration back to Azure: log.Println("[INFO] Sending updated network configuration back to Azure.") reqID, err := vnetClient.SetVirtualNetworkConfiguration(netConf) if err != nil { return fmt.Errorf("Failed issuing update to network configuration: %s", err) } err = mgmtClient.WaitForOperation(reqID, nil) if err != nil { return fmt.Errorf("Error setting network configuration: %s", err) } d.SetId(name) return nil }
// GetDeploymentName queries an existing Azure cloud service for the name of the Deployment, // if any, in its 'Production' slot (the only slot possible). If none exists, it returns empty // string but no error // //https://msdn.microsoft.com/en-us/library/azure/ee460804.aspx func (vm VirtualMachineClient) GetDeploymentName(cloudServiceName string) (string, error) { var deployment DeploymentResponse if cloudServiceName == "" { return "", fmt.Errorf(errParamNotSpecified, "cloudServiceName") } requestURL := fmt.Sprintf(azureListDeploymentsInSlotURL, cloudServiceName) response, err := vm.client.SendAzureGetRequest(requestURL) if err != nil { if management.IsResourceNotFoundError(err) { return "", nil } return "", err } err = xml.Unmarshal(response, &deployment) if err != nil { return "", err } return deployment.Name, nil }
func testAccCheckAzureAffinityGroupDestroyed(s *terraform.State) error { var err error affinityGroupClient := testAccProvider.Meta().(*Client).affinityGroupClient for _, resource := range s.RootModule().Resources { if resource.Type != "azure_affinity_group" { continue } if resource.Primary.ID == "" { return fmt.Errorf("Affinity Group resource ID not set.") } _, err = affinityGroupClient.GetAffinityGroup(resource.Primary.ID) if !management.IsResourceNotFoundError(err) { return err } } return nil }
// resourceAzureStorageServiceExists does all the necessary API calls to // check if the storage service exists on Azure. func resourceAzureStorageServiceExists(d *schema.ResourceData, meta interface{}) (bool, error) { storageServiceClient := meta.(*Client).storageServiceClient // get our storage service: log.Println("[INFO] Sending query about storage service to Azure.") name := d.Get("name").(string) _, err := storageServiceClient.GetStorageService(name) if err != nil { if !management.IsResourceNotFoundError(err) { return false, fmt.Errorf("Failed to query about Azure about storage service: %s", err) } else { // it means that the resource has been deleted from Azure // in the meantime and we must remove its associated Resource. d.SetId("") return false, nil } } return true, nil }
// resourceAzureSecurityGroupRuleDelete does all the necessary API calls to // delete a network security group rule off Azure. func resourceAzureSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) mgmtClient := azureClient.mgmtClient secGroupClient := azureClient.secGroupClient secGroupName := d.Get("security_group_name").(string) // get info on the network security group and search for our rule: log.Println("[INFO] Sending network security group rule query for deletion to Azure.") secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if management.IsResourceNotFoundError(err) { // it meants that the network security group this rule belonged to has // been deleted; so we need do nothing more but stop tracking the resource: d.SetId("") return nil } else { return fmt.Errorf("Error issuing network security group rules query: %s", err) } } // check is the resource has not been deleted in the meantime: name := d.Get("name").(string) for _, rule := range secgroup.Rules { if rule.Name == name { // if not; we shall issue the delete: reqID, err := secGroupClient.DeleteNetworkSecurityGroupRule(secGroupName, name) if err != nil { return fmt.Errorf("Error sending network security group rule delete request to Azure: %s", err) } err = mgmtClient.WaitForOperation(reqID, nil) if err != nil { return fmt.Errorf("Error deleting network security group rule off Azure: %s", err) } } } return nil }
func testAccCheckAzureInstanceDestroy(s *terraform.State) error { hostedServiceClient := testAccProvider.Meta().(*Client).hostedServiceClient for _, rs := range s.RootModule().Resources { if rs.Type != "azure_instance" { continue } if rs.Primary.ID == "" { return fmt.Errorf("No instance ID is set") } _, err := hostedServiceClient.GetHostedService(rs.Primary.ID) if err == nil { return fmt.Errorf("Instance %s still exists", rs.Primary.ID) } if !management.IsResourceNotFoundError(err) { return err } } return nil }
func testAccCheckAzureSecurityGroupDestroy(s *terraform.State) error { secGroupClient := testAccProvider.Meta().(*Client).secGroupClient for _, rs := range s.RootModule().Resources { if rs.Type != "azure_security_group" { continue } if rs.Primary.ID == "" { return fmt.Errorf("No Network Security Group ID is set") } _, err := secGroupClient.GetNetworkSecurityGroup(rs.Primary.ID) if err == nil { return fmt.Errorf("Network Security Group %s still exists", rs.Primary.ID) } if !management.IsResourceNotFoundError(err) { return err } } return nil }
// resourceAzureSecurityGroupRuleUpdate does all the necessary API calls to // update the state of a network security group ruke off Azure. func resourceAzureSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) mgmtClient := azureClient.mgmtClient secGroupClient := azureClient.secGroupClient secGroupName := d.Get("security_group_name").(string) // get info on the network security group and check its rules for this one: log.Println("[INFO] Sending network security group rule query for update to Azure.") secgroup, err := secGroupClient.GetNetworkSecurityGroup(secGroupName) if err != nil { if !management.IsResourceNotFoundError(err) { return fmt.Errorf("Error issuing network security group rules query: %s", err) } else { // it meants that the network security group this rule belonged to has // been deleted; so we must remove this resource from the schema: d.SetId("") return nil } } // try and find our security group rule: var found bool name := d.Get("name").(string) for _, rule := range secgroup.Rules { if rule.Name == name { found = true } } // check is the resource has not been deleted in the meantime: if !found { // if not; remove the resource: d.SetId("") return nil } // else, start building up the rule request struct: newRule := netsecgroup.RuleRequest{ Name: d.Get("name").(string), Type: netsecgroup.RuleType(d.Get("type").(string)), Priority: d.Get("priority").(int), Action: netsecgroup.RuleAction(d.Get("action").(string)), SourceAddressPrefix: d.Get("source_address_prefix").(string), SourcePortRange: d.Get("source_port_range").(string), DestinationAddressPrefix: d.Get("destination_address_prefix").(string), DestinationPortRange: d.Get("destination_port_range").(string), Protocol: netsecgroup.RuleProtocol(d.Get("protocol").(string)), } // send the create request to Azure: log.Println("[INFO] Sending network security group rule update request to Azure.") reqID, err := secGroupClient.SetNetworkSecurityGroupRule( secGroupName, newRule, ) if err != nil { return fmt.Errorf("Error sending network security group rule update request to Azure: %s", err) } err = mgmtClient.WaitForOperation(reqID, nil) if err != nil { return fmt.Errorf("Error updating network security group rule on Azure: %s", err) } return nil }
func resourceAzureInstanceRead(d *schema.ResourceData, meta interface{}) error { azureClient := meta.(*Client) hostedServiceClient := azureClient.hostedServiceClient vmClient := azureClient.vmClient name := d.Get("name").(string) // check if the instance belongs to an independent hosted service // or it had one created for it. var hostedServiceName string if serviceName, ok := d.GetOk("hosted_service_name"); ok { // if independent; use that hosted service name: hostedServiceName = serviceName.(string) } else { // else; suppose it's the instance's name: hostedServiceName = name } log.Printf("[DEBUG] Retrieving Cloud Service for instance: %s", name) cs, err := hostedServiceClient.GetHostedService(hostedServiceName) if err != nil { return fmt.Errorf("Error retrieving Cloud Service of instance %s (%q): %s", name, hostedServiceName, err) } d.Set("reverse_dns", cs.ReverseDNSFqdn) d.Set("location", cs.Location) log.Printf("[DEBUG] Retrieving instance: %s", name) dpmt, err := vmClient.GetDeployment(hostedServiceName, name) if err != nil { if management.IsResourceNotFoundError(err) { d.SetId("") return nil } return fmt.Errorf("Error retrieving instance %s: %s", name, err) } if len(dpmt.RoleList) != 1 { return fmt.Errorf( "Instance %s has an unexpected number of roles: %d", name, len(dpmt.RoleList)) } d.Set("size", dpmt.RoleList[0].RoleSize) if len(dpmt.RoleInstanceList) != 1 { return fmt.Errorf( "Instance %s has an unexpected number of role instances: %d", name, len(dpmt.RoleInstanceList)) } d.Set("ip_address", dpmt.RoleInstanceList[0].IPAddress) if len(dpmt.RoleInstanceList[0].InstanceEndpoints) > 0 { d.Set("vip_address", dpmt.RoleInstanceList[0].InstanceEndpoints[0].Vip) } // Find the network configuration set for _, c := range dpmt.RoleList[0].ConfigurationSets { if c.ConfigurationSetType == virtualmachine.ConfigurationSetTypeNetwork { // Create a new set to hold all configured endpoints endpoints := &schema.Set{ F: resourceAzureEndpointHash, } // Loop through all endpoints for _, ep := range c.InputEndpoints { endpoint := map[string]interface{}{} // Update the values endpoint["name"] = ep.Name endpoint["protocol"] = string(ep.Protocol) endpoint["public_port"] = ep.Port endpoint["private_port"] = ep.LocalPort endpoints.Add(endpoint) } d.Set("endpoint", endpoints) // Update the subnet switch len(c.SubnetNames) { case 1: d.Set("subnet", c.SubnetNames[0]) case 0: d.Set("subnet", "") default: return fmt.Errorf( "Instance %s has an unexpected number of associated subnets %d", name, len(dpmt.RoleInstanceList)) } // Update the security group d.Set("security_group", c.NetworkSecurityGroup) } } connType := "ssh" if dpmt.RoleList[0].OSVirtualHardDisk.OS == windows { connType = "winrm" } // Set the connection info for any configured provisioners d.SetConnInfo(map[string]string{ "type": connType, "host": dpmt.VirtualIPs[0].Address, "user": d.Get("username").(string), "password": d.Get("password").(string), }) return nil }