-
Notifications
You must be signed in to change notification settings - Fork 961
Expand file tree
/
Copy pathresource_github_organization_inherited_runner_group_settings.go
More file actions
383 lines (323 loc) · 12.8 KB
/
resource_github_organization_inherited_runner_group_settings.go
File metadata and controls
383 lines (323 loc) · 12.8 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
package github
import (
"context"
"fmt"
"log"
"net/http"
"strconv"
"github.com/google/go-github/v83/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceGithubOrganizationInheritedRunnerGroupSettings() *schema.Resource {
return &schema.Resource{
Description: "Manages organization-level settings for an enterprise Actions runner group inherited by the organization.",
CreateContext: resourceGithubOrganizationInheritedRunnerGroupSettingsCreate,
ReadContext: resourceGithubOrganizationInheritedRunnerGroupSettingsRead,
UpdateContext: resourceGithubOrganizationInheritedRunnerGroupSettingsUpdate,
DeleteContext: resourceGithubOrganizationInheritedRunnerGroupSettingsDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceGithubOrganizationInheritedRunnerGroupSettingsImport,
},
Schema: map[string]*schema.Schema{
"organization": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The GitHub organization name.",
},
"enterprise_runner_group_name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the enterprise runner group inherited by the organization.",
},
"runner_group_id": {
Type: schema.TypeInt,
Computed: true,
Description: "The ID of the inherited enterprise runner group in the organization.",
},
"inherited": {
Type: schema.TypeBool,
Computed: true,
Description: "Whether this runner group is inherited from the enterprise.",
},
"visibility": {
Type: schema.TypeString,
Optional: true,
Default: "selected",
Description: "The visibility of the runner group. Can be 'all', 'selected', or 'private'.",
ValidateDiagFunc: validation.ToDiagFunc(validation.StringInSlice([]string{"all", "selected", "private"}, false)),
},
"selected_repository_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
Set: schema.HashInt,
Optional: true,
Description: "List of repository IDs that can access the runner group. Only applicable when visibility is set to 'selected'.",
},
"allows_public_repositories": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether public repositories can be added to the runner group.",
},
"restricted_to_workflows": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "If 'true', the runner group will be restricted to running only the workflows specified in the 'selected_workflows' array. Defaults to 'false'.",
},
"selected_workflows": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Description: "List of workflows the runner group should be allowed to run. This setting will be ignored unless restricted_to_workflows is set to 'true'.",
},
},
}
}
func findInheritedEnterpriseRunnerGroupByName(client *github.Client, ctx context.Context, org string, name string) (*github.RunnerGroup, error) {
opts := &github.ListOrgRunnerGroupOptions{
ListOptions: github.ListOptions{
PerPage: maxPerPage,
},
}
for {
groups, resp, err := client.Actions.ListOrganizationRunnerGroups(ctx, org, opts)
if err != nil {
return nil, err
}
for _, group := range groups.RunnerGroups {
if group.GetInherited() && group.GetName() == name {
return group, nil
}
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
return nil, fmt.Errorf("inherited enterprise runner group '%s' not found in organization '%s'. Ensure the enterprise runner group is shared with this organization", name, org)
}
func resourceGithubOrganizationInheritedRunnerGroupSettingsCreate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
org := d.Get("organization").(string)
enterpriseRunnerGroupName := d.Get("enterprise_runner_group_name").(string)
visibility := d.Get("visibility").(string)
allowsPublicRepositories := d.Get("allows_public_repositories").(bool)
restrictedToWorkflows := d.Get("restricted_to_workflows").(bool)
selectedRepositories, hasSelectedRepositories := d.GetOk("selected_repository_ids")
selectedWorkflows := []string{}
if workflows, ok := d.GetOk("selected_workflows"); ok {
for _, workflow := range workflows.([]any) {
selectedWorkflows = append(selectedWorkflows, workflow.(string))
}
}
// Find the inherited enterprise runner group by name
runnerGroup, err := findInheritedEnterpriseRunnerGroupByName(client, ctx, org, enterpriseRunnerGroupName)
if err != nil {
return diag.FromErr(err)
}
runnerGroupID := runnerGroup.GetID()
id, err := buildID(org, strconv.FormatInt(runnerGroupID, 10))
if err != nil {
return diag.FromErr(err)
}
d.SetId(id)
if err := d.Set("runner_group_id", int(runnerGroupID)); err != nil {
return diag.FromErr(err)
}
if err := d.Set("inherited", runnerGroup.GetInherited()); err != nil {
return diag.FromErr(err)
}
// Update runner group settings
updateReq := github.UpdateRunnerGroupRequest{
Visibility: github.Ptr(visibility),
AllowsPublicRepositories: github.Ptr(allowsPublicRepositories),
RestrictedToWorkflows: github.Ptr(restrictedToWorkflows),
SelectedWorkflows: selectedWorkflows,
}
_, _, err = client.Actions.UpdateOrganizationRunnerGroup(ctx, org, runnerGroupID, updateReq)
if err != nil {
return diag.Errorf("failed to update runner group: %s", err)
}
// Set repository access if visibility is "selected"
if visibility == "selected" && hasSelectedRepositories {
selectedRepositoryIDs := []int64{}
for _, id := range selectedRepositories.(*schema.Set).List() {
selectedRepositoryIDs = append(selectedRepositoryIDs, int64(id.(int)))
}
repoAccessReq := github.SetRepoAccessRunnerGroupRequest{
SelectedRepositoryIDs: selectedRepositoryIDs,
}
_, err = client.Actions.SetRepositoryAccessRunnerGroup(ctx, org, runnerGroupID, repoAccessReq)
if err != nil {
return diag.Errorf("failed to set repository access: %s", err)
}
}
return nil
}
func resourceGithubOrganizationInheritedRunnerGroupSettingsRead(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
org := d.Get("organization").(string)
runnerGroupID := int64(d.Get("runner_group_id").(int))
// Get the runner group details
runnerGroup, _, err := client.Actions.GetOrganizationRunnerGroup(ctx, org, runnerGroupID)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok {
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[INFO] Removing actions organization runner group %s from state because it no longer exists in GitHub",
d.Id())
d.SetId("")
return nil
}
}
return diag.FromErr(err)
}
if err := d.Set("inherited", runnerGroup.GetInherited()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("visibility", runnerGroup.GetVisibility()); err != nil {
return diag.FromErr(err)
}
// Get repository access list only if visibility is "selected"
if runnerGroup.GetVisibility() == "selected" {
selectedRepositoryIDs := []int64{}
opts := &github.ListOptions{
PerPage: maxPerPage,
}
for {
repos, resp, err := client.Actions.ListRepositoryAccessRunnerGroup(ctx, org, runnerGroupID, opts)
if err != nil {
return diag.Errorf("failed to list repository access: %s", err)
}
for _, repo := range repos.Repositories {
selectedRepositoryIDs = append(selectedRepositoryIDs, repo.GetID())
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
if err := d.Set("selected_repository_ids", selectedRepositoryIDs); err != nil {
return diag.FromErr(err)
}
} else {
if err := d.Set("selected_repository_ids", []int64{}); err != nil {
return diag.FromErr(err)
}
}
if err := d.Set("allows_public_repositories", runnerGroup.GetAllowsPublicRepositories()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("restricted_to_workflows", runnerGroup.GetRestrictedToWorkflows()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("selected_workflows", runnerGroup.SelectedWorkflows); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceGithubOrganizationInheritedRunnerGroupSettingsUpdate(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
org := d.Get("organization").(string)
runnerGroupID := int64(d.Get("runner_group_id").(int))
visibility := d.Get("visibility").(string)
selectedRepositories, hasSelectedRepositories := d.GetOk("selected_repository_ids")
// Update runner group settings if any relevant fields changed
if d.HasChange("visibility") || d.HasChange("allows_public_repositories") || d.HasChange("restricted_to_workflows") || d.HasChange("selected_workflows") {
allowsPublicRepositories := d.Get("allows_public_repositories").(bool)
restrictedToWorkflows := d.Get("restricted_to_workflows").(bool)
selectedWorkflows := []string{}
if workflows, ok := d.GetOk("selected_workflows"); ok {
for _, workflow := range workflows.([]any) {
selectedWorkflows = append(selectedWorkflows, workflow.(string))
}
}
updateReq := github.UpdateRunnerGroupRequest{
Visibility: github.Ptr(visibility),
AllowsPublicRepositories: github.Ptr(allowsPublicRepositories),
RestrictedToWorkflows: github.Ptr(restrictedToWorkflows),
SelectedWorkflows: selectedWorkflows,
}
_, _, err := client.Actions.UpdateOrganizationRunnerGroup(ctx, org, runnerGroupID, updateReq)
if err != nil {
return diag.Errorf("failed to update runner group: %s", err)
}
}
// Update repository access if changed and visibility is "selected"
if d.HasChange("selected_repository_ids") && visibility == "selected" && hasSelectedRepositories {
selectedRepositoryIDs := []int64{}
for _, id := range selectedRepositories.(*schema.Set).List() {
selectedRepositoryIDs = append(selectedRepositoryIDs, int64(id.(int)))
}
repoAccessReq := github.SetRepoAccessRunnerGroupRequest{
SelectedRepositoryIDs: selectedRepositoryIDs,
}
_, err := client.Actions.SetRepositoryAccessRunnerGroup(ctx, org, runnerGroupID, repoAccessReq)
if err != nil {
return diag.Errorf("failed to set repository access: %s", err)
}
}
return nil
}
func resourceGithubOrganizationInheritedRunnerGroupSettingsDelete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
client := meta.(*Owner).v3client
org := d.Get("organization").(string)
runnerGroupID := int64(d.Get("runner_group_id").(int))
log.Printf("[INFO] Removing repository access for runner group: %s", d.Id())
// Reset to "all" visibility and clear repository access
updateReq := github.UpdateRunnerGroupRequest{
Visibility: github.Ptr("all"),
}
_, _, err := client.Actions.UpdateOrganizationRunnerGroup(ctx, org, runnerGroupID, updateReq)
if err != nil {
// If the runner group doesn't exist, that's fine
if ghErr, ok := err.(*github.ErrorResponse); ok {
if ghErr.Response.StatusCode == http.StatusNotFound {
return nil
}
}
return diag.Errorf("failed to reset runner group visibility: %s", err)
}
return nil
}
func resourceGithubOrganizationInheritedRunnerGroupSettingsImport(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
org, identifier, err := parseID2(d.Id())
if err != nil {
return nil, fmt.Errorf("invalid import ID format, expected 'organization:enterprise_runner_group_name' or 'organization:organization_runner_group_id'")
}
client := meta.(*Owner).v3client
var runnerGroup *github.RunnerGroup
// Try to parse as ID first
if id, parseErr := strconv.ParseInt(identifier, 10, 64); parseErr == nil {
// It's an ID - get the runner group and verify it's inherited
runnerGroup, _, err = client.Actions.GetOrganizationRunnerGroup(ctx, org, id)
if err != nil {
return nil, fmt.Errorf("failed to get runner group: %w", err)
}
} else {
// It's a name - find the inherited enterprise runner group
runnerGroup, err = findInheritedEnterpriseRunnerGroupByName(client, ctx, org, identifier)
if err != nil {
return nil, err
}
}
// Verify the runner group is inherited from the enterprise
if !runnerGroup.GetInherited() {
return nil, fmt.Errorf("runner group '%s' is not inherited from the enterprise. This resource only manages inherited enterprise runner groups", runnerGroup.GetName())
}
id, err := buildID(org, strconv.FormatInt(runnerGroup.GetID(), 10))
if err != nil {
return nil, err
}
d.SetId(id)
d.Set("organization", org)
d.Set("enterprise_runner_group_name", runnerGroup.GetName())
d.Set("runner_group_id", int(runnerGroup.GetID()))
d.Set("inherited", runnerGroup.GetInherited())
return []*schema.ResourceData{d}, nil
}