-
Notifications
You must be signed in to change notification settings - Fork 984
Expand file tree
/
Copy pathresource_github_repository_environment.go
More file actions
396 lines (341 loc) · 10.9 KB
/
resource_github_repository_environment.go
File metadata and controls
396 lines (341 loc) · 10.9 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
package github
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/google/go-github/v88/github"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceGithubRepositoryEnvironment() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
StateUpgraders: []schema.StateUpgrader{
{
Type: resourceGithubRepositoryEnvironmentV0().CoreConfigSchema().ImpliedType(),
Upgrade: resourceGithubRepositoryEnvironmentStateUpgradeV0,
Version: 0,
},
},
Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Required: true,
Description: "The repository of the environment.",
},
"repository_id": {
Description: "The ID of the GitHub repository.",
Type: schema.TypeInt,
Computed: true,
},
"environment": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of the environment.",
},
"can_admins_bypass": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Can Admins bypass deployment protections",
},
"prevent_self_review": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Prevent users from approving workflows runs that they triggered.",
},
"wait_timer": {
Type: schema.TypeInt,
Optional: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.IntBetween(0, 43200)),
Description: "Amount of time to delay a job after the job is initially triggered.",
},
"reviewers": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The environment reviewers configuration.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"teams": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeInt},
Optional: true,
MaxItems: 6,
Description: "Up to 6 IDs for teams who may review jobs that reference the environment. Reviewers must have at least read access to the repository. Only one of the required reviewers needs to approve the job for it to proceed.",
},
"users": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeInt},
Optional: true,
MaxItems: 6,
Description: "Up to 6 IDs for users who may review jobs that reference the environment. Reviewers must have at least read access to the repository. Only one of the required reviewers needs to approve the job for it to proceed.",
},
},
},
},
"deployment_branch_policy": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "The deployment branch policy configuration",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"protected_branches": {
Type: schema.TypeBool,
Required: true,
Description: "Whether only branches with branch protection rules can deploy to this environment.",
},
"custom_branch_policies": {
Type: schema.TypeBool,
Required: true,
Description: "Whether only branches that match the specified name patterns can deploy to this environment.",
},
},
},
},
},
CustomizeDiff: customdiff.All(
diffRepository,
resourceGithubRepositoryEnvironmentDiff,
),
CreateContext: resourceGithubRepositoryEnvironmentCreate,
ReadContext: resourceGithubRepositoryEnvironmentRead,
UpdateContext: resourceGithubRepositoryEnvironmentUpdate,
DeleteContext: resourceGithubRepositoryEnvironmentDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceGithubRepositoryEnvironmentImport,
},
}
}
func resourceGithubRepositoryEnvironmentDiff(_ context.Context, d *schema.ResourceDiff, _ any) error {
if d.Id() == "" {
return nil
}
if v, ok := d.GetOk("reviewers"); ok {
if c, ok := v.([]any); ok && len(c) > 0 {
if o, ok := c[0].(map[string]any); ok {
count := 0
if t, ok := o["teams"]; ok {
if s, ok := t.(*schema.Set); ok {
count += s.Len()
}
}
if u, ok := o["users"]; ok {
if s, ok := u.(*schema.Set); ok {
count += s.Len()
}
}
if count > 6 {
return fmt.Errorf("a maximum of 6 reviewers (users and teams combined) can be set for an environment")
}
}
}
}
return nil
}
func resourceGithubRepositoryEnvironmentCreate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
meta := m.(*Owner)
client := meta.v3client
owner := meta.name
repoName := d.Get("repository").(string)
envName := d.Get("environment").(string)
updateData := createUpdateEnvironmentData(d)
_, _, err := client.Repositories.CreateUpdateEnvironment(ctx, owner, repoName, url.PathEscape(envName), &updateData)
if err != nil {
return diag.FromErr(err)
}
id, err := buildID(repoName, escapeIDPart(envName))
if err != nil {
return diag.FromErr(err)
}
d.SetId(id)
repo, _, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
return diag.FromErr(err)
}
if err := d.Set("repository_id", int(repo.GetID())); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceGithubRepositoryEnvironmentRead(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
ctx = tflog.SetField(ctx, "id", d.Id())
meta := m.(*Owner)
client := meta.v3client
owner := meta.name
repoName := d.Get("repository").(string)
envName := d.Get("environment").(string)
env, _, err := client.Repositories.GetEnvironment(ctx, owner, repoName, url.PathEscape(envName))
if err != nil {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotFound {
tflog.Info(ctx, "Repository environment not found, removing from state.", map[string]any{"repository": repoName, "environment": envName})
d.SetId("")
return nil
}
}
return diag.FromErr(err)
}
if err := d.Set("wait_timer", nil); err != nil {
return diag.FromErr(err)
}
if err := d.Set("can_admins_bypass", env.CanAdminsBypass); err != nil {
return diag.FromErr(err)
}
for _, pr := range env.ProtectionRules {
switch pr.GetType() {
case "wait_timer":
if err = d.Set("wait_timer", pr.WaitTimer); err != nil {
return diag.FromErr(err)
}
case "required_reviewers":
teams := make([]int64, 0)
users := make([]int64, 0)
for _, r := range pr.Reviewers {
switch *r.Type {
case "Team":
if r.Reviewer.(*github.Team).ID != nil {
teams = append(teams, *r.Reviewer.(*github.Team).ID)
}
case "User":
if r.Reviewer.(*github.User).ID != nil {
users = append(users, *r.Reviewer.(*github.User).ID)
}
}
}
if err = d.Set("reviewers", []any{
map[string]any{
"teams": teams,
"users": users,
},
}); err != nil {
return diag.FromErr(err)
}
if err = d.Set("prevent_self_review", pr.PreventSelfReview); err != nil {
return diag.FromErr(err)
}
}
}
if env.DeploymentBranchPolicy != nil {
if err = d.Set("deployment_branch_policy", []any{
map[string]any{
"protected_branches": env.DeploymentBranchPolicy.ProtectedBranches,
"custom_branch_policies": env.DeploymentBranchPolicy.CustomBranchPolicies,
},
}); err != nil {
return diag.FromErr(err)
}
} else {
if err := d.Set("deployment_branch_policy", []any{}); err != nil {
return diag.FromErr(err)
}
}
return nil
}
func resourceGithubRepositoryEnvironmentUpdate(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
meta := m.(*Owner)
client := meta.v3client
owner := meta.name
repoName := d.Get("repository").(string)
envName := d.Get("environment").(string)
updateData := createUpdateEnvironmentData(d)
_, _, err := client.Repositories.CreateUpdateEnvironment(ctx, owner, repoName, url.PathEscape(envName), &updateData)
if err != nil {
return diag.FromErr(err)
}
id, err := buildID(repoName, escapeIDPart(envName))
if err != nil {
return diag.FromErr(err)
}
d.SetId(id)
return nil
}
func resourceGithubRepositoryEnvironmentDelete(ctx context.Context, d *schema.ResourceData, m any) diag.Diagnostics {
meta := m.(*Owner)
client := meta.v3client
owner := meta.name
repoName := d.Get("repository").(string)
envName := d.Get("environment").(string)
_, err := client.Repositories.DeleteEnvironment(ctx, owner, repoName, url.PathEscape(envName))
if err != nil {
return diag.FromErr(deleteResourceOn404AndSwallow304OtherwiseReturnError(err, d, "environment (%s)", envName))
}
return nil
}
func resourceGithubRepositoryEnvironmentImport(ctx context.Context, d *schema.ResourceData, m any) ([]*schema.ResourceData, error) {
meta := m.(*Owner)
client := meta.v3client
owner := meta.name
repoName, envNamePart, err := parseID2(d.Id())
if err != nil {
return nil, fmt.Errorf("invalid id (%s), expected format <repository>:<environment>", d.Id())
}
repo, _, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
return nil, fmt.Errorf("failed to retrieve repository %s: %w", repoName, err)
}
if err := d.Set("repository", repoName); err != nil {
return nil, err
}
if err := d.Set("repository_id", int(repo.GetID())); err != nil {
return nil, err
}
if err := d.Set("environment", unescapeIDPart(envNamePart)); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
}
func createUpdateEnvironmentData(d *schema.ResourceData) github.CreateUpdateEnvironment {
data := github.CreateUpdateEnvironment{}
if v, ok := d.GetOk("wait_timer"); ok {
data.WaitTimer = new(v.(int))
}
data.CanAdminsBypass = new(d.Get("can_admins_bypass").(bool))
data.PreventSelfReview = new(d.Get("prevent_self_review").(bool))
if v, ok := d.GetOk("reviewers"); ok {
envReviewers := make([]*github.EnvReviewers, 0)
for _, team := range expandReviewers(v, "teams") {
envReviewers = append(envReviewers, &github.EnvReviewers{
Type: new("Team"),
ID: new(team),
})
}
for _, user := range expandReviewers(v, "users") {
envReviewers = append(envReviewers, &github.EnvReviewers{
Type: new("User"),
ID: new(user),
})
}
data.Reviewers = envReviewers
}
if v, ok := d.GetOk("deployment_branch_policy"); ok {
policy := v.([]any)[0].(map[string]any)
data.DeploymentBranchPolicy = &github.BranchPolicy{
ProtectedBranches: new(policy["protected_branches"].(bool)),
CustomBranchPolicies: new(policy["custom_branch_policies"].(bool)),
}
}
return data
}
func expandReviewers(v any, target string) []int64 {
res := make([]int64, 0)
m := v.([]any)[0]
if m != nil {
if v, ok := m.(map[string]any)[target]; ok {
vL := v.(*schema.Set).List()
for _, v := range vL {
res = append(res, int64(v.(int)))
}
}
}
return res
}