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