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_organization_secret.go
More file actions
280 lines (245 loc) · 8.66 KB
/
resource_github_actions_organization_secret.go
File metadata and controls
280 lines (245 loc) · 8.66 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
package github
import (
"context"
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"github.com/google/go-github/v67/github"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceGithubActionsOrganizationSecret() *schema.Resource {
return &schema.Resource{
Create: resourceGithubActionsOrganizationSecretCreateOrUpdate,
Read: resourceGithubActionsOrganizationSecretRead,
Delete: resourceGithubActionsOrganizationSecretDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
if err := d.Set("secret_name", d.Id()); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
},
},
// Schema migration added in v6.7.1 to handle the addition of destroy_on_drift field
// Resources created before v6.7.0 need the field populated with default value
SchemaVersion: 1,
MigrateState: resourceGithubActionsOrganizationSecretMigrateState,
Schema: map[string]*schema.Schema{
"secret_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Name of the secret.",
ValidateDiagFunc: validateSecretNameFunc,
},
"encrypted_value": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"plaintext_value"},
Description: "Encrypted value of the secret using the GitHub public key in Base64 format.",
ValidateDiagFunc: toDiagFunc(validation.StringIsBase64, "encrypted_value"),
},
"plaintext_value": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"encrypted_value"},
Description: "Plaintext value of the secret to be encrypted.",
},
"visibility": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: validateValueFunc([]string{"all", "private", "selected"}),
Description: "Configures the access that repositories have to the organization secret. Must be one of 'all', 'private', or 'selected'. 'selected_repository_ids' is required if set to 'selected'.",
},
"selected_repository_ids": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeInt,
},
Set: schema.HashInt,
Optional: true,
ForceNew: true,
Description: "An array of repository ids that can access the organization secret.",
},
"created_at": {
Type: schema.TypeString,
Computed: true,
Description: "Date of 'actions_secret' creation.",
},
"updated_at": {
Type: schema.TypeString,
Computed: true,
Description: "Date of 'actions_secret' update.",
},
"destroy_on_drift": {
Type: schema.TypeBool,
Default: true,
Optional: true,
ForceNew: true,
Description: "Boolean indicating whether to recreate the secret if it's modified outside of Terraform. When `true` (default), Terraform will delete and recreate the secret if it detects external changes. When `false`, Terraform will acknowledge external changes but not recreate the secret.",
},
},
}
}
func resourceGithubActionsOrganizationSecretCreateOrUpdate(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
ctx := context.Background()
secretName := d.Get("secret_name").(string)
plaintextValue := d.Get("plaintext_value").(string)
var encryptedValue string
visibility := d.Get("visibility").(string)
selectedRepositories, hasSelectedRepositories := d.GetOk("selected_repository_ids")
if visibility != "selected" && hasSelectedRepositories {
return fmt.Errorf("cannot use selected_repository_ids without visibility being set to selected")
}
selectedRepositoryIDs := []int64{}
if hasSelectedRepositories {
ids := selectedRepositories.(*schema.Set).List()
for _, id := range ids {
selectedRepositoryIDs = append(selectedRepositoryIDs, int64(id.(int)))
}
}
keyId, publicKey, err := getOrganizationPublicKeyDetails(owner, meta)
if err != nil {
return err
}
if encryptedText, ok := d.GetOk("encrypted_value"); ok {
encryptedValue = encryptedText.(string)
} else {
encryptedBytes, err := encryptPlaintext(plaintextValue, publicKey)
if err != nil {
return err
}
encryptedValue = base64.StdEncoding.EncodeToString(encryptedBytes)
}
// Create an EncryptedSecret and encrypt the plaintext value into it
eSecret := &github.EncryptedSecret{
Name: secretName,
KeyID: keyId,
Visibility: visibility,
SelectedRepositoryIDs: selectedRepositoryIDs,
EncryptedValue: encryptedValue,
}
_, err = client.Actions.CreateOrUpdateOrgSecret(ctx, owner, eSecret)
if err != nil {
return err
}
d.SetId(secretName)
return resourceGithubActionsOrganizationSecretRead(d, meta)
}
func resourceGithubActionsOrganizationSecretRead(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
owner := meta.(*Owner).name
ctx := context.Background()
secret, _, err := client.Actions.GetOrgSecret(ctx, owner, d.Id())
if err != nil {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) {
if ghErr.Response.StatusCode == http.StatusNotFound {
log.Printf("[INFO] Removing actions secret %s from state because it no longer exists in GitHub",
d.Id())
d.SetId("")
return nil
}
}
return err
}
if err = d.Set("created_at", secret.CreatedAt.String()); err != nil {
return err
}
if err = d.Set("visibility", secret.Visibility); err != nil {
return err
}
selectedRepositoryIDs := []int64{}
if secret.Visibility == "selected" {
opt := &github.ListOptions{
PerPage: 30,
}
for {
results, resp, err := client.Actions.ListSelectedReposForOrgSecret(ctx, owner, d.Id(), opt)
if err != nil {
return err
}
for _, repo := range results.Repositories {
selectedRepositoryIDs = append(selectedRepositoryIDs, repo.GetID())
}
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
}
if err = d.Set("selected_repository_ids", selectedRepositoryIDs); err != nil {
return err
}
// This is a drift detection mechanism based on timestamps.
//
// If we do not currently store the "updated_at" field, it means we've only
// just created the resource and the value is most likely what we want it to
// be.
//
// If the resource is changed externally in the meantime then reading back
// the last update timestamp will return a result different than the
// timestamp we've persisted in the state. In that case, we can no longer
// trust that the value (which we don't see) is equal to what we've declared
// previously.
destroyOnDrift := d.Get("destroy_on_drift").(bool)
storedUpdatedAt, hasStoredUpdatedAt := d.GetOk("updated_at")
if hasStoredUpdatedAt && storedUpdatedAt != secret.UpdatedAt.String() {
log.Printf("[INFO] The secret %s has been externally updated in GitHub", d.Id())
if destroyOnDrift {
// Original behavior: mark for recreation
d.SetId("")
return nil
} else {
// Alternative approach: set sensitive values to empty to trigger update plan
// This tells Terraform that the current state is unknown and needs reconciliation
if err = d.Set("encrypted_value", ""); err != nil {
return err
}
if err = d.Set("plaintext_value", ""); err != nil {
return err
}
log.Printf("[INFO] Detected drift but destroy_on_drift=false, clearing sensitive values to trigger update")
}
} else {
// No drift detected, preserve the configured values in state
if err = d.Set("encrypted_value", d.Get("encrypted_value")); err != nil {
return err
}
if err = d.Set("plaintext_value", d.Get("plaintext_value")); err != nil {
return err
}
}
// Always update the timestamp to prevent repeated drift detection
if err = d.Set("updated_at", secret.UpdatedAt.String()); err != nil {
return err
}
return nil
}
func resourceGithubActionsOrganizationSecretDelete(d *schema.ResourceData, meta any) error {
client := meta.(*Owner).v3client
orgName := meta.(*Owner).name
ctx := context.WithValue(context.Background(), ctxId, d.Id())
log.Printf("[INFO] Deleting secret: %s", d.Id())
_, err := client.Actions.DeleteOrgSecret(ctx, orgName, d.Id())
return err
}
func getOrganizationPublicKeyDetails(owner string, meta any) (keyId, pkValue string, err error) {
client := meta.(*Owner).v3client
ctx := context.Background()
publicKey, _, err := client.Actions.GetOrgPublicKey(ctx, owner)
if err != nil {
return keyId, pkValue, err
}
return publicKey.GetKeyID(), publicKey.GetKey(), err
}