forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_arm_virtual_network.go
379 lines (312 loc) · 10.7 KB
/
resource_arm_virtual_network.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package azurerm
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2017-09-01/network"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
var virtualNetworkResourceName = "azurerm_virtual_network"
func resourceArmVirtualNetwork() *schema.Resource {
return &schema.Resource{
Create: resourceArmVirtualNetworkCreate,
Read: resourceArmVirtualNetworkRead,
Update: resourceArmVirtualNetworkCreate,
Delete: resourceArmVirtualNetworkDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"address_space": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"dns_servers": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"subnet": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"address_prefix": {
Type: schema.TypeString,
Required: true,
},
"security_group": {
Type: schema.TypeString,
Optional: true,
},
},
},
Set: resourceAzureSubnetHash,
},
"location": locationSchema(),
"resource_group_name": resourceGroupNameSchema(),
"tags": tagsSchema(),
},
}
}
func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vnetClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.")
name := d.Get("name").(string)
location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{})
vnetProperties, vnetPropsErr := getVirtualNetworkProperties(ctx, d, meta)
if vnetPropsErr != nil {
return vnetPropsErr
}
vnet := network.VirtualNetwork{
Name: &name,
Location: &location,
VirtualNetworkPropertiesFormat: vnetProperties,
Tags: expandTags(tags),
}
networkSecurityGroupNames := make([]string, 0)
for _, subnet := range *vnet.VirtualNetworkPropertiesFormat.Subnets {
if subnet.NetworkSecurityGroup != nil {
nsgName, err := parseNetworkSecurityGroupName(*subnet.NetworkSecurityGroup.ID)
if err != nil {
return err
}
if !sliceContainsValue(networkSecurityGroupNames, nsgName) {
networkSecurityGroupNames = append(networkSecurityGroupNames, nsgName)
}
}
}
azureRMLockMultipleByName(&networkSecurityGroupNames, networkSecurityGroupResourceName)
defer azureRMUnlockMultipleByName(&networkSecurityGroupNames, networkSecurityGroupResourceName)
future, err := client.CreateOrUpdate(ctx, resGroup, name, vnet)
if err != nil {
return fmt.Errorf("Error Creating/Updating Virtual Network %q (Resource Group %q): %+v", name, resGroup, err)
}
err = future.WaitForCompletion(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting for completion of Virtual Network %q (Resource Group %q): %+v", name, resGroup, err)
}
read, err := client.Get(ctx, resGroup, name, "")
if err != nil {
return err
}
if read.ID == nil {
return fmt.Errorf("Cannot read Virtual Network %q (resource group %q) ID", name, resGroup)
}
d.SetId(*read.ID)
return resourceArmVirtualNetworkRead(d, meta)
}
func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vnetClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["virtualNetworks"]
resp, err := client.Get(ctx, resGroup, name, "")
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on Virtual Network %q (Resource Group %q): %+v", name, resGroup, err)
}
vnet := *resp.VirtualNetworkPropertiesFormat
// update appropriate values
d.Set("resource_group_name", resGroup)
d.Set("name", resp.Name)
d.Set("address_space", vnet.AddressSpace.AddressPrefixes)
if location := resp.Location; location != nil {
d.Set("location", azureRMNormalizeLocation(*location))
}
subnets := &schema.Set{
F: resourceAzureSubnetHash,
}
for _, subnet := range *vnet.Subnets {
s := map[string]interface{}{}
s["name"] = *subnet.Name
s["address_prefix"] = *subnet.SubnetPropertiesFormat.AddressPrefix
if subnet.SubnetPropertiesFormat.NetworkSecurityGroup != nil {
s["security_group"] = *subnet.SubnetPropertiesFormat.NetworkSecurityGroup.ID
}
subnets.Add(s)
}
d.Set("subnet", subnets)
if vnet.DhcpOptions != nil && vnet.DhcpOptions.DNSServers != nil {
dnses := []string{}
for _, dns := range *vnet.DhcpOptions.DNSServers {
dnses = append(dnses, dns)
}
d.Set("dns_servers", dnses)
}
flattenAndSetTags(d, resp.Tags)
return nil
}
func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vnetClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["virtualNetworks"]
nsgNames, err := expandAzureRmVirtualNetworkVirtualNetworkSecurityGroupNames(d)
if err != nil {
return fmt.Errorf("[ERROR] Error parsing Network Security Group ID's: %+v", err)
}
azureRMLockMultipleByName(&nsgNames, virtualNetworkResourceName)
defer azureRMUnlockMultipleByName(&nsgNames, virtualNetworkResourceName)
future, err := client.Delete(ctx, resGroup, name)
if err != nil {
return fmt.Errorf("Error deleting Virtual Network %q (Resource Group %q): %+v", name, resGroup, err)
}
err = future.WaitForCompletion(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting for deletion of Virtual Network %q (Resource Group %q): %+v", name, resGroup, err)
}
return nil
}
func getVirtualNetworkProperties(ctx context.Context, d *schema.ResourceData, meta interface{}) (*network.VirtualNetworkPropertiesFormat, error) {
// first; get address space prefixes:
prefixes := []string{}
for _, prefix := range d.Get("address_space").([]interface{}) {
prefixes = append(prefixes, prefix.(string))
}
// then; the dns servers:
dnses := []string{}
for _, dns := range d.Get("dns_servers").([]interface{}) {
dnses = append(dnses, dns.(string))
}
// then; the subnets:
subnets := []network.Subnet{}
if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 {
for _, subnet := range subs.List() {
subnet := subnet.(map[string]interface{})
name := subnet["name"].(string)
log.Printf("[INFO] setting subnets inside vNet, processing %q", name)
//since subnets can also be created outside of vNet definition (as root objects)
// do a GET on subnet properties from the server before setting them
resGroup := d.Get("resource_group_name").(string)
vnetName := d.Get("name").(string)
subnetObj, err := getExistingSubnet(ctx, resGroup, vnetName, name, meta)
if err != nil {
return nil, err
}
log.Printf("[INFO] Completed GET of Subnet props ")
prefix := subnet["address_prefix"].(string)
secGroup := subnet["security_group"].(string)
//set the props from config and leave the rest intact
subnetObj.Name = &name
if subnetObj.SubnetPropertiesFormat == nil {
subnetObj.SubnetPropertiesFormat = &network.SubnetPropertiesFormat{}
}
subnetObj.SubnetPropertiesFormat.AddressPrefix = &prefix
if secGroup != "" {
subnetObj.SubnetPropertiesFormat.NetworkSecurityGroup = &network.SecurityGroup{
ID: &secGroup,
}
} else {
subnetObj.SubnetPropertiesFormat.NetworkSecurityGroup = nil
}
subnets = append(subnets, *subnetObj)
}
}
properties := &network.VirtualNetworkPropertiesFormat{
AddressSpace: &network.AddressSpace{
AddressPrefixes: &prefixes,
},
DhcpOptions: &network.DhcpOptions{
DNSServers: &dnses,
},
Subnets: &subnets,
}
// finally; return the struct:
return properties, nil
}
func resourceAzureSubnetHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s", m["name"].(string)))
buf.WriteString(fmt.Sprintf("%s", m["address_prefix"].(string)))
if v, ok := m["security_group"]; ok {
buf.WriteString(v.(string))
}
return hashcode.String(buf.String())
}
func getExistingSubnet(ctx context.Context, resGroup string, vnetName string, subnetName string, meta interface{}) (*network.Subnet, error) {
//attempt to retrieve existing subnet from the server
existingSubnet := network.Subnet{}
subnetClient := meta.(*ArmClient).subnetClient
resp, err := subnetClient.Get(ctx, resGroup, vnetName, subnetName, "")
if err != nil {
if resp.StatusCode == http.StatusNotFound {
return &existingSubnet, nil
}
//raise an error if there was an issue other than 404 in getting subnet properties
return nil, err
}
existingSubnet.SubnetPropertiesFormat = &network.SubnetPropertiesFormat{}
existingSubnet.SubnetPropertiesFormat.AddressPrefix = resp.SubnetPropertiesFormat.AddressPrefix
if resp.SubnetPropertiesFormat.NetworkSecurityGroup != nil {
existingSubnet.SubnetPropertiesFormat.NetworkSecurityGroup = resp.SubnetPropertiesFormat.NetworkSecurityGroup
}
if resp.SubnetPropertiesFormat.RouteTable != nil {
existingSubnet.SubnetPropertiesFormat.RouteTable = resp.SubnetPropertiesFormat.RouteTable
}
if resp.SubnetPropertiesFormat.IPConfigurations != nil {
ips := make([]string, 0, len(*resp.SubnetPropertiesFormat.IPConfigurations))
for _, ip := range *resp.SubnetPropertiesFormat.IPConfigurations {
ips = append(ips, *ip.ID)
}
existingSubnet.SubnetPropertiesFormat.IPConfigurations = resp.SubnetPropertiesFormat.IPConfigurations
}
return &existingSubnet, nil
}
func expandAzureRmVirtualNetworkVirtualNetworkSecurityGroupNames(d *schema.ResourceData) ([]string, error) {
nsgNames := make([]string, 0)
if v, ok := d.GetOk("subnet"); ok {
subnets := v.(*schema.Set).List()
for _, subnet := range subnets {
subnet, ok := subnet.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("[ERROR] Subnet should be a Hash - was '%+v'", subnet)
}
networkSecurityGroupId := subnet["security_group"].(string)
if networkSecurityGroupId != "" {
nsgName, err := parseNetworkSecurityGroupName(networkSecurityGroupId)
if err != nil {
return nil, err
}
if !sliceContainsValue(nsgNames, nsgName) {
nsgNames = append(nsgNames, nsgName)
}
}
}
}
return nsgNames, nil
}