github.com/peterbale/terraform@v0.9.0-beta2.0.20170315142748-5723acd55547/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  
   177  	dns, hasDns := d.GetOk("dns_servers")
   178  	nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label")
   179  	if hasDns || hasNameLabel {
   180  		ifaceDnsSettings := network.InterfaceDNSSettings{}
   181  
   182  		if hasDns {
   183  			var dnsServers []string
   184  			dns := dns.(*schema.Set).List()
   185  			for _, v := range dns {
   186  				str := v.(string)
   187  				dnsServers = append(dnsServers, str)
   188  			}
   189  			ifaceDnsSettings.DNSServers = &dnsServers
   190  		}
   191  
   192  		if hasNameLabel {
   193  			name_label := nameLabel.(string)
   194  			ifaceDnsSettings.InternalDNSNameLabel = &name_label
   195  
   196  		}
   197  
   198  		properties.DNSSettings = &ifaceDnsSettings
   199  	}
   200  
   201  	ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d)
   202  	if sgErr != nil {
   203  		return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr)
   204  	}
   205  	if len(ipConfigs) > 0 {
   206  		properties.IPConfigurations = &ipConfigs
   207  	}
   208  
   209  	iface := network.Interface{
   210  		Name:                      &name,
   211  		Location:                  &location,
   212  		InterfacePropertiesFormat: &properties,
   213  		Tags: expandTags(tags),
   214  	}
   215  
   216  	_, err := ifaceClient.CreateOrUpdate(resGroup, name, iface, make(chan struct{}))
   217  	if err != nil {
   218  		return err
   219  	}
   220  
   221  	read, err := ifaceClient.Get(resGroup, name, "")
   222  	if err != nil {
   223  		return err
   224  	}
   225  	if read.ID == nil {
   226  		return fmt.Errorf("Cannot read NIC %s (resource group %s) ID", name, resGroup)
   227  	}
   228  
   229  	d.SetId(*read.ID)
   230  
   231  	return resourceArmNetworkInterfaceRead(d, meta)
   232  }
   233  
   234  func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
   235  	ifaceClient := meta.(*ArmClient).ifaceClient
   236  
   237  	id, err := parseAzureResourceID(d.Id())
   238  	if err != nil {
   239  		return err
   240  	}
   241  	resGroup := id.ResourceGroup
   242  	name := id.Path["networkInterfaces"]
   243  
   244  	resp, err := ifaceClient.Get(resGroup, name, "")
   245  	if err != nil {
   246  		if resp.StatusCode == http.StatusNotFound {
   247  			d.SetId("")
   248  			return nil
   249  		}
   250  		return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err)
   251  	}
   252  
   253  	iface := *resp.InterfacePropertiesFormat
   254  
   255  	if iface.MacAddress != nil {
   256  		if *iface.MacAddress != "" {
   257  			d.Set("mac_address", iface.MacAddress)
   258  		}
   259  	}
   260  
   261  	if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 {
   262  		var privateIPAddress *string
   263  		///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
   264  		if (*iface.IPConfigurations)[0].InterfaceIPConfigurationPropertiesFormat != nil {
   265  			privateIPAddress = (*iface.IPConfigurations)[0].InterfaceIPConfigurationPropertiesFormat.PrivateIPAddress
   266  		}
   267  
   268  		if *privateIPAddress != "" {
   269  			d.Set("private_ip_address", *privateIPAddress)
   270  		}
   271  	}
   272  
   273  	if iface.VirtualMachine != nil {
   274  		if *iface.VirtualMachine.ID != "" {
   275  			d.Set("virtual_machine_id", *iface.VirtualMachine.ID)
   276  		}
   277  	}
   278  
   279  	if iface.DNSSettings != nil {
   280  		if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 {
   281  			dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers))
   282  			for _, dns := range *iface.DNSSettings.AppliedDNSServers {
   283  				dnsServers = append(dnsServers, dns)
   284  			}
   285  
   286  			if err := d.Set("applied_dns_servers", dnsServers); err != nil {
   287  				return err
   288  			}
   289  		}
   290  
   291  		if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" {
   292  			d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn)
   293  		}
   294  	}
   295  
   296  	flattenAndSetTags(d, resp.Tags)
   297  
   298  	return nil
   299  }
   300  
   301  func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
   302  	ifaceClient := meta.(*ArmClient).ifaceClient
   303  
   304  	id, err := parseAzureResourceID(d.Id())
   305  	if err != nil {
   306  		return err
   307  	}
   308  	resGroup := id.ResourceGroup
   309  	name := id.Path["networkInterfaces"]
   310  
   311  	_, err = ifaceClient.Delete(resGroup, name, make(chan struct{}))
   312  
   313  	return err
   314  }
   315  
   316  func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int {
   317  	var buf bytes.Buffer
   318  	m := v.(map[string]interface{})
   319  	buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
   320  	buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string)))
   321  	if m["private_ip_address"] != nil {
   322  		buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string)))
   323  	}
   324  	buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string)))
   325  	if m["public_ip_address_id"] != nil {
   326  		buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string)))
   327  	}
   328  	if m["load_balancer_backend_address_pools_ids"] != nil {
   329  		ids := m["load_balancer_backend_address_pools_ids"].(*schema.Set).List()
   330  		for _, id := range ids {
   331  			buf.WriteString(fmt.Sprintf("%d-", schema.HashString(id.(string))))
   332  		}
   333  	}
   334  	if m["load_balancer_inbound_nat_rules_ids"] != nil {
   335  		ids := m["load_balancer_inbound_nat_rules_ids"].(*schema.Set).List()
   336  		for _, id := range ids {
   337  			buf.WriteString(fmt.Sprintf("%d-", schema.HashString(id.(string))))
   338  		}
   339  	}
   340  
   341  	return hashcode.String(buf.String())
   342  }
   343  
   344  func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) {
   345  	value := strings.ToLower(v.(string))
   346  	allocations := map[string]bool{
   347  		"static":  true,
   348  		"dynamic": true,
   349  	}
   350  
   351  	if !allocations[value] {
   352  		errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic"))
   353  	}
   354  	return
   355  }
   356  
   357  func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) {
   358  	configs := d.Get("ip_configuration").(*schema.Set).List()
   359  	ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs))
   360  
   361  	for _, configRaw := range configs {
   362  		data := configRaw.(map[string]interface{})
   363  
   364  		subnet_id := data["subnet_id"].(string)
   365  		private_ip_allocation_method := data["private_ip_address_allocation"].(string)
   366  
   367  		var allocationMethod network.IPAllocationMethod
   368  		switch strings.ToLower(private_ip_allocation_method) {
   369  		case "dynamic":
   370  			allocationMethod = network.Dynamic
   371  		case "static":
   372  			allocationMethod = network.Static
   373  		default:
   374  			return []network.InterfaceIPConfiguration{}, fmt.Errorf(
   375  				"valid values for private_ip_allocation_method are 'dynamic' and 'static' - got '%s'",
   376  				private_ip_allocation_method)
   377  		}
   378  
   379  		properties := network.InterfaceIPConfigurationPropertiesFormat{
   380  			Subnet: &network.Subnet{
   381  				ID: &subnet_id,
   382  			},
   383  			PrivateIPAllocationMethod: allocationMethod,
   384  		}
   385  
   386  		if v := data["private_ip_address"].(string); v != "" {
   387  			properties.PrivateIPAddress = &v
   388  		}
   389  
   390  		if v := data["public_ip_address_id"].(string); v != "" {
   391  			properties.PublicIPAddress = &network.PublicIPAddress{
   392  				ID: &v,
   393  			}
   394  		}
   395  
   396  		if v, ok := data["load_balancer_backend_address_pools_ids"]; ok {
   397  			var ids []network.BackendAddressPool
   398  			pools := v.(*schema.Set).List()
   399  			for _, p := range pools {
   400  				pool_id := p.(string)
   401  				id := network.BackendAddressPool{
   402  					ID: &pool_id,
   403  				}
   404  
   405  				ids = append(ids, id)
   406  			}
   407  
   408  			properties.LoadBalancerBackendAddressPools = &ids
   409  		}
   410  
   411  		if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok {
   412  			var natRules []network.InboundNatRule
   413  			rules := v.(*schema.Set).List()
   414  			for _, r := range rules {
   415  				rule_id := r.(string)
   416  				rule := network.InboundNatRule{
   417  					ID: &rule_id,
   418  				}
   419  
   420  				natRules = append(natRules, rule)
   421  			}
   422  
   423  			properties.LoadBalancerInboundNatRules = &natRules
   424  		}
   425  
   426  		name := data["name"].(string)
   427  		ipConfig := network.InterfaceIPConfiguration{
   428  			Name: &name,
   429  			InterfaceIPConfigurationPropertiesFormat: &properties,
   430  		}
   431  
   432  		ipConfigs = append(ipConfigs, ipConfig)
   433  	}
   434  
   435  	return ipConfigs, nil
   436  }