forked from cloudflare/terraform-provider-cloudflare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_cloudflare_pages_project.go
382 lines (339 loc) · 13.6 KB
/
resource_cloudflare_pages_project.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
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
package provider
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/MakeNowJust/heredoc/v2"
"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceCloudflarePagesProject() *schema.Resource {
return &schema.Resource{
Schema: resourceCloudflarePagesProjectSchema(),
CreateContext: resourceCloudflarePagesProjectCreate,
ReadContext: resourceCloudflarePagesProjectRead,
UpdateContext: resourceCloudflarePagesProjectUpdate,
DeleteContext: resourceCloudflarePagesProjectDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceCloudflarePagesProjectImport,
},
Description: heredoc.Doc(`
Provides a resource which manages Cloudflare Pages projects.
`),
}
}
func buildDeploymentConfig(environment interface{}) cloudflare.PagesProjectDeploymentConfigEnvironment {
config := cloudflare.PagesProjectDeploymentConfigEnvironment{}
parsed := environment.(map[string]interface{})
deploymentVariables := cloudflare.EnvironmentVariableMap{}
for key, value := range parsed {
switch key {
case "environment_variables":
variables := value.(map[string]interface{})
for i, variable := range variables {
envVar := cloudflare.EnvironmentVariable{
Value: variable.(string),
Type: cloudflare.PlainText,
}
deploymentVariables[i] = &envVar
}
break
case "kv_namespaces":
namespace := cloudflare.NamespaceBindingMap{}
variables := value.(map[string]interface{})
for i, variable := range variables {
namespace[i] = &cloudflare.NamespaceBindingValue{Value: variable.(string)}
}
config.KvNamespaces = namespace
break
case "durable_object_namespaces":
namespace := cloudflare.NamespaceBindingMap{}
variables := value.(map[string]interface{})
for i, variable := range variables {
namespace[i] = &cloudflare.NamespaceBindingValue{Value: variable.(string)}
}
config.DoNamespaces = namespace
break
case "d1_databases":
bindingMap := cloudflare.D1BindingMap{}
variables := value.(map[string]interface{})
for i, variable := range variables {
bindingMap[i] = &cloudflare.D1Binding{ID: variable.(string)}
}
config.D1Databases = bindingMap
break
case "r2_buckets":
bindingMap := cloudflare.R2BindingMap{}
variables := value.(map[string]interface{})
for i, variable := range variables {
bindingMap[i] = &cloudflare.R2BindingValue{Name: variable.(string)}
}
config.R2Bindings = bindingMap
break
case "compatibility_date":
config.CompatibilityDate = value.(string)
break
case "compatibility_flags":
for _, item := range value.([]interface{}) {
config.CompatibilityFlags = append(config.CompatibilityFlags, item.(string))
}
break
case "fail_open":
config.FailOpen = value.(bool)
break
case "always_use_latest_compatibility_date":
config.AlwaysUseLatestCompatibilityDate = value.(bool)
break
case "usage_model":
config.UsageModel = cloudflare.UsageModel(value.(string))
break
case "service_binding":
serviceMap := cloudflare.ServiceBindingMap{}
for _, item := range value.(*schema.Set).List() {
data := item.(map[string]interface{})
serviceMap[data["name"].(string)] = &cloudflare.ServiceBinding{
Service: data["service"].(string),
Environment: data["environment"].(string),
}
}
config.ServiceBindings = serviceMap
break
}
}
config.EnvVars = deploymentVariables
return config
}
func parseDeploymentConfig(deployment cloudflare.PagesProjectDeploymentConfigEnvironment) (returnValue []map[string]interface{}) {
config := make(map[string]interface{})
config["compatibility_date"] = deployment.CompatibilityDate
config["compatibility_flags"] = deployment.CompatibilityFlags
config["fail_open"] = deployment.FailOpen
config["always_use_latest_compatibility_date"] = deployment.AlwaysUseLatestCompatibilityDate
config["usage_model"] = deployment.UsageModel
deploymentVars := map[string]string{}
//secretsBinding := &schema.Set{F: schema.HashResource(secretTextBindingResource)}
for key, value := range deployment.EnvVars {
if value.Type == cloudflare.PlainText {
deploymentVars[key] = value.Value
}
}
config["environment_variables"] = deploymentVars
deploymentVars = map[string]string{}
for key, value := range deployment.KvNamespaces {
deploymentVars[key] = value.Value
}
config["kv_namespaces"] = deploymentVars
deploymentVars = map[string]string{}
for key, value := range deployment.DoNamespaces {
deploymentVars[key] = value.Value
}
config["durable_object_namespaces"] = deploymentVars
deploymentVars = map[string]string{}
for key, value := range deployment.R2Bindings {
deploymentVars[key] = value.Name
}
config["r2_buckets"] = deploymentVars
deploymentVars = map[string]string{}
for key, value := range deployment.D1Databases {
deploymentVars[key] = value.ID
}
config["d1_databases"] = deploymentVars
serviceBindings := &schema.Set{F: schema.HashResource(serviceBindingResource)}
for key, value := range deployment.ServiceBindings {
serviceBindings.Add(map[string]interface{}{
"name": key,
"service": value.Service,
"environment": value.Environment,
})
}
config["service_binding"] = serviceBindings
returnValue = append(returnValue, config)
return
}
func buildPagesProject(d *schema.ResourceData) cloudflare.PagesProject {
project := cloudflare.PagesProject{}
project.Name = d.Get("name").(string)
project.ProductionBranch = d.Get("production_branch").(string)
if _, ok := d.GetOk("build_config"); ok {
buildConfig := cloudflare.PagesProjectBuildConfig{}
if buildCommand, ok := d.GetOk("build_config.0.build_command"); ok {
buildConfig.BuildCommand = buildCommand.(string)
}
if destinationDir, ok := d.GetOk("build_config.0.destination_dir"); ok {
buildConfig.DestinationDir = destinationDir.(string)
}
if rootDir, ok := d.GetOk("build_config.0.root_dir"); ok {
buildConfig.RootDir = rootDir.(string)
}
if webAnalyticsTag, ok := d.GetOk("build_config.0.web_analytics_tag"); ok {
buildConfig.WebAnalyticsTag = webAnalyticsTag.(string)
}
if webAnalyticsToken, ok := d.GetOk("build_config.0.web_analytics_token"); ok {
buildConfig.WebAnalyticsToken = webAnalyticsToken.(string)
}
project.BuildConfig = buildConfig
}
source := cloudflare.PagesProjectSource{}
if _, ok := d.GetOk("source"); ok {
if sourceType, ok := d.GetOk("source.0.type"); ok {
source.Type = sourceType.(string)
}
if _, ok := d.GetOk("source.0.config"); ok {
sourceConfig := cloudflare.PagesProjectSourceConfig{}
if sourceOwner, ok := d.GetOk("source.0.config.0.owner"); ok {
sourceConfig.Owner = sourceOwner.(string)
}
if sourceRepoName, ok := d.GetOk("source.0.config.0.repo_name"); ok {
sourceConfig.RepoName = sourceRepoName.(string)
}
if sourceProductionBranch, ok := d.GetOk("source.0.config.0.production_branch"); ok {
sourceConfig.ProductionBranch = sourceProductionBranch.(string)
}
if sourcePRComments, ok := d.GetOk("source.0.config.0.pr_comments_enabled"); ok {
sourceConfig.PRCommentsEnabled = sourcePRComments.(bool)
}
if sourceDeploymentsEnabled, ok := d.GetOk("source.0.config.0.deployments_enabled"); ok {
sourceConfig.DeploymentsEnabled = sourceDeploymentsEnabled.(bool)
}
if productionBranch, ok := d.GetOk("source.0.config.0.production_branch"); ok {
sourceConfig.ProductionBranch = productionBranch.(string)
}
if productionBranchEnable, ok := d.GetOk("source.0.config.0.production_deployment_enabled"); ok {
sourceConfig.ProductionDeploymentsEnabled = productionBranchEnable.(bool)
}
if previewBranchIncludes, ok := d.GetOk("source.0.config.0.preview_branch_includes"); ok {
for _, item := range previewBranchIncludes.([]interface{}) {
sourceConfig.PreviewBranchIncludes = append(sourceConfig.PreviewBranchIncludes, item.(string))
}
}
if previewBranchExcludes, ok := d.GetOk("source.0.config.0.preview_branch_excludes"); ok {
for _, item := range previewBranchExcludes.([]interface{}) {
sourceConfig.PreviewBranchExcludes = append(sourceConfig.PreviewBranchExcludes, item.(string))
}
}
if previewDeploymentSetting, ok := d.GetOk("source.0.config.0.preview_deployment_setting"); ok {
sourceConfig.PreviewDeploymentSetting = cloudflare.PagesPreviewDeploymentSetting(previewDeploymentSetting.(string))
}
source.Config = &sourceConfig
}
project.Source = &source
}
if previewConfig, ok := d.GetOk("deployment_configs.0.preview.0"); ok {
project.DeploymentConfigs.Preview = buildDeploymentConfig(previewConfig)
}
if productionConfig, ok := d.GetOk("deployment_configs.0.production.0"); ok {
project.DeploymentConfigs.Production = buildDeploymentConfig(productionConfig)
}
return project
}
func resourceCloudflarePagesProjectRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)
project, err := client.PagesProject(ctx, accountID, d.Id())
if err != nil {
return diag.FromErr(fmt.Errorf("error reading cloudflare pages project %q: %w", d.Id(), err))
}
tflog.Debug(ctx, fmt.Sprintf("Cloudflare Pages Project Response: %#v", project))
d.Set("subdomain", project.SubDomain)
d.Set("production_branch", project.ProductionBranch)
d.Set("account_id", accountID)
d.Set("domains", project.Domains)
d.Set("created_on", project.CreatedOn.Format(time.RFC3339))
if project.Source != nil {
var source []map[string]interface{}
source = append(source, map[string]interface{}{
"type": project.Source.Type,
"config": []map[string]interface{}{
{
"owner": project.Source.Config.Owner,
"repo_name": project.Source.Config.RepoName,
"production_branch": project.Source.Config.ProductionBranch,
"pr_comments_enabled": project.Source.Config.PRCommentsEnabled,
"deployments_enabled": project.Source.Config.DeploymentsEnabled,
"production_deployment_enabled": project.Source.Config.ProductionDeploymentsEnabled,
"preview_branch_includes": project.Source.Config.PreviewBranchIncludes,
"preview_branch_excludes": project.Source.Config.PreviewBranchExcludes,
"preview_deployment_setting": project.Source.Config.PreviewDeploymentSetting,
},
},
},
)
d.Set("source", source)
}
emptyProjectBuildConfig := cloudflare.PagesProjectBuildConfig{}
if project.BuildConfig != emptyProjectBuildConfig {
var buildConfig []map[string]interface{}
buildConfig = append(buildConfig, map[string]interface{}{
"build_command": project.BuildConfig.BuildCommand,
"destination_dir": project.BuildConfig.DestinationDir,
"root_dir": project.BuildConfig.RootDir,
"web_analytics_tag": project.BuildConfig.WebAnalyticsTag,
"web_analytics_token": project.BuildConfig.WebAnalyticsToken,
},
)
d.Set("build_config", buildConfig)
}
var deploymentConfigs []map[string]interface{}
deploymentConfig := make(map[string]interface{})
deploymentConfig["preview"] = parseDeploymentConfig(project.DeploymentConfigs.Preview)
deploymentConfig["production"] = parseDeploymentConfig(project.DeploymentConfigs.Production)
deploymentConfigs = append(deploymentConfigs, deploymentConfig)
d.Set("deployment_configs", deploymentConfigs)
return nil
}
func resourceCloudflarePagesProjectCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)
pageProject := buildPagesProject(d)
project, err := client.CreatePagesProject(ctx, accountID, pageProject)
if err != nil {
return diag.FromErr(fmt.Errorf("error creating cloudflare pages project %q: %w", pageProject.Name, err))
}
d.SetId(project.Name)
return resourceCloudflarePagesProjectRead(ctx, d, meta)
}
func resourceCloudflarePagesProjectUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)
pageProject := buildPagesProject(d)
_, err := client.UpdatePagesProject(ctx, accountID, d.Id(), pageProject)
if err != nil {
return diag.FromErr(fmt.Errorf("error updating cloudflare pages project %q: %w", d.Id(), err))
}
return resourceCloudflarePagesProjectRead(ctx, d, meta)
}
func resourceCloudflarePagesProjectDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*cloudflare.API)
accountID := d.Get("account_id").(string)
err := client.DeletePagesProject(ctx, accountID, d.Id())
if err != nil {
return diag.FromErr(fmt.Errorf("error deleting cloudflare pages project %q: %w", d.Id(), err))
}
return nil
}
func resourceCloudflarePagesProjectImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(*cloudflare.API)
// split the id so we can look up
idAttr := strings.SplitN(d.Id(), "/", 2)
var accountID string
var projectName string
if len(idAttr) == 2 {
accountID = idAttr[0]
projectName = idAttr[1]
} else {
return nil, fmt.Errorf("invalid id %q specified, should be in format \"accountID/project-name\" for import", d.Id())
}
project, err := client.PagesProject(ctx, accountID, projectName)
if err != nil {
return nil, fmt.Errorf("Unable to find record with ID %q: %w", d.Id(), err)
}
tflog.Info(ctx, fmt.Sprintf("Found project: %s", project.Name))
d.SetId(project.Name)
d.Set("name", project.Name)
d.Set("account_id", accountID)
resourceCloudflarePagesProjectRead(ctx, d, meta)
return []*schema.ResourceData{d}, nil
}