github.com/IBM-Cloud/terraform@v0.6.4-0.20170726051544-8872b87621df/builtin/providers/azurerm/resource_arm_network_interface_card.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"log"
     7  	"net/http"
     8  	"strings"
     9  
    10  	"github.com/Azure/azure-sdk-for-go/arm/network"
    11  	"github.com/hashicorp/terraform/helper/hashcode"
    12  	"github.com/hashicorp/terraform/helper/schema"
    13  )
    14  
    15  func resourceArmNetworkInterface() *schema.Resource {
    16  	return &schema.Resource{
    17  		Create: resourceArmNetworkInterfaceCreate,
    18  		Read:   resourceArmNetworkInterfaceRead,
    19  		Update: resourceArmNetworkInterfaceCreate,
    20  		Delete: resourceArmNetworkInterfaceDelete,
    21  
    22  		Schema: map[string]*schema.Schema{
    23  			"name": {
    24  				Type:     schema.TypeString,
    25  				Required: true,
    26  				ForceNew: true,
    27  			},
    28  
    29  			"location": locationSchema(),
    30  
    31  			"resource_group_name": {
    32  				Type:     schema.TypeString,
    33  				Required: true,
    34  				ForceNew: true,
    35  			},
    36  
    37  			"network_security_group_id": {
    38  				Type:     schema.TypeString,
    39  				Optional: true,
    40  				Computed: true,
    41  			},
    42  
    43  			"mac_address": {
    44  				Type:     schema.TypeString,
    45  				Optional: true,
    46  				Computed: true,
    47  			},
    48  
    49  			"private_ip_address": {
    50  				Type:     schema.TypeString,
    51  				Computed: true,
    52  			},
    53  
    54  			"virtual_machine_id": {
    55  				Type:     schema.TypeString,
    56  				Optional: true,
    57  				Computed: true,
    58  			},
    59  
    60  			"ip_configuration": {
    61  				Type:     schema.TypeSet,
    62  				Required: true,
    63  				Elem: &schema.Resource{
    64  					Schema: map[string]*schema.Schema{
    65  						"name": {
    66  							Type:     schema.TypeString,
    67  							Required: true,
    68  						},
    69  
    70  						"subnet_id": {
    71  							Type:     schema.TypeString,
    72  							Required: true,
    73  						},
    74  
    75  						"private_ip_address": {
    76  							Type:     schema.TypeString,
    77  							Optional: true,
    78  							Computed: true,
    79  						},
    80  
    81  						"private_ip_address_allocation": {
    82  							Type:             schema.TypeString,
    83  							Required:         true,
    84  							ValidateFunc:     validateNetworkInterfacePrivateIpAddressAllocation,
    85  							StateFunc:        ignoreCaseStateFunc,
    86  							DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
    87  						},
    88  
    89  						"public_ip_address_id": {
    90  							Type:     schema.TypeString,
    91  							Optional: true,
    92  							Computed: true,
    93  						},
    94  
    95  						"load_balancer_backend_address_pools_ids": {
    96  							Type:     schema.TypeSet,
    97  							Optional: true,
    98  							Computed: true,
    99  							Elem:     &schema.Schema{Type: schema.TypeString},
   100  							Set:      schema.HashString,
   101  						},
   102  
   103  						"load_balancer_inbound_nat_rules_ids": {
   104  							Type:     schema.TypeSet,
   105  							Optional: true,
   106  							Computed: true,
   107  							Elem:     &schema.Schema{Type: schema.TypeString},
   108  							Set:      schema.HashString,
   109  						},
   110  					},
   111  				},
   112  				Set: resourceArmNetworkInterfaceIpConfigurationHash,
   113  			},
   114  
   115  			"dns_servers": {
   116  				Type:     schema.TypeSet,
   117  				Optional: true,
   118  				Computed: true,
   119  				Elem:     &schema.Schema{Type: schema.TypeString},
   120  				Set:      schema.HashString,
   121  			},
   122  
   123  			"internal_dns_name_label": {
   124  				Type:     schema.TypeString,
   125  				Optional: true,
   126  				Computed: true,
   127  			},
   128  
   129  			"applied_dns_servers": {
   130  				Type:     schema.TypeSet,
   131  				Optional: true,
   132  				Computed: true,
   133  				Elem:     &schema.Schema{Type: schema.TypeString},
   134  				Set:      schema.HashString,
   135  			},
   136  
   137  			"internal_fqdn": {
   138  				Type:     schema.TypeString,
   139  				Optional: true,
   140  				Computed: true,
   141  			},
   142  
   143  			"enable_ip_forwarding": {
   144  				Type:     schema.TypeBool,
   145  				Optional: true,
   146  				Default:  false,
   147  			},
   148  
   149  			"tags": tagsSchema(),
   150  		},
   151  	}
   152  }
   153  
   154  func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
   155  	client := meta.(*ArmClient)
   156  	ifaceClient := client.ifaceClient
   157  
   158  	log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.")
   159  
   160  	name := d.Get("name").(string)
   161  	location := d.Get("location").(string)
   162  	resGroup := d.Get("resource_group_name").(string)
   163  	enableIpForwarding := d.Get("enable_ip_forwarding").(bool)
   164  	tags := d.Get("tags").(map[string]interface{})
   165  
   166  	properties := network.InterfacePropertiesFormat{
   167  		EnableIPForwarding: &enableIpForwarding,
   168  	}
   169  
   170  	if v, ok := d.GetOk("network_security_group_id"); ok {
   171  		nsgId := v.(string)
   172  		properties.NetworkSecurityGroup = &network.SecurityGroup{
   173  			ID: &nsgId,
   174  		}
   175  
   176  		networkSecurityGroupName, err := parseNetworkSecurityGroupName(nsgId)
   177  		if err != nil {
   178  			return err
   179  		}
   180  
   181  		armMutexKV.Lock(networkSecurityGroupName)
   182  		defer armMutexKV.Unlock(networkSecurityGroupName)
   183  	}
   184  
   185  	dns, hasDns := d.GetOk("dns_servers")
   186  	nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label")
   187  	if hasDns || hasNameLabel {
   188  		ifaceDnsSettings := network.InterfaceDNSSettings{}
   189  
   190  		if hasDns {
   191  			var dnsServers []string
   192  			dns := dns.(*schema.Set).List()
   193  			for _, v := range dns {
   194  				str := v.(string)
   195  				dnsServers = append(dnsServers, str)
   196  			}
   197  			ifaceDnsSettings.DNSServers = &dnsServers
   198  		}
   199  
   200  		if hasNameLabel {
   201  			name_label := nameLabel.(string)
   202  			ifaceDnsSettings.InternalDNSNameLabel = &name_label
   203  		}
   204  
   205  		properties.DNSSettings = &ifaceDnsSettings
   206  	}
   207  
   208  	ipConfigs, namesToLock, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d)
   209  	if sgErr != nil {
   210  		return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr)
   211  	}
   212  
   213  	azureRMLockMultiple(namesToLock)
   214  	defer azureRMUnlockMultiple(namesToLock)
   215  
   216  	if len(ipConfigs) > 0 {
   217  		properties.IPConfigurations = &ipConfigs
   218  	}
   219  
   220  	iface := network.Interface{
   221  		Name:                      &name,
   222  		Location:                  &location,
   223  		InterfacePropertiesFormat: &properties,
   224  		Tags: expandTags(tags),
   225  	}
   226  
   227  	_, err := ifaceClient.CreateOrUpdate(resGroup, name, iface, make(chan struct{}))
   228  	if err != nil {
   229  		return err
   230  	}
   231  
   232  	read, err := ifaceClient.Get(resGroup, name, "")
   233  	if err != nil {
   234  		return err
   235  	}
   236  	if read.ID == nil {
   237  		return fmt.Errorf("Cannot read NIC %s (resource group %s) ID", name, resGroup)
   238  	}
   239  
   240  	d.SetId(*read.ID)
   241  
   242  	return resourceArmNetworkInterfaceRead(d, meta)
   243  }
   244  
   245  func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
   246  	ifaceClient := meta.(*ArmClient).ifaceClient
   247  
   248  	id, err := parseAzureResourceID(d.Id())
   249  	if err != nil {
   250  		return err
   251  	}
   252  	resGroup := id.ResourceGroup
   253  	name := id.Path["networkInterfaces"]
   254  
   255  	resp, err := ifaceClient.Get(resGroup, name, "")
   256  	if err != nil {
   257  		if resp.StatusCode == http.StatusNotFound {
   258  			d.SetId("")
   259  			return nil
   260  		}
   261  		return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err)
   262  	}
   263  
   264  	iface := *resp.InterfacePropertiesFormat
   265  
   266  	if iface.MacAddress != nil {
   267  		if *iface.MacAddress != "" {
   268  			d.Set("mac_address", iface.MacAddress)
   269  		}
   270  	}
   271  
   272  	if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 {
   273  		var privateIPAddress *string
   274  		///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
   275  		if (*iface.IPConfigurations)[0].InterfaceIPConfigurationPropertiesFormat != nil {
   276  			privateIPAddress = (*iface.IPConfigurations)[0].InterfaceIPConfigurationPropertiesFormat.PrivateIPAddress
   277  		}
   278  
   279  		if *privateIPAddress != "" {
   280  			d.Set("private_ip_address", *privateIPAddress)
   281  		}
   282  	}
   283  
   284  	if iface.VirtualMachine != nil {
   285  		if *iface.VirtualMachine.ID != "" {
   286  			d.Set("virtual_machine_id", *iface.VirtualMachine.ID)
   287  		}
   288  	}
   289  
   290  	if iface.DNSSettings != nil {
   291  		if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 {
   292  			dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers))
   293  			for _, dns := range *iface.DNSSettings.AppliedDNSServers {
   294  				dnsServers = append(dnsServers, dns)
   295  			}
   296  
   297  			if err := d.Set("applied_dns_servers", dnsServers); err != nil {
   298  				return err
   299  			}
   300  		}
   301  
   302  		if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" {
   303  			d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn)
   304  		}
   305  	}
   306  
   307  	flattenAndSetTags(d, resp.Tags)
   308  
   309  	return nil
   310  }
   311  
   312  func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
   313  	ifaceClient := meta.(*ArmClient).ifaceClient
   314  
   315  	id, err := parseAzureResourceID(d.Id())
   316  	if err != nil {
   317  		return err
   318  	}
   319  	resGroup := id.ResourceGroup
   320  	name := id.Path["networkInterfaces"]
   321  
   322  	if v, ok := d.GetOk("network_security_group_id"); ok {
   323  		networkSecurityGroupId := v.(string)
   324  		networkSecurityGroupName, err := parseNetworkSecurityGroupName(networkSecurityGroupId)
   325  		if err != nil {
   326  			return err
   327  		}
   328  
   329  		armMutexKV.Lock(networkSecurityGroupName)
   330  		defer armMutexKV.Unlock(networkSecurityGroupName)
   331  	}
   332  
   333  	configs := d.Get("ip_configuration").(*schema.Set).List()
   334  	namesToLock := make([]string, 0)
   335  
   336  	for _, configRaw := range configs {
   337  		data := configRaw.(map[string]interface{})
   338  
   339  		subnet_id := data["subnet_id"].(string)
   340  		subnetId, err := parseAzureResourceID(subnet_id)
   341  		if err != nil {
   342  			return err
   343  		}
   344  		subnetName := subnetId.Path["subnets"]
   345  		virtualNetworkName := subnetId.Path["virtualNetworks"]
   346  		namesToLock = append(namesToLock, subnetName)
   347  		namesToLock = append(namesToLock, virtualNetworkName)
   348  	}
   349  
   350  	azureRMLockMultiple(&namesToLock)
   351  	defer azureRMUnlockMultiple(&namesToLock)
   352  
   353  	_, err = ifaceClient.Delete(resGroup, name, make(chan struct{}))
   354  
   355  	return err
   356  }
   357  
   358  func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int {
   359  	var buf bytes.Buffer
   360  	m := v.(map[string]interface{})
   361  	buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
   362  	buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string)))
   363  	if m["private_ip_address"] != nil {
   364  		buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string)))
   365  	}
   366  	buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string)))
   367  	if m["public_ip_address_id"] != nil {
   368  		buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string)))
   369  	}
   370  	if m["load_balancer_backend_address_pools_ids"] != nil {
   371  		ids := m["load_balancer_backend_address_pools_ids"].(*schema.Set).List()
   372  		for _, id := range ids {
   373  			buf.WriteString(fmt.Sprintf("%d-", schema.HashString(id.(string))))
   374  		}
   375  	}
   376  	if m["load_balancer_inbound_nat_rules_ids"] != nil {
   377  		ids := m["load_balancer_inbound_nat_rules_ids"].(*schema.Set).List()
   378  		for _, id := range ids {
   379  			buf.WriteString(fmt.Sprintf("%d-", schema.HashString(id.(string))))
   380  		}
   381  	}
   382  
   383  	return hashcode.String(buf.String())
   384  }
   385  
   386  func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) {
   387  	value := strings.ToLower(v.(string))
   388  	allocations := map[string]bool{
   389  		"static":  true,
   390  		"dynamic": true,
   391  	}
   392  
   393  	if !allocations[value] {
   394  		errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic"))
   395  	}
   396  	return
   397  }
   398  
   399  func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, *[]string, error) {
   400  	configs := d.Get("ip_configuration").(*schema.Set).List()
   401  	ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs))
   402  	namesToLock := make([]string, 0)
   403  
   404  	for _, configRaw := range configs {
   405  		data := configRaw.(map[string]interface{})
   406  
   407  		subnet_id := data["subnet_id"].(string)
   408  		private_ip_allocation_method := data["private_ip_address_allocation"].(string)
   409  
   410  		var allocationMethod network.IPAllocationMethod
   411  		switch strings.ToLower(private_ip_allocation_method) {
   412  		case "dynamic":
   413  			allocationMethod = network.Dynamic
   414  		case "static":
   415  			allocationMethod = network.Static
   416  		default:
   417  			return []network.InterfaceIPConfiguration{}, nil, fmt.Errorf(
   418  				"valid values for private_ip_allocation_method are 'dynamic' and 'static' - got '%s'",
   419  				private_ip_allocation_method)
   420  		}
   421  
   422  		properties := network.InterfaceIPConfigurationPropertiesFormat{
   423  			Subnet: &network.Subnet{
   424  				ID: &subnet_id,
   425  			},
   426  			PrivateIPAllocationMethod: allocationMethod,
   427  		}
   428  
   429  		subnetId, err := parseAzureResourceID(subnet_id)
   430  		if err != nil {
   431  			return []network.InterfaceIPConfiguration{}, nil, err
   432  		}
   433  		subnetName := subnetId.Path["subnets"]
   434  		virtualNetworkName := subnetId.Path["virtualNetworks"]
   435  		namesToLock = append(namesToLock, subnetName)
   436  		namesToLock = append(namesToLock, virtualNetworkName)
   437  
   438  		if v := data["private_ip_address"].(string); v != "" {
   439  			properties.PrivateIPAddress = &v
   440  		}
   441  
   442  		if v := data["public_ip_address_id"].(string); v != "" {
   443  			properties.PublicIPAddress = &network.PublicIPAddress{
   444  				ID: &v,
   445  			}
   446  		}
   447  
   448  		if v, ok := data["load_balancer_backend_address_pools_ids"]; ok {
   449  			var ids []network.BackendAddressPool
   450  			pools := v.(*schema.Set).List()
   451  			for _, p := range pools {
   452  				pool_id := p.(string)
   453  				id := network.BackendAddressPool{
   454  					ID: &pool_id,
   455  				}
   456  
   457  				ids = append(ids, id)
   458  			}
   459  
   460  			properties.LoadBalancerBackendAddressPools = &ids
   461  		}
   462  
   463  		if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok {
   464  			var natRules []network.InboundNatRule
   465  			rules := v.(*schema.Set).List()
   466  			for _, r := range rules {
   467  				rule_id := r.(string)
   468  				rule := network.InboundNatRule{
   469  					ID: &rule_id,
   470  				}
   471  
   472  				natRules = append(natRules, rule)
   473  			}
   474  
   475  			properties.LoadBalancerInboundNatRules = &natRules
   476  		}
   477  
   478  		name := data["name"].(string)
   479  		ipConfig := network.InterfaceIPConfiguration{
   480  			Name: &name,
   481  			InterfaceIPConfigurationPropertiesFormat: &properties,
   482  		}
   483  
   484  		ipConfigs = append(ipConfigs, ipConfig)
   485  	}
   486  
   487  	return ipConfigs, &namesToLock, nil
   488  }