forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_azure_virtual_network.go
367 lines (300 loc) · 10.2 KB
/
resource_azure_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
package azure
import (
"fmt"
"log"
"github.com/Azure/azure-sdk-for-go/management"
"github.com/Azure/azure-sdk-for-go/management/virtualnetwork"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)
const (
virtualNetworkRetrievalError = "Error retrieving Virtual Network Configuration: %s"
)
func resourceAzureVirtualNetwork() *schema.Resource {
return &schema.Resource{
Create: resourceAzureVirtualNetworkCreate,
Read: resourceAzureVirtualNetworkRead,
Update: resourceAzureVirtualNetworkUpdate,
Delete: resourceAzureVirtualNetworkDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"address_space": &schema.Schema{
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dns_servers_names": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"subnet": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"address_prefix": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"security_group": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
Set: resourceAzureSubnetHash,
},
"location": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
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.vnetMutex.Lock()
defer ac.vnetMutex.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)
}
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
}
func resourceAzureVirtualNetworkUpdate(d *schema.ResourceData, meta interface{}) error {
ac := meta.(*Client)
mc := ac.mgmtClient
vnetClient := ac.vnetClient
// 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.vnetMutex.Lock()
defer ac.vnetMutex.Unlock()
nc, err := vnetClient.GetVirtualNetworkConfiguration()
if err != nil {
return fmt.Errorf(virtualNetworkRetrievalError, err)
}
found := false
for i, n := range nc.Configuration.VirtualNetworkSites {
if n.Name == d.Id() {
network := createVirtualNetwork(d)
nc.Configuration.VirtualNetworkSites[i] = network
found = true
}
}
if !found {
return fmt.Errorf("Virtual Network %s does not exists!", d.Id())
}
req, err := vnetClient.SetVirtualNetworkConfiguration(nc)
if err != nil {
return fmt.Errorf("Error updating Virtual Network %s: %s", d.Id(), err)
}
// Wait until the virtual network is updated
if err := mc.WaitForOperation(req, nil); err != nil {
return fmt.Errorf("Error waiting for Virtual Network %s to be updated: %s", d.Id(), err)
}
if err := associateSecurityGroups(d, meta); err != nil {
return err
}
return resourceAzureVirtualNetworkRead(d, meta)
}
func resourceAzureVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error {
ac := meta.(*Client)
mc := ac.mgmtClient
vnetClient := ac.vnetClient
// 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.vnetMutex.Lock()
defer ac.vnetMutex.Unlock()
nc, err := vnetClient.GetVirtualNetworkConfiguration()
if err != nil {
return fmt.Errorf(virtualNetworkRetrievalError, err)
}
filtered := nc.Configuration.VirtualNetworkSites[:0]
for _, n := range nc.Configuration.VirtualNetworkSites {
if n.Name != d.Id() {
filtered = append(filtered, n)
}
}
nc.Configuration.VirtualNetworkSites = filtered
req, err := vnetClient.SetVirtualNetworkConfiguration(nc)
if err != nil {
return fmt.Errorf("Error deleting Virtual Network %s: %s", d.Id(), err)
}
// Wait until the virtual network is deleted
if err := mc.WaitForOperation(req, nil); err != nil {
return fmt.Errorf("Error waiting for Virtual Network %s to be deleted: %s", d.Id(), err)
}
d.SetId("")
return nil
}
func resourceAzureSubnetHash(v interface{}) int {
m := v.(map[string]interface{})
subnet := m["name"].(string) + m["address_prefix"].(string) + m["security_group"].(string)
return hashcode.String(subnet)
}
func createVirtualNetwork(d *schema.ResourceData) virtualnetwork.VirtualNetworkSite {
// fetch address spaces:
var prefixes []string
for _, prefix := range d.Get("address_space").([]interface{}) {
prefixes = append(prefixes, prefix.(string))
}
// fetch DNS references:
var dnsRefs []virtualnetwork.DNSServerRef
for _, dns := range d.Get("dns_servers_names").([]interface{}) {
dnsRefs = append(dnsRefs, virtualnetwork.DNSServerRef{
Name: dns.(string),
})
}
// Add all subnets that are configured
var subnets []virtualnetwork.Subnet
if rs := d.Get("subnet").(*schema.Set); rs.Len() > 0 {
for _, subnet := range rs.List() {
subnet := subnet.(map[string]interface{})
subnets = append(subnets, virtualnetwork.Subnet{
Name: subnet["name"].(string),
AddressPrefix: subnet["address_prefix"].(string),
})
}
}
return virtualnetwork.VirtualNetworkSite{
Name: d.Get("name").(string),
Location: d.Get("location").(string),
AddressSpace: virtualnetwork.AddressSpace{
AddressPrefix: prefixes,
},
DNSServersRef: dnsRefs,
Subnets: subnets,
}
}
func associateSecurityGroups(d *schema.ResourceData, meta interface{}) error {
azureClient := meta.(*Client)
mc := azureClient.mgmtClient
secGroupClient := azureClient.secGroupClient
virtualNetwork := d.Get("name").(string)
if rs := d.Get("subnet").(*schema.Set); rs.Len() > 0 {
for _, subnet := range rs.List() {
subnet := subnet.(map[string]interface{})
securityGroup := subnet["security_group"].(string)
subnetName := subnet["name"].(string)
// Get the associated (if any) security group
sg, err := secGroupClient.GetNetworkSecurityGroupForSubnet(subnetName, d.Id())
if err != nil && !management.IsResourceNotFoundError(err) {
return fmt.Errorf(
"Error retrieving Network Security Group associations of subnet %s: %s", subnetName, err)
}
// If the desired and actual security group are the same, were done so can just continue
if sg.Name == securityGroup {
continue
}
// If there is an associated security group, make sure we first remove it from the subnet
if sg.Name != "" {
req, err := secGroupClient.RemoveNetworkSecurityGroupFromSubnet(sg.Name, subnetName, virtualNetwork)
if err != nil {
return fmt.Errorf("Error removing Network Security Group %s from subnet %s: %s",
securityGroup, subnetName, err)
}
// Wait until the security group is associated
if err := mc.WaitForOperation(req, nil); err != nil {
return fmt.Errorf(
"Error waiting for Network Security Group %s to be removed from subnet %s: %s",
securityGroup, subnetName, err)
}
}
// If the desired security group is not empty, assign the security group to the subnet
if securityGroup != "" {
req, err := secGroupClient.AddNetworkSecurityToSubnet(securityGroup, subnetName, virtualNetwork)
if err != nil {
return fmt.Errorf("Error associating Network Security Group %s to subnet %s: %s",
securityGroup, subnetName, err)
}
// Wait until the security group is associated
if err := mc.WaitForOperation(req, nil); err != nil {
return fmt.Errorf(
"Error waiting for Network Security Group %s to be associated with subnet %s: %s",
securityGroup, subnetName, err)
}
}
}
}
return nil
}