forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_github_actions_hosted_runner.go
More file actions
563 lines (497 loc) · 14.3 KB
/
resource_github_actions_hosted_runner.go
File metadata and controls
563 lines (497 loc) · 14.3 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
package github
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"regexp"
"strconv"
"time"
"github.com/google/go-github/v82/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceGithubActionsHostedRunner() *schema.Resource {
return &schema.Resource{
Create: resourceGithubActionsHostedRunnerCreate,
Read: resourceGithubActionsHostedRunnerRead,
Update: resourceGithubActionsHostedRunnerUpdate,
Delete: resourceGithubActionsHostedRunnerDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.All(
validation.StringLenBetween(1, 64),
validation.StringMatch(
regexp.MustCompile(`^[a-zA-Z0-9._-]+$`),
"name may only contain alphanumeric characters, '.', '-', and '_'",
),
)),
Description: "Name of the hosted runner. Must be between 1 and 64 characters and may only contain upper and lowercase letters a-z, numbers 0-9, '.', '-', and '_'.",
},
"image": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
Description: "The image ID.",
},
"source": {
Type: schema.TypeString,
Optional: true,
Default: "github",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"github", "partner", "custom"}, false)),
Description: "The image source (github, partner, or custom).",
},
"size_gb": {
Type: schema.TypeInt,
Computed: true,
Description: "The size of the image in GB.",
},
},
},
Description: "Image configuration for the hosted runner. Cannot be changed after creation.",
},
"size": {
Type: schema.TypeString,
Required: true,
Description: "Machine size (e.g., '4-core', '8-core'). Can be updated to scale the runner.",
},
"runner_group_id": {
Type: schema.TypeInt,
Required: true,
Description: "The runner group ID.",
},
"maximum_runners": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.IntAtLeast(1)),
Description: "Maximum number of runners to scale up to.",
},
"public_ip_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether to enable static public IP.",
},
"image_version": {
Type: schema.TypeString,
Optional: true,
Description: "The version of the runner image to deploy. This is relevant only for runners using custom images.",
},
"image_gen": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
Description: "Whether this runner should be used to generate custom images. Cannot be changed after creation.",
},
"id": {
Type: schema.TypeString,
Computed: true,
Description: "The hosted runner ID.",
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: "Current status of the runner.",
},
"platform": {
Type: schema.TypeString,
Computed: true,
Description: "Platform of the runner.",
},
"machine_size_details": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
Description: "Machine size ID.",
},
"cpu_cores": {
Type: schema.TypeInt,
Computed: true,
Description: "Number of CPU cores.",
},
"memory_gb": {
Type: schema.TypeInt,
Computed: true,
Description: "Memory in GB.",
},
"storage_gb": {
Type: schema.TypeInt,
Computed: true,
Description: "Storage in GB.",
},
},
},
Description: "Detailed machine size specifications.",
},
"public_ips": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Computed: true,
Description: "Whether this IP range is enabled.",
},
"prefix": {
Type: schema.TypeString,
Computed: true,
Description: "IP address prefix.",
},
"length": {
Type: schema.TypeInt,
Computed: true,
Description: "Subnet length.",
},
},
},
Description: "List of public IP ranges assigned to this runner.",
},
"last_active_on": {
Type: schema.TypeString,
Computed: true,
Description: "Timestamp when the runner was last active.",
},
},
}
}
func expandImage(imageList []any) map[string]any {
if len(imageList) == 0 {
return nil
}
imageMap := imageList[0].(map[string]any)
result := make(map[string]any)
if id, ok := imageMap["id"].(string); ok {
result["id"] = id
}
if source, ok := imageMap["source"].(string); ok {
result["source"] = source
}
return result
}
func flattenImage(image map[string]any) []any {
if image == nil {
return []any{}
}
result := make(map[string]any)
// Handle id as either string or number
if id, ok := image["id"].(string); ok {
result["id"] = id
} else if id, ok := image["id"].(float64); ok {
result["id"] = fmt.Sprintf("%.0f", id)
}
if source, ok := image["source"].(string); ok {
result["source"] = source
}
if size, ok := image["size"].(float64); ok {
result["size_gb"] = int(size)
}
return []any{result}
}
func flattenMachineSizeDetails(details map[string]any) []any {
if details == nil {
return []any{}
}
result := make(map[string]any)
if id, ok := details["id"].(string); ok {
result["id"] = id
}
if cpuCores, ok := details["cpu_cores"].(float64); ok {
result["cpu_cores"] = int(cpuCores)
}
if memoryGB, ok := details["memory_gb"].(float64); ok {
result["memory_gb"] = int(memoryGB)
}
if storageGB, ok := details["storage_gb"].(float64); ok {
result["storage_gb"] = int(storageGB)
}
return []any{result}
}
func flattenPublicIPs(ips []any) []any {
if ips == nil {
return []any{}
}
result := make([]any, 0, len(ips))
for _, ip := range ips {
ipMap, ok := ip.(map[string]any)
if !ok {
continue
}
ipResult := make(map[string]any)
if enabled, ok := ipMap["enabled"].(bool); ok {
ipResult["enabled"] = enabled
}
if prefix, ok := ipMap["prefix"].(string); ok {
ipResult["prefix"] = prefix
}
if length, ok := ipMap["length"].(float64); ok {
ipResult["length"] = int(length)
}
result = append(result, ipResult)
}
return result
}
func resourceGithubActionsHostedRunnerCreate(d *schema.ResourceData, meta any) error {
err := checkOrganization(meta)
if err != nil {
return err
}
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.Background()
// Build request payload
payload := map[string]any{
"name": d.Get("name").(string),
"image": expandImage(d.Get("image").([]any)),
"size": d.Get("size").(string),
"runner_group_id": d.Get("runner_group_id").(int),
}
if v, ok := d.GetOk("maximum_runners"); ok {
payload["maximum_runners"] = v.(int)
}
if v, ok := d.GetOk("public_ip_enabled"); ok {
payload["enable_static_ip"] = v.(bool)
}
if v, ok := d.GetOk("image_version"); ok {
payload["image_version"] = v.(string)
}
if v, ok := d.GetOk("image_gen"); ok {
payload["image_gen"] = v.(bool)
}
// Create HTTP request
req, err := client.NewRequest("POST", fmt.Sprintf("orgs/%s/actions/hosted-runners", orgName), payload)
if err != nil {
return err
}
var runner map[string]any
_, err = client.Do(ctx, req, &runner)
if err != nil {
var acceptedErr *github.AcceptedError
if !errors.As(err, &acceptedErr) {
return err
}
}
if runner == nil {
return fmt.Errorf("no runner data returned from API")
}
// Set the ID
if id, ok := runner["id"].(float64); ok {
d.SetId(strconv.Itoa(int(id)))
} else {
return fmt.Errorf("failed to get runner ID from response: %+v", runner)
}
return resourceGithubActionsHostedRunnerRead(d, meta)
}
func resourceGithubActionsHostedRunnerRead(d *schema.ResourceData, meta any) error {
err := checkOrganization(meta)
if err != nil {
return err
}
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
runnerID := d.Id()
ctx := context.WithValue(context.Background(), ctxId, runnerID)
// Create GET request
req, err := client.NewRequest("GET", fmt.Sprintf("orgs/%s/actions/hosted-runners/%s", orgName, runnerID), nil)
if err != nil {
return err
}
var runner map[string]any
_, err = client.Do(ctx, req, &runner)
if err != nil {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[WARN] Removing hosted runner %s from state because it no longer exists in GitHub", runnerID)
d.SetId("")
return nil
}
}
return err
}
if runner == nil {
return fmt.Errorf("no runner data returned from API")
}
if name, ok := runner["name"].(string); ok {
if err := d.Set("name", name); err != nil {
return err
}
}
if status, ok := runner["status"].(string); ok {
if err := d.Set("status", status); err != nil {
return err
}
}
if platform, ok := runner["platform"].(string); ok {
if err := d.Set("platform", platform); err != nil {
return err
}
}
if lastActiveOn, ok := runner["last_active_on"].(string); ok {
if err := d.Set("last_active_on", lastActiveOn); err != nil {
return err
}
}
if publicIPEnabled, ok := runner["public_ip_enabled"].(bool); ok {
if err := d.Set("public_ip_enabled", publicIPEnabled); err != nil {
return err
}
}
if image, ok := runner["image"].(map[string]any); ok {
if err := d.Set("image", flattenImage(image)); err != nil {
return err
}
}
if machineSizeDetails, ok := runner["machine_size_details"].(map[string]any); ok {
if err := d.Set("size", machineSizeDetails["id"]); err != nil {
return err
}
if err := d.Set("machine_size_details", flattenMachineSizeDetails(machineSizeDetails)); err != nil {
return err
}
}
if runnerGroupID, ok := runner["runner_group_id"].(float64); ok {
if err := d.Set("runner_group_id", int(runnerGroupID)); err != nil {
return err
}
}
if maxRunners, ok := runner["maximum_runners"].(float64); ok {
if err := d.Set("maximum_runners", int(maxRunners)); err != nil {
return err
}
}
if publicIPs, ok := runner["public_ips"].([]any); ok {
if err := d.Set("public_ips", flattenPublicIPs(publicIPs)); err != nil {
return err
}
}
if imageGen, ok := runner["image_gen"].(bool); ok {
if err := d.Set("image_gen", imageGen); err != nil {
return err
}
}
return nil
}
func resourceGithubActionsHostedRunnerUpdate(d *schema.ResourceData, meta any) error {
err := checkOrganization(meta)
if err != nil {
return err
}
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
runnerID := d.Id()
ctx := context.WithValue(context.Background(), ctxId, runnerID)
payload := make(map[string]any)
if d.HasChange("name") {
payload["name"] = d.Get("name").(string)
}
if d.HasChange("size") {
payload["size"] = d.Get("size").(string)
}
if d.HasChange("runner_group_id") {
payload["runner_group_id"] = d.Get("runner_group_id").(int)
}
if d.HasChange("maximum_runners") {
payload["maximum_runners"] = d.Get("maximum_runners").(int)
}
if d.HasChange("public_ip_enabled") {
payload["enable_static_ip"] = d.Get("public_ip_enabled").(bool)
}
if d.HasChange("image_version") {
payload["image_version"] = d.Get("image_version").(string)
}
if len(payload) == 0 {
return resourceGithubActionsHostedRunnerRead(d, meta)
}
// Create PATCH request
req, err := client.NewRequest("PATCH", fmt.Sprintf("orgs/%s/actions/hosted-runners/%s", orgName, runnerID), payload)
if err != nil {
return err
}
var runner map[string]any
_, err = client.Do(ctx, req, &runner)
if err != nil {
var acceptedErr *github.AcceptedError
if !errors.As(err, &acceptedErr) {
return err
}
}
return resourceGithubActionsHostedRunnerRead(d, meta)
}
func resourceGithubActionsHostedRunnerDelete(d *schema.ResourceData, meta any) error {
err := checkOrganization(meta)
if err != nil {
return err
}
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.Background()
runnerID := d.Id()
// Send DELETE request
req, err := client.NewRequest("DELETE", fmt.Sprintf("orgs/%s/actions/hosted-runners/%s", orgName, runnerID), nil)
if err != nil {
return err
}
resp, err := client.Do(ctx, req, nil)
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil
}
var acceptedErr *github.AcceptedError
if errors.As(err, &acceptedErr) {
return waitForRunnerDeletion(ctx, client, orgName, runnerID, d.Timeout(schema.TimeoutDelete))
}
return err
}
if resp != nil && resp.StatusCode == http.StatusAccepted {
return waitForRunnerDeletion(ctx, client, orgName, runnerID, d.Timeout(schema.TimeoutDelete))
}
return nil
}
func waitForRunnerDeletion(ctx context.Context, client *github.Client, orgName, runnerID string, timeout time.Duration) error {
conf := &retry.StateChangeConf{
Pending: []string{"deleting", "active"},
Target: []string{"deleted"},
Refresh: func() (any, string, error) {
req, err := client.NewRequest("GET", fmt.Sprintf("orgs/%s/actions/hosted-runners/%s", orgName, runnerID), nil)
if err != nil {
return nil, "", err
}
resp, err := client.Do(ctx, req, nil)
if resp != nil && resp.StatusCode == http.StatusNotFound {
return "deleted", "deleted", nil
}
if err != nil {
return nil, "deleting", err
}
return "deleting", "deleting", nil
},
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 5 * time.Second,
}
_, err := conf.WaitForStateContext(ctx)
return err
}