forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
automation_schedule_resource.go
442 lines (384 loc) · 14.4 KB
/
automation_schedule_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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package automation
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/preview/automation/mgmt/2018-06-30-preview/automation"
"github.com/Azure/go-autorest/autorest/date"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/azure"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/tf"
azvalidate "github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/validate"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/clients"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/automation/parse"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/automation/validate"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/pluginsdk"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/set"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/suppress"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/validation"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/timeouts"
"github.com/kevinklinger/terraform-provider-azurerm/v2/utils"
)
func resourceAutomationSchedule() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceAutomationScheduleCreateUpdate,
Read: resourceAutomationScheduleRead,
Update: resourceAutomationScheduleCreateUpdate,
Delete: resourceAutomationScheduleDelete,
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.ScheduleID(id)
return err
}),
Timeouts: &pluginsdk.ResourceTimeout{
Create: pluginsdk.DefaultTimeout(30 * time.Minute),
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
Update: pluginsdk.DefaultTimeout(30 * time.Minute),
Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.ScheduleName(),
},
"resource_group_name": azure.SchemaResourceGroupName(),
"automation_account_name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.AutomationAccount(),
},
"frequency": {
Type: pluginsdk.TypeString,
Required: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.StringInSlice([]string{
string(automation.Day),
string(automation.Hour),
string(automation.Month),
string(automation.OneTime),
string(automation.Week),
}, true),
},
// ignored when frequency is `OneTime`
"interval": {
Type: pluginsdk.TypeInt,
Optional: true,
Computed: true, // defaults to 1 if frequency is not OneTime
ValidateFunc: validation.IntBetween(1, 100),
},
"start_time": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: suppress.RFC3339Time,
ValidateFunc: validation.IsRFC3339Time,
// defaults to now + 7 minutes in create function if not set
},
"expiry_time": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true, // same as start time when OneTime, ridiculous value when recurring: "9999-12-31T15:59:00-08:00"
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.IsRFC3339Time,
},
"description": {
Type: pluginsdk.TypeString,
Optional: true,
},
"timezone": {
Type: pluginsdk.TypeString,
Optional: true,
Default: "UTC", // TODO 3.0 Change the default to Etc/UTC
ValidateFunc: azvalidate.AzureTimeZoneString(),
},
"week_days": {
Type: pluginsdk.TypeSet,
Optional: true,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeString,
ValidateFunc: validation.StringInSlice([]string{
string(automation.Monday),
string(automation.Tuesday),
string(automation.Wednesday),
string(automation.Thursday),
string(automation.Friday),
string(automation.Saturday),
string(automation.Sunday),
}, true),
},
Set: set.HashStringIgnoreCase,
ConflictsWith: []string{"month_days", "monthly_occurrence"},
},
"month_days": {
Type: pluginsdk.TypeSet,
Optional: true,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeInt,
ValidateFunc: validation.All(
validation.IntBetween(-1, 31),
validation.IntNotInSlice([]int{0}),
),
},
Set: set.HashInt,
ConflictsWith: []string{"week_days", "monthly_occurrence"},
},
"monthly_occurrence": {
Type: pluginsdk.TypeList,
Optional: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"day": {
Type: pluginsdk.TypeString,
Required: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.StringInSlice([]string{
string(automation.Monday),
string(automation.Tuesday),
string(automation.Wednesday),
string(automation.Thursday),
string(automation.Friday),
string(automation.Saturday),
string(automation.Sunday),
}, true),
},
"occurrence": {
Type: pluginsdk.TypeInt,
Required: true,
ValidateFunc: validation.All(
validation.IntBetween(-1, 5),
validation.IntNotInSlice([]int{0}),
),
},
},
},
ConflictsWith: []string{"week_days", "month_days"},
},
},
CustomizeDiff: pluginsdk.CustomizeDiffShim(func(ctx context.Context, diff *pluginsdk.ResourceDiff, v interface{}) error {
frequency := strings.ToLower(diff.Get("frequency").(string))
interval, _ := diff.GetOk("interval")
if frequency == "onetime" && interval.(int) > 0 {
return fmt.Errorf("`interval` cannot be set when frequency is `OneTime`")
}
_, hasWeekDays := diff.GetOk("week_days")
if hasWeekDays && frequency != "week" {
return fmt.Errorf("`week_days` can only be set when frequency is `Week`")
}
_, hasMonthDays := diff.GetOk("month_days")
if hasMonthDays && frequency != "month" {
return fmt.Errorf("`month_days` can only be set when frequency is `Month`")
}
_, hasMonthlyOccurrences := diff.GetOk("monthly_occurrence")
if hasMonthlyOccurrences && frequency != "month" {
return fmt.Errorf("`monthly_occurrence` can only be set when frequency is `Month`")
}
return nil
}),
}
}
func resourceAutomationScheduleCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.ScheduleClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
log.Printf("[INFO] preparing arguments for AzureRM Automation Schedule creation.")
name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string)
accountName := d.Get("automation_account_name").(string)
if d.IsNewResource() {
existing, err := client.Get(ctx, resGroup, accountName, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing Automation Schedule %q (Account %q / Resource Group %q): %s", name, accountName, resGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_automation_schedule", *existing.ID)
}
}
frequency := d.Get("frequency").(string)
timeZone := d.Get("timezone").(string)
description := d.Get("description").(string)
parameters := automation.ScheduleCreateOrUpdateParameters{
Name: &name,
ScheduleCreateOrUpdateProperties: &automation.ScheduleCreateOrUpdateProperties{
Description: &description,
Frequency: automation.ScheduleFrequency(frequency),
TimeZone: &timeZone,
},
}
properties := parameters.ScheduleCreateOrUpdateProperties
// start time can default to now + 7 (5 could be invalid by the time the API is called)
if v, ok := d.GetOk("start_time"); ok {
t, _ := time.Parse(time.RFC3339, v.(string)) // should be validated by the schema
duration := time.Duration(5) * time.Minute
if time.Until(t) < duration {
return fmt.Errorf("start_time is %q and should be at least %q in the future", t, duration)
}
properties.StartTime = &date.Time{Time: t}
} else {
properties.StartTime = &date.Time{Time: time.Now().Add(time.Duration(7) * time.Minute)}
}
if v, ok := d.GetOk("expiry_time"); ok {
t, _ := time.Parse(time.RFC3339, v.(string)) // should be validated by the schema
properties.ExpiryTime = &date.Time{Time: t}
}
// only pay attention to interval if frequency is not OneTime, and default it to 1 if not set
if properties.Frequency != automation.OneTime {
if v, ok := d.GetOk("interval"); ok {
properties.Interval = utils.Int32(int32(v.(int)))
} else {
properties.Interval = 1
}
}
// only pay attention to the advanced schedule fields if frequency is either Week or Month
if properties.Frequency == automation.Week || properties.Frequency == automation.Month {
properties.AdvancedSchedule = expandArmAutomationScheduleAdvanced(d, d.Id() != "")
}
if _, err := client.CreateOrUpdate(ctx, resGroup, accountName, name, parameters); err != nil {
return err
}
read, err := client.Get(ctx, resGroup, accountName, name)
if err != nil {
return err
}
if read.ID == nil {
return fmt.Errorf("Cannot read Automation Schedule '%s' (resource group %s) ID", name, resGroup)
}
d.SetId(*read.ID)
return resourceAutomationScheduleRead(d, meta)
}
func resourceAutomationScheduleRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.ScheduleClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.ScheduleID(d.Id())
if err != nil {
return err
}
resp, err := client.Get(ctx, id.ResourceGroup, id.AutomationAccountName, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("making Read request on AzureRM Automation Schedule '%s': %+v", id.Name, err)
}
d.Set("name", id.Name)
d.Set("resource_group_name", id.ResourceGroup)
d.Set("automation_account_name", id.AutomationAccountName)
d.Set("frequency", string(resp.Frequency))
if v := resp.StartTime; v != nil {
d.Set("start_time", v.Format(time.RFC3339))
}
if v := resp.ExpiryTime; v != nil {
d.Set("expiry_time", v.Format(time.RFC3339))
}
if v := resp.Interval; v != nil {
d.Set("interval", v)
}
if v := resp.Description; v != nil {
d.Set("description", v)
}
if v := resp.TimeZone; v != nil {
d.Set("timezone", v)
}
if v := resp.AdvancedSchedule; v != nil {
if err := d.Set("week_days", flattenArmAutomationScheduleAdvancedWeekDays(v)); err != nil {
return fmt.Errorf("setting `week_days`: %+v", err)
}
if err := d.Set("month_days", flattenArmAutomationScheduleAdvancedMonthDays(v)); err != nil {
return fmt.Errorf("setting `month_days`: %+v", err)
}
if err := d.Set("monthly_occurrence", flattenArmAutomationScheduleAdvancedMonthlyOccurrences(v)); err != nil {
return fmt.Errorf("setting `monthly_occurrence`: %+v", err)
}
}
return nil
}
func resourceAutomationScheduleDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.ScheduleClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.ScheduleID(d.Id())
if err != nil {
return err
}
resp, err := client.Delete(ctx, id.ResourceGroup, id.AutomationAccountName, id.Name)
if err != nil {
if !utils.ResponseWasNotFound(resp) {
return fmt.Errorf("issuing AzureRM delete request for Automation Schedule '%s': %+v", id.Name, err)
}
}
return nil
}
func expandArmAutomationScheduleAdvanced(d *pluginsdk.ResourceData, isUpdate bool) *automation.AdvancedSchedule {
expandedAdvancedSchedule := automation.AdvancedSchedule{}
// If frequency is set to `Month` the `week_days` array cannot be set (even empty), otherwise the API returns an error.
// During update it can be set and it will not return an error. Workaround for the APIs behaviour
if v, ok := d.GetOk("week_days"); ok {
weekDays := v.(*pluginsdk.Set).List()
expandedWeekDays := make([]string, len(weekDays))
for i := range weekDays {
expandedWeekDays[i] = weekDays[i].(string)
}
expandedAdvancedSchedule.WeekDays = &expandedWeekDays
} else if isUpdate {
expandedAdvancedSchedule.WeekDays = &[]string{}
}
// Same as above with `week_days`
if v, ok := d.GetOk("month_days"); ok {
monthDays := v.(*pluginsdk.Set).List()
expandedMonthDays := make([]int32, len(monthDays))
for i := range monthDays {
expandedMonthDays[i] = int32(monthDays[i].(int))
}
expandedAdvancedSchedule.MonthDays = &expandedMonthDays
} else if isUpdate {
expandedAdvancedSchedule.MonthDays = &[]int32{}
}
monthlyOccurrences := d.Get("monthly_occurrence").([]interface{})
expandedMonthlyOccurrences := make([]automation.AdvancedScheduleMonthlyOccurrence, len(monthlyOccurrences))
for i := range monthlyOccurrences {
m := monthlyOccurrences[i].(map[string]interface{})
occurrence := int32(m["occurrence"].(int))
expandedMonthlyOccurrences[i] = automation.AdvancedScheduleMonthlyOccurrence{
Occurrence: &occurrence,
Day: automation.ScheduleDay(m["day"].(string)),
}
}
expandedAdvancedSchedule.MonthlyOccurrences = &expandedMonthlyOccurrences
return &expandedAdvancedSchedule
}
func flattenArmAutomationScheduleAdvancedWeekDays(s *automation.AdvancedSchedule) *pluginsdk.Set {
flattenedWeekDays := pluginsdk.NewSet(set.HashStringIgnoreCase, []interface{}{})
if weekDays := s.WeekDays; weekDays != nil {
for _, v := range *weekDays {
flattenedWeekDays.Add(v)
}
}
return flattenedWeekDays
}
func flattenArmAutomationScheduleAdvancedMonthDays(s *automation.AdvancedSchedule) *pluginsdk.Set {
flattenedMonthDays := pluginsdk.NewSet(set.HashInt, []interface{}{})
if monthDays := s.MonthDays; monthDays != nil {
for _, v := range *monthDays {
flattenedMonthDays.Add(int(v))
}
}
return flattenedMonthDays
}
func flattenArmAutomationScheduleAdvancedMonthlyOccurrences(s *automation.AdvancedSchedule) []map[string]interface{} {
flattenedMonthlyOccurrences := make([]map[string]interface{}, 0)
if monthlyOccurrences := s.MonthlyOccurrences; monthlyOccurrences != nil {
for _, v := range *monthlyOccurrences {
f := make(map[string]interface{})
f["day"] = v.Day
f["occurrence"] = int(*v.Occurrence)
flattenedMonthlyOccurrences = append(flattenedMonthlyOccurrences, f)
}
}
return flattenedMonthlyOccurrences
}