/
app_service_environment_resource.go
397 lines (331 loc) · 13.5 KB
/
app_service_environment_resource.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package web
import (
"context"
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/web/mgmt/2019-08-01/web"
"github.com/hashicorp/go-azure-helpers/response"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
helpersValidate "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
networkParse "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/parse"
networkValidate "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags"
azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
const (
InternalLoadBalancingModeWebPublishing web.InternalLoadBalancingMode = "Web, Publishing"
)
func resourceArmAppServiceEnvironment() *schema.Resource {
return &schema.Resource{
Create: resourceArmAppServiceEnvironmentCreate,
Read: resourceArmAppServiceEnvironmentRead,
Update: resourceArmAppServiceEnvironmentUpdate,
Delete: resourceArmAppServiceEnvironmentDelete,
Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
_, err := parse.AppServiceEnvironmentID(id)
return err
}),
// Need to find sane values for below, some operations on this resource can take an exceptionally long time
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Hour),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(4 * time.Hour),
Delete: schema.DefaultTimeout(4 * time.Hour),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.AppServiceEnvironmentName,
},
"subnet_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: networkValidate.SubnetID,
},
"internal_load_balancing_mode": {
Type: schema.TypeString,
Optional: true,
Default: string(web.InternalLoadBalancingModeNone),
ValidateFunc: validation.StringInSlice([]string{
string(web.InternalLoadBalancingModeNone),
string(web.InternalLoadBalancingModePublishing),
string(web.InternalLoadBalancingModeWeb),
string(InternalLoadBalancingModeWebPublishing),
}, false),
},
"front_end_scale_factor": {
Type: schema.TypeInt,
Optional: true,
Default: 15,
ValidateFunc: validation.IntBetween(5, 15),
},
"pricing_tier": {
Type: schema.TypeString,
Optional: true,
Default: "I1",
ValidateFunc: validation.StringInSlice([]string{
"I1",
"I2",
"I3",
}, false),
},
"user_whitelisted_ip_ranges": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: helpersValidate.CIDR,
},
},
// TODO in 3.0 Make it "Required"
"resource_group_name": azure.SchemaResourceGroupNameOptionalComputed(),
"tags": tags.ForceNewSchema(),
// Computed
"location": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceArmAppServiceEnvironmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Web.AppServiceEnvironmentsClient
networksClient := meta.(*clients.Client).Network.VnetClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
name := d.Get("name").(string)
internalLoadBalancingMode := d.Get("internal_load_balancing_mode").(string)
t := d.Get("tags").(map[string]interface{})
userWhitelistedIPRangesRaw := d.Get("user_whitelisted_ip_ranges").(*schema.Set).List()
subnetId := d.Get("subnet_id").(string)
subnet, err := networkParse.SubnetID(subnetId)
if err != nil {
return err
}
// TODO: Remove the implicit behavior in new major version.
// Discrepancy of resource group between ASE and Subnet is allowed. While for the sake of
// compatibility, we still allow user to use the resource group of Subnet to be the one for
// ASE implicitly. While allow user to explicitly specify the resource group, which takes higher
// precedence.
resourceGroup := subnet.ResourceGroup
if v, ok := d.GetOk("resource_group_name"); ok {
resourceGroup = v.(string)
}
vnet, err := networksClient.Get(ctx, subnet.ResourceGroup, subnet.VirtualNetworkName, "")
if err != nil {
return fmt.Errorf("Error retrieving Virtual Network %q (Resource Group %q): %+v", subnet.VirtualNetworkName, subnet.ResourceGroup, err)
}
// the App Service Environment has to be in the same location as the Virtual Network
var location string
if loc := vnet.Location; loc != nil {
location = azure.NormalizeLocation(*loc)
} else {
return fmt.Errorf("Error determining Location from Virtual Network %q (Resource Group %q): `location` was nil", subnet.VirtualNetworkName, subnet.ResourceGroup)
}
existing, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing App Service Environment %q (Resource Group %q): %s", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_app_service_environment", *existing.ID)
}
frontEndScaleFactor := d.Get("front_end_scale_factor").(int)
pricingTier := d.Get("pricing_tier").(string)
envelope := web.AppServiceEnvironmentResource{
Location: utils.String(location),
Kind: utils.String("ASEV2"),
AppServiceEnvironment: &web.AppServiceEnvironment{
Name: utils.String(name),
Location: utils.String(location),
InternalLoadBalancingMode: web.InternalLoadBalancingMode(internalLoadBalancingMode),
FrontEndScaleFactor: utils.Int32(int32(frontEndScaleFactor)),
MultiSize: utils.String(convertFromIsolatedSKU(pricingTier)),
VirtualNetwork: &web.VirtualNetworkProfile{
ID: utils.String(subnetId),
Subnet: utils.String(subnet.Name),
},
UserWhitelistedIPRanges: utils.ExpandStringSlice(userWhitelistedIPRangesRaw),
// the SDK is coded primarily for v1, which needs a non-null entry for workerpool, so we construct an empty slice for it
// TODO: remove this hack once https://github.com/Azure/azure-rest-api-specs/pull/8433 has been merged
WorkerPools: &[]web.WorkerPool{{}},
},
Tags: tags.Expand(t),
}
// whilst this returns a future go-autorest has a max number of retries
if _, err := client.CreateOrUpdate(ctx, resourceGroup, name, envelope); err != nil {
return fmt.Errorf("Error creating App Service Environment %q (Resource Group %q): %+v", name, resourceGroup, err)
}
// as such we'll ignore it and use a custom poller instead
if err := waitForAppServiceEnvironmentToStabilize(ctx, client, resourceGroup, name); err != nil {
return fmt.Errorf("Error waiting for the creation of App Service Environment %q (Resource Group %q): %+v", name, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error retrieving App Service Environment %q (Resource Group %q): %+v", name, resourceGroup, err)
}
d.SetId(*read.ID)
return resourceArmAppServiceEnvironmentRead(d, meta)
}
func resourceArmAppServiceEnvironmentUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Web.AppServiceEnvironmentsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.AppServiceEnvironmentID(d.Id())
if err != nil {
return err
}
environment := web.AppServiceEnvironmentPatchResource{
AppServiceEnvironment: &web.AppServiceEnvironment{},
}
if d.HasChange("internal_load_balancing_mode") {
v := d.Get("internal_load_balancing_mode").(string)
environment.AppServiceEnvironment.InternalLoadBalancingMode = web.InternalLoadBalancingMode(v)
}
if d.HasChange("front_end_scale_factor") {
v := d.Get("front_end_scale_factor").(int)
environment.AppServiceEnvironment.FrontEndScaleFactor = utils.Int32(int32(v))
}
if d.HasChange("pricing_tier") {
v := d.Get("pricing_tier").(string)
v = convertFromIsolatedSKU(v)
environment.AppServiceEnvironment.MultiSize = utils.String(v)
}
if d.HasChange("user_whitelisted_ip_ranges") {
v := d.Get("user_whitelisted_ip_ranges").(*schema.Set).List()
environment.UserWhitelistedIPRanges = utils.ExpandStringSlice(v)
}
if _, err := client.Update(ctx, id.ResourceGroup, id.Name, environment); err != nil {
return fmt.Errorf("Error updating App Service Environment %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
if err := waitForAppServiceEnvironmentToStabilize(ctx, client, id.ResourceGroup, id.Name); err != nil {
return fmt.Errorf("Error waiting for Update of App Service Environment %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
return resourceArmAppServiceEnvironmentRead(d, meta)
}
func resourceArmAppServiceEnvironmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Web.AppServiceEnvironmentsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.AppServiceEnvironmentID(d.Id())
if err != nil {
return err
}
existing, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(existing.Response) {
log.Printf("[DEBUG] App Service Environmment %q (Resource Group %q) was not found - removing from state!", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving App Service Environmment %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
d.Set("name", id.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := existing.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
if props := existing.AppServiceEnvironment; props != nil {
d.Set("internal_load_balancing_mode", string(props.InternalLoadBalancingMode))
subnetId := ""
if props.VirtualNetwork != nil && props.VirtualNetwork.ID != nil {
subnetId = *props.VirtualNetwork.ID
}
d.Set("subnet_id", subnetId)
frontendScaleFactor := 0
if props.FrontEndScaleFactor != nil {
frontendScaleFactor = int(*props.FrontEndScaleFactor)
}
d.Set("front_end_scale_factor", frontendScaleFactor)
pricingTier := ""
if props.MultiSize != nil {
pricingTier = convertToIsolatedSKU(*props.MultiSize)
}
d.Set("pricing_tier", pricingTier)
d.Set("user_whitelisted_ip_ranges", props.UserWhitelistedIPRanges)
}
return tags.FlattenAndSet(d, existing.Tags)
}
func resourceArmAppServiceEnvironmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Web.AppServiceEnvironmentsClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.AppServiceEnvironmentID(d.Id())
if err != nil {
return err
}
log.Printf("[DEBUG] Deleting App Service Environment %q (Resource Group %q)", id.Name, id.ResourceGroup)
// TODO: should this behaviour be added to the `features` block?
forceDeleteAllChildren := utils.Bool(false)
future, err := client.Delete(ctx, id.ResourceGroup, id.Name, forceDeleteAllChildren)
if err != nil {
if response.WasNotFound(future.Response()) {
return nil
}
return fmt.Errorf("Error deleting App Service Environment %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
err = future.WaitForCompletionRef(ctx, client.Client)
if err != nil {
if response.WasNotFound(future.Response()) {
return nil
}
return fmt.Errorf("Error waiting for deletion of App Service Environment %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
return nil
}
func waitForAppServiceEnvironmentToStabilize(ctx context.Context, client *web.AppServiceEnvironmentsClient, resourceGroup string, name string) error {
for {
time.Sleep(1 * time.Minute)
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return err
}
if read.AppServiceEnvironment == nil {
return fmt.Errorf("`properties` was nil")
}
state := read.AppServiceEnvironment.ProvisioningState
if state == web.ProvisioningStateSucceeded {
return nil
}
if state == web.ProvisioningStateInProgress {
continue
}
return fmt.Errorf("Unexpected ProvisioningState: %q", state)
}
}
// Note: These are abstractions and possibly subject to change if Azure changes the underlying SKU for Isolated instances.
func convertFromIsolatedSKU(isolated string) (vmSKU string) {
switch isolated {
case "I1":
vmSKU = "Standard_D1_V2"
case "I2":
vmSKU = "Standard_D2_V2"
case "I3":
vmSKU = "Standard_D3_V2"
}
return vmSKU
}
func convertToIsolatedSKU(vmSKU string) (isolated string) {
switch vmSKU {
case "Standard_D1_V2":
isolated = "I1"
case "Standard_D2_V2":
isolated = "I2"
case "Standard_D3_V2":
isolated = "I3"
}
return isolated
}