forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
automation_runbook_resource.go
400 lines (339 loc) · 13 KB
/
automation_runbook_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
package automation
import (
"bytes"
"fmt"
"io"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/preview/automation/mgmt/2018-06-30-preview/automation"
"github.com/gofrs/uuid"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/azure"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/tf"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/clients"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/automation/helper"
"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/tags"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/pluginsdk"
"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 resourceAutomationRunbook() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceAutomationRunbookCreateUpdate,
Read: resourceAutomationRunbookRead,
Update: resourceAutomationRunbookCreateUpdate,
Delete: resourceAutomationRunbookDelete,
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.RunbookID(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.RunbookName(),
},
"automation_account_name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.AutomationAccount(),
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"runbook_type": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.StringInSlice([]string{
string(automation.Graph),
string(automation.GraphPowerShell),
string(automation.GraphPowerShellWorkflow),
string(automation.PowerShell),
string(automation.PowerShellWorkflow),
string(automation.Script),
}, true),
},
"log_progress": {
Type: pluginsdk.TypeBool,
Required: true,
},
"log_verbose": {
Type: pluginsdk.TypeBool,
Required: true,
},
"description": {
Type: pluginsdk.TypeString,
Optional: true,
},
"content": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
AtLeastOneOf: []string{"content", "publish_content_link"},
ValidateFunc: validation.StringIsNotEmpty,
},
"job_schedule": helper.JobScheduleSchema(),
"publish_content_link": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
AtLeastOneOf: []string{"content", "publish_content_link"},
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"uri": {
Type: pluginsdk.TypeString,
Required: true,
},
"version": {
Type: pluginsdk.TypeString,
Optional: true,
},
"hash": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"algorithm": {
Type: pluginsdk.TypeString,
Required: true,
},
"value": {
Type: pluginsdk.TypeString,
Required: true,
},
},
},
},
},
},
},
"tags": tags.Schema(),
},
}
}
func resourceAutomationRunbookCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.RunbookClient
jsClient := meta.(*clients.Client).Automation.JobScheduleClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
log.Printf("[INFO] preparing arguments for AzureRM Automation Runbook creation.")
name := d.Get("name").(string)
accName := d.Get("automation_account_name").(string)
resGroup := d.Get("resource_group_name").(string)
if d.IsNewResource() {
existing, err := client.Get(ctx, resGroup, accName, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing Automation Runbook %q (Account %q / Resource Group %q): %s", name, accName, resGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_automation_runbook", *existing.ID)
}
}
location := azure.NormalizeLocation(d.Get("location").(string))
t := d.Get("tags").(map[string]interface{})
runbookType := automation.RunbookTypeEnum(d.Get("runbook_type").(string))
logProgress := d.Get("log_progress").(bool)
logVerbose := d.Get("log_verbose").(bool)
description := d.Get("description").(string)
parameters := automation.RunbookCreateOrUpdateParameters{
RunbookCreateOrUpdateProperties: &automation.RunbookCreateOrUpdateProperties{
LogVerbose: &logVerbose,
LogProgress: &logProgress,
RunbookType: runbookType,
Description: &description,
},
Location: &location,
Tags: tags.Expand(t),
}
contentLink := expandContentLink(d.Get("publish_content_link").([]interface{}))
if contentLink != nil {
parameters.RunbookCreateOrUpdateProperties.PublishContentLink = contentLink
} else {
parameters.RunbookCreateOrUpdateProperties.Draft = &automation.RunbookDraft{}
}
if _, err := client.CreateOrUpdate(ctx, resGroup, accName, name, parameters); err != nil {
return fmt.Errorf("creating/updating Automation Runbook %q (Account %q / Resource Group %q): %+v", name, accName, resGroup, err)
}
if v, ok := d.GetOk("content"); ok {
content := v.(string)
reader := io.NopCloser(bytes.NewBufferString(content))
draftClient := meta.(*clients.Client).Automation.RunbookDraftClient
if _, err := draftClient.ReplaceContent(ctx, resGroup, accName, name, reader); err != nil {
return fmt.Errorf("setting the draft Automation Runbook %q (Account %q / Resource Group %q): %+v", name, accName, resGroup, err)
}
if _, err := client.Publish(ctx, resGroup, accName, name); err != nil {
return fmt.Errorf("publishing the updated Automation Runbook %q (Account %q / Resource Group %q): %+v", name, accName, resGroup, err)
}
}
read, err := client.Get(ctx, resGroup, accName, name)
if err != nil {
return fmt.Errorf("retrieving Automation Runbook %q (Account %q / Resource Group %q): %+v", name, accName, resGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Automation Runbook %q (Account %q / Resource Group %q) ID", name, accName, resGroup)
}
d.SetId(*read.ID)
for jsIterator, err := jsClient.ListByAutomationAccountComplete(ctx, resGroup, accName, ""); jsIterator.NotDone(); err = jsIterator.NextWithContext(ctx) {
if err != nil {
return fmt.Errorf("loading Automation Account %q Job Schedule List: %+v", accName, err)
}
if props := jsIterator.Value().JobScheduleProperties; props != nil {
if props.Runbook.Name != nil && *props.Runbook.Name == name {
if jsIterator.Value().JobScheduleID == nil || *jsIterator.Value().JobScheduleID == "" {
return fmt.Errorf("job schedule Id is nil or empty listed by Automation Account %q Job Schedule List: %+v", accName, err)
}
jsId, err := uuid.FromString(*jsIterator.Value().JobScheduleID)
if err != nil {
return fmt.Errorf("parsing job schedule Id listed by Automation Account %q Job Schedule List:%v", accName, err)
}
if _, err := jsClient.Delete(ctx, resGroup, accName, jsId); err != nil {
return fmt.Errorf("deleting job schedule Id listed by Automation Account %q Job Schedule List:%v", accName, err)
}
}
}
}
if v, ok := d.GetOk("job_schedule"); ok {
jsMap, err := helper.ExpandAutomationJobSchedule(v.(*pluginsdk.Set).List(), name)
if err != nil {
return err
}
for jsuuid, js := range *jsMap {
if _, err := jsClient.Create(ctx, resGroup, accName, jsuuid, js); err != nil {
return fmt.Errorf("creating Automation Runbook %q Job Schedules (Account %q / Resource Group %q): %+v", name, accName, resGroup, err)
}
}
}
return resourceAutomationRunbookRead(d, meta)
}
func resourceAutomationRunbookRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.RunbookClient
jsClient := meta.(*clients.Client).Automation.JobScheduleClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.RunbookID(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 Runbook %q (Account %q / Resource Group %q): %+v", id.Name, id.AutomationAccountName, id.ResourceGroup, err)
}
d.Set("name", id.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
d.Set("automation_account_name", id.AutomationAccountName)
if props := resp.RunbookProperties; props != nil {
d.Set("log_verbose", props.LogVerbose)
d.Set("log_progress", props.LogProgress)
d.Set("runbook_type", props.RunbookType)
d.Set("description", props.Description)
}
response, err := client.GetContent(ctx, id.ResourceGroup, id.AutomationAccountName, id.Name)
if err != nil {
if utils.ResponseWasNotFound(response.Response) {
d.Set("content", "")
} else {
return fmt.Errorf("retrieving content for Automation Runbook %q (Account %q / Resource Group %q): %+v", id.Name, id.AutomationAccountName, id.ResourceGroup, err)
}
}
if v := response.Value; v != nil {
if contentBytes := *response.Value; contentBytes != nil {
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(contentBytes); err != nil {
return fmt.Errorf("reading from Automation Runbook buffer %q: %+v", id.Name, err)
}
content := buf.String()
d.Set("content", content)
}
}
jsMap := make(map[uuid.UUID]automation.JobScheduleProperties)
for jsIterator, err := jsClient.ListByAutomationAccountComplete(ctx, id.ResourceGroup, id.AutomationAccountName, ""); jsIterator.NotDone(); err = jsIterator.NextWithContext(ctx) {
if err != nil {
return fmt.Errorf("loading Automation Account %q Job Schedule List: %+v", id.AutomationAccountName, err)
}
if props := jsIterator.Value().JobScheduleProperties; props != nil {
if props.Runbook.Name != nil && *props.Runbook.Name == id.Name {
if jsIterator.Value().JobScheduleID == nil || *jsIterator.Value().JobScheduleID == "" {
return fmt.Errorf("job schedule Id is nil or empty listed by Automation Account %q Job Schedule List: %+v", id.AutomationAccountName, err)
}
jsId, err := uuid.FromString(*jsIterator.Value().JobScheduleID)
if err != nil {
return fmt.Errorf("parsing job schedule Id listed by Automation Account %q Job Schedule List:%v", id.AutomationAccountName, err)
}
jsMap[jsId] = *props
}
}
}
jobSchedule := helper.FlattenAutomationJobSchedule(jsMap)
if err := d.Set("job_schedule", jobSchedule); err != nil {
return fmt.Errorf("setting `job_schedule`: %+v", err)
}
if t := resp.Tags; t != nil {
return tags.FlattenAndSet(d, t)
}
return nil
}
func resourceAutomationRunbookDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.RunbookClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.RunbookID(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 nil
}
return fmt.Errorf("issuing AzureRM delete request for Automation Runbook '%s': %+v", id.Name, err)
}
return nil
}
func expandContentLink(inputs []interface{}) *automation.ContentLink {
if len(inputs) == 0 || inputs[0] == nil {
return nil
}
input := inputs[0].(map[string]interface{})
uri := input["uri"].(string)
version := input["version"].(string)
hashes := input["hash"].([]interface{})
if len(hashes) > 0 {
hash := hashes[0].(map[string]interface{})
hashValue := hash["value"].(string)
hashAlgorithm := hash["algorithm"].(string)
return &automation.ContentLink{
URI: &uri,
Version: &version,
ContentHash: &automation.ContentHash{
Algorithm: &hashAlgorithm,
Value: &hashValue,
},
}
}
return &automation.ContentLink{
URI: &uri,
Version: &version,
}
}