forked from launchdarkly/terraform-provider-launchdarkly
/
environments_helper.go
269 lines (242 loc) · 8.25 KB
/
environments_helper.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
package launchdarkly
import (
"context"
"fmt"
"log"
"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"
ldapi "github.com/launchdarkly/api-client-go/v7"
)
// baseEnvironmentSchema covers the overlap between the data source and resource schemas
// certain attributes are required for the resource that are not for the data source and so those
// will need to be differentiated
func baseEnvironmentSchema(forProject bool) map[string]*schema.Schema {
return map[string]*schema.Schema{
KEY: {
Type: schema.TypeString,
Required: true,
Description: "A project-unique key for the new environment",
// Don't force new if the environment schema will be nested in a project
ForceNew: !forProject,
ValidateDiagFunc: validateKey(),
},
API_KEY: {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
MOBILE_KEY: {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
CLIENT_SIDE_ID: {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
DEFAULT_TTL: {
Type: schema.TypeInt,
Optional: true,
Default: 0,
// Default TTL should be between 0 and 60 minutes: https://docs.launchdarkly.com/docs/environments
Description: "The TTL for the environment. This must be between 0 and 60 minutes. The TTL setting only applies to environments using the PHP SDK",
ValidateDiagFunc: validation.ToDiagFunc(validation.IntBetween(0, 60)),
},
SECURE_MODE: {
Default: false,
Type: schema.TypeBool,
Optional: true,
Description: "Whether or not to use secure mode. Secure mode ensures a user of the client-side SDK cannot impersonate another user",
},
DEFAULT_TRACK_EVENTS: {
Default: false,
Type: schema.TypeBool,
Optional: true,
Description: "Whether or not to default to sending data export events for flags created in the environment",
},
REQUIRE_COMMENTS: {
Default: false,
Type: schema.TypeBool,
Optional: true,
Description: "Whether or not to require comments for flag and segment changes in this environment",
},
CONFIRM_CHANGES: {
Default: false,
Type: schema.TypeBool,
Optional: true,
Description: "Whether or not to require confirmation for flag and segment changes in this environment",
},
TAGS: tagsSchema(),
APPROVAL_SETTINGS: approvalSchema(),
}
}
func getEnvironmentUpdatePatches(oldConfig, config map[string]interface{}) ([]ldapi.PatchOperation, error) {
// Always include required fields
name := config[NAME]
color := config[COLOR]
patches := []ldapi.PatchOperation{
patchReplace("/name", name),
patchReplace("/color", color),
}
// Add optional fields if they exist
defaultTtl, ok := config[DEFAULT_TTL]
if ok {
patches = append(patches, patchReplace("/defaultTtl", defaultTtl))
}
secureMode, ok := config[SECURE_MODE]
if ok {
patches = append(patches, patchReplace("/secureMode", secureMode))
}
defaultTrackEvents, ok := config[DEFAULT_TRACK_EVENTS]
if ok {
patches = append(patches, patchReplace("/defaultTrackEvents", defaultTrackEvents))
}
requireComments, ok := config[REQUIRE_COMMENTS]
if ok {
patches = append(patches, patchReplace("/requireComments", requireComments))
}
confirmChanges, ok := config[CONFIRM_CHANGES]
if ok {
patches = append(patches, patchReplace("/confirmChanges", confirmChanges))
}
tags, ok := config[TAGS]
if ok {
envTags := stringsFromSchemaSet(tags.(*schema.Set))
patches = append(patches, patchReplace("/tags", &envTags))
}
var oldApprovalSettings []interface{}
if oldSettings, ok := oldConfig[APPROVAL_SETTINGS]; ok {
oldApprovalSettings = oldSettings.([]interface{})
}
newApprovalSettings := config[APPROVAL_SETTINGS]
approvalPatches, err := approvalPatchFromSettings(oldApprovalSettings, newApprovalSettings)
if err != nil {
return []ldapi.PatchOperation{}, err
}
patches = append(patches, approvalPatches...)
return patches, nil
}
func environmentSchema(forProject bool) map[string]*schema.Schema {
schemaMap := baseEnvironmentSchema(forProject)
schemaMap[NAME] = &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The name of the new environment",
}
schemaMap[COLOR] = &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "A color swatch (as an RGB hex value with no leading '#', e.g. C8C8C8)",
}
return schemaMap
}
func dataSourceEnvironmentSchema(forProject bool) map[string]*schema.Schema {
schemaMap := baseEnvironmentSchema(forProject)
schemaMap[NAME] = &schema.Schema{
Type: schema.TypeString,
Computed: true,
}
schemaMap[COLOR] = &schema.Schema{
Type: schema.TypeString,
Computed: true,
}
return schemaMap
}
func environmentPostsFromResourceData(d *schema.ResourceData) []ldapi.EnvironmentPost {
schemaEnvList := d.Get(ENVIRONMENTS).([]interface{})
envs := make([]ldapi.EnvironmentPost, len(schemaEnvList))
for i, env := range schemaEnvList {
envs[i] = environmentPostFromResourceData(env)
}
return envs
}
func environmentPostFromResourceData(env interface{}) ldapi.EnvironmentPost {
envMap := env.(map[string]interface{})
envPost := ldapi.EnvironmentPost{
Name: envMap[NAME].(string),
Key: envMap[KEY].(string),
Color: envMap[COLOR].(string),
}
if defaultTTL, ok := envMap[DEFAULT_TTL]; ok {
envPost.DefaultTtl = ldapi.PtrInt32(int32(defaultTTL.(int)))
}
return envPost
}
type envResourceData map[string]interface{}
func environmentsToResourceDataMap(envs []ldapi.Environment) map[string]envResourceData {
envMap := make(map[string]envResourceData, len(envs))
for _, env := range envs {
envMap[env.Key] = environmentToResourceData(env)
}
return envMap
}
func environmentToResourceData(env ldapi.Environment) envResourceData {
envData := envResourceData{
KEY: env.Key,
NAME: env.Name,
API_KEY: env.ApiKey,
MOBILE_KEY: env.MobileKey,
CLIENT_SIDE_ID: env.Id,
COLOR: env.Color,
DEFAULT_TTL: int(env.DefaultTtl),
SECURE_MODE: env.SecureMode,
DEFAULT_TRACK_EVENTS: env.DefaultTrackEvents,
REQUIRE_COMMENTS: env.RequireComments,
CONFIRM_CHANGES: env.ConfirmChanges,
TAGS: env.Tags,
}
if env.ApprovalSettings != nil {
envData[APPROVAL_SETTINGS] = approvalSettingsToResourceData(*env.ApprovalSettings)
}
return envData
}
func rawEnvironmentConfigsToKeyList(rawEnvs []interface{}) []string {
keys := make([]string, 0, len(rawEnvs))
for _, rawEnv := range rawEnvs {
env := rawEnv.(map[string]interface{})
envKey := env[KEY].(string)
keys = append(keys, envKey)
}
return keys
}
func environmentRead(ctx context.Context, d *schema.ResourceData, meta interface{}, isDataSource bool) diag.Diagnostics {
var diags diag.Diagnostics
client := meta.(*Client)
projectKey := d.Get(PROJECT_KEY).(string)
key := d.Get(KEY).(string)
env, res, err := client.ld.EnvironmentsApi.GetEnvironment(client.ctx, projectKey, key).Execute()
if isStatusNotFound(res) && !isDataSource {
log.Printf("[WARN] failed to find environment with key %q in project %q, removing from state", key, projectKey)
diags = append(diags, diag.Diagnostic{
Severity: diag.Warning,
Summary: fmt.Sprintf("[WARN] failed to find environment with key %q in project %q, removing from state", key, projectKey),
})
d.SetId("")
return diags
}
if err != nil {
return diag.Errorf("failed to get environment with key %q for project key: %q: %v", key, projectKey, handleLdapiErr(err))
}
d.SetId(projectKey + "/" + key)
_ = d.Set(KEY, env.Key)
_ = d.Set(NAME, env.Name)
_ = d.Set(API_KEY, env.ApiKey)
_ = d.Set(MOBILE_KEY, env.MobileKey)
_ = d.Set(CLIENT_SIDE_ID, env.Id)
_ = d.Set(COLOR, env.Color)
_ = d.Set(DEFAULT_TTL, int(env.DefaultTtl))
_ = d.Set(SECURE_MODE, env.SecureMode)
_ = d.Set(DEFAULT_TRACK_EVENTS, env.DefaultTrackEvents)
_ = d.Set(TAGS, env.Tags)
_ = d.Set(REQUIRE_COMMENTS, env.RequireComments)
_ = d.Set(CONFIRM_CHANGES, env.ConfirmChanges)
if env.ApprovalSettings != nil {
err = d.Set(APPROVAL_SETTINGS, approvalSettingsToResourceData(*env.ApprovalSettings))
if err != nil {
return diag.FromErr(err)
}
}
return diags
}