forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_fastly_service_v1.go
1872 lines (1664 loc) · 52.9 KB
/
resource_fastly_service_v1.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fastly
import (
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform/helper/schema"
gofastly "github.com/sethvargo/go-fastly"
)
var fastlyNoServiceFoundErr = errors.New("No matching Fastly Service found")
func resourceServiceV1() *schema.Resource {
return &schema.Resource{
Create: resourceServiceV1Create,
Read: resourceServiceV1Read,
Update: resourceServiceV1Update,
Delete: resourceServiceV1Delete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Unique name for this Service",
},
// Active Version represents the currently activated version in Fastly. In
// Terraform, we abstract this number away from the users and manage
// creating and activating. It's used internally, but also exported for
// users to see.
"active_version": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"domain": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The domain that this Service will respond to",
},
"comment": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
},
"condition": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"statement": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The statement used to determine if the condition is met",
StateFunc: func(v interface{}) string {
value := v.(string)
// Trim newlines and spaces, to match Fastly API
return strings.TrimSpace(value)
},
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Required: true,
Description: "A number used to determine the order in which multiple conditions execute. Lower numbers execute first",
},
"type": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Type of the condition, either `REQUEST`, `RESPONSE`, or `CACHE`",
},
},
},
},
"default_ttl": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 3600,
Description: "The default Time-to-live (TTL) for the version",
},
"default_host": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The default hostname for the version",
},
"backend": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// required fields
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "A name for this Backend",
},
"address": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "An IPv4, hostname, or IPv6 address for the Backend",
},
// Optional fields, defaults where they exist
"auto_loadbalance": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Should this Backend be load balanced",
},
"between_bytes_timeout": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 10000,
Description: "How long to wait between bytes in milliseconds",
},
"connect_timeout": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 1000,
Description: "How long to wait for a timeout in milliseconds",
},
"error_threshold": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: "Number of errors to allow before the Backend is marked as down",
},
"first_byte_timeout": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 15000,
Description: "How long to wait for the first bytes in milliseconds",
},
"max_conn": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 200,
Description: "Maximum number of connections for this Backend",
},
"port": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 80,
Description: "The port number Backend responds on. Default 80",
},
"ssl_check_cert": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Be strict on checking SSL certs",
},
// UseSSL is something we want to support in the future, but
// requires SSL setup we don't yet have
// TODO: Provide all SSL fields from https://docs.fastly.com/api/config#backend
// "use_ssl": &schema.Schema{
// Type: schema.TypeBool,
// Optional: true,
// Default: false,
// Description: "Whether or not to use SSL to reach the Backend",
// },
"weight": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 100,
Description: "The portion of traffic to send to a specific origins. Each origin receives weight/total of the traffic.",
},
},
},
},
"force_destroy": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
},
"cache_setting": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// required fields
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "A name to refer to this Cache Setting",
},
"cache_condition": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Condition to check if this Cache Setting applies",
},
"action": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "Action to take",
},
// optional
"stale_ttl": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Description: "Max 'Time To Live' for stale (unreachable) objects.",
Default: 300,
},
"ttl": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Description: "The 'Time To Live' for the object",
},
},
},
},
"gzip": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// required fields
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "A name to refer to this gzip condition",
},
// optional fields
"content_types": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Description: "Content types to apply automatic gzip to",
Elem: &schema.Schema{Type: schema.TypeString},
},
"extensions": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Description: "File extensions to apply automatic gzip to. Do not include '.'",
Elem: &schema.Schema{Type: schema.TypeString},
},
// These fields represent Fastly options that Terraform does not
// currently support
"cache_condition": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Optional name of a CacheCondition to apply.",
},
},
},
},
"header": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// required fields
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "A name to refer to this Header object",
},
"action": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "One of set, append, delete, regex, or regex_repeat",
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
var found bool
for _, t := range []string{"set", "append", "delete", "regex", "regex_repeat"} {
if v.(string) == t {
found = true
}
}
if !found {
es = append(es, fmt.Errorf(
"Fastly Header action is case sensitive and must be one of 'set', 'append', 'delete', 'regex', or 'regex_repeat'; found: %s", v.(string)))
}
return
},
},
"type": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Type to manipulate: request, fetch, cache, response",
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
var found bool
for _, t := range []string{"request", "fetch", "cache", "response"} {
if v.(string) == t {
found = true
}
}
if !found {
es = append(es, fmt.Errorf(
"Fastly Header type is case sensitive and must be one of 'request', 'fetch', 'cache', or 'response'; found: %s", v.(string)))
}
return
},
},
"destination": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Header this affects",
},
// Optional fields, defaults where they exist
"ignore_if_set": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Don't add the header if it is already. (Only applies to 'set' action.). Default `false`",
},
"source": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Variable to be used as a source for the header content (Does not apply to 'delete' action.)",
},
"regex": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Regular expression to use (Only applies to 'regex' and 'regex_repeat' actions.)",
},
"substitution": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Value to substitute in place of regular expression. (Only applies to 'regex' and 'regex_repeat'.)",
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 100,
Description: "Lower priorities execute first. (Default: 100.)",
},
// These fields represent Fastly options that Terraform does not
// currently support
"request_condition": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Optional name of a RequestCondition to apply.",
},
"cache_condition": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Optional name of a CacheCondition to apply.",
},
"response_condition": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Description: "Optional name of a ResponseCondition to apply.",
},
},
},
},
"s3logging": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Required fields
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Unique name to refer to this logging setup",
},
"bucket_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "S3 Bucket name to store logs in",
},
"s3_access_key": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("FASTLY_S3_ACCESS_KEY", ""),
Description: "AWS Access Key",
},
"s3_secret_key": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("FASTLY_S3_SECRET_KEY", ""),
Description: "AWS Secret Key",
},
// Optional fields
"path": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "Path to store the files. Must end with a trailing slash",
},
"domain": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "Bucket endpoint",
},
"gzip_level": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: "Gzip Compression level",
},
"period": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 3600,
Description: "How frequently the logs should be transferred, in seconds (Default 3600)",
},
"format": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "%h %l %u %t %r %>s",
Description: "Apache-style string or VCL variables to use for log formatting",
},
"timestamp_format": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "%Y-%m-%dT%H:%M:%S.000",
Description: "specified timestamp formatting (default `%Y-%m-%dT%H:%M:%S.000`)",
},
},
},
},
"request_setting": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// Required fields
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Unique name to refer to this Request Setting",
},
"request_condition": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "Name of a RequestCondition to apply.",
},
// Optional fields
"max_stale_age": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 60,
Description: "How old an object is allowed to be, in seconds. Default `60`",
},
"force_miss": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Description: "Force a cache miss for the request",
},
"force_ssl": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Description: "Forces the request use SSL",
},
"action": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "Allows you to terminate request handling and immediately perform an action",
},
"bypass_busy_wait": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Description: "Disable collapsed forwarding",
},
"hash_keys": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "Comma separated list of varnish request object fields that should be in the hash key",
},
"xff": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "append",
Description: "X-Forwarded-For options",
},
"timer_support": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Description: "Injects the X-Timer info into the request",
},
"geo_headers": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Description: "Inject Fastly-Geo-Country, Fastly-Geo-City, and Fastly-Geo-Region",
},
"default_host": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Description: "the host header",
},
},
},
},
"vcl": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "A name to refer to this VCL configuration",
},
"content": &schema.Schema{
Type: schema.TypeString,
Required: true,
Description: "The contents of this VCL configuration",
StateFunc: func(v interface{}) string {
switch v.(type) {
case string:
hash := sha1.Sum([]byte(v.(string)))
return hex.EncodeToString(hash[:])
default:
return ""
}
},
},
"main": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Should this VCL configuration be the main configuration",
},
},
},
},
},
}
}
func resourceServiceV1Create(d *schema.ResourceData, meta interface{}) error {
if err := validateVCLs(d); err != nil {
return err
}
conn := meta.(*FastlyClient).conn
service, err := conn.CreateService(&gofastly.CreateServiceInput{
Name: d.Get("name").(string),
Comment: "Managed by Terraform",
})
if err != nil {
return err
}
d.SetId(service.ID)
return resourceServiceV1Update(d, meta)
}
func resourceServiceV1Update(d *schema.ResourceData, meta interface{}) error {
if err := validateVCLs(d); err != nil {
return err
}
conn := meta.(*FastlyClient).conn
// Update Name. No new verions is required for this
if d.HasChange("name") {
_, err := conn.UpdateService(&gofastly.UpdateServiceInput{
ID: d.Id(),
Name: d.Get("name").(string),
})
if err != nil {
return err
}
}
// Once activated, Versions are locked and become immutable. This is true for
// versions that are no longer active. For Domains, Backends, DefaultHost and
// DefaultTTL, a new Version must be created first, and updates posted to that
// Version. Loop these attributes and determine if we need to create a new version first
var needsChange bool
for _, v := range []string{
"domain",
"backend",
"default_host",
"default_ttl",
"header",
"gzip",
"s3logging",
"condition",
"request_setting",
"cache_setting",
"vcl",
} {
if d.HasChange(v) {
needsChange = true
}
}
if needsChange {
latestVersion := d.Get("active_version").(string)
if latestVersion == "" {
// If the service was just created, there is an empty Version 1 available
// that is unlocked and can be updated
latestVersion = "1"
} else {
// Clone the latest version, giving us an unlocked version we can modify
log.Printf("[DEBUG] Creating clone of version (%s) for updates", latestVersion)
newVersion, err := conn.CloneVersion(&gofastly.CloneVersionInput{
Service: d.Id(),
Version: latestVersion,
})
if err != nil {
return err
}
// The new version number is named "Number", but it's actually a string
latestVersion = newVersion.Number
// New versions are not immediately found in the API, or are not
// immediately mutable, so we need to sleep a few and let Fastly ready
// itself. Typically, 7 seconds is enough
log.Printf("[DEBUG] Sleeping 7 seconds to allow Fastly Version to be available")
time.Sleep(7 * time.Second)
}
// update general settings
if d.HasChange("default_host") || d.HasChange("default_ttl") {
opts := gofastly.UpdateSettingsInput{
Service: d.Id(),
Version: latestVersion,
// default_ttl has the same default value of 3600 that is provided by
// the Fastly API, so it's safe to include here
DefaultTTL: uint(d.Get("default_ttl").(int)),
}
if attr, ok := d.GetOk("default_host"); ok {
opts.DefaultHost = attr.(string)
}
log.Printf("[DEBUG] Update Settings opts: %#v", opts)
_, err := conn.UpdateSettings(&opts)
if err != nil {
return err
}
}
// Conditions need to be updated first, as they can be referenced by other
// configuraiton objects (Backends, Request Headers, etc)
// Find difference in Conditions
if d.HasChange("condition") {
// Note: we don't utilize the PUT endpoint to update these objects, we simply
// destroy any that have changed, and create new ones with the updated
// values. This is how Terraform works with nested sub resources, we only
// get the full diff not a partial set item diff. Because this is done
// on a new version of the Fastly Service configuration, this is considered safe
oc, nc := d.GetChange("condition")
if oc == nil {
oc = new(schema.Set)
}
if nc == nil {
nc = new(schema.Set)
}
ocs := oc.(*schema.Set)
ncs := nc.(*schema.Set)
removeConditions := ocs.Difference(ncs).List()
addConditions := ncs.Difference(ocs).List()
// DELETE old Conditions
for _, cRaw := range removeConditions {
cf := cRaw.(map[string]interface{})
opts := gofastly.DeleteConditionInput{
Service: d.Id(),
Version: latestVersion,
Name: cf["name"].(string),
}
log.Printf("[DEBUG] Fastly Conditions Removal opts: %#v", opts)
err := conn.DeleteCondition(&opts)
if err != nil {
return err
}
}
// POST new Conditions
for _, cRaw := range addConditions {
cf := cRaw.(map[string]interface{})
opts := gofastly.CreateConditionInput{
Service: d.Id(),
Version: latestVersion,
Name: cf["name"].(string),
Type: cf["type"].(string),
// need to trim leading/tailing spaces, incase the config has HEREDOC
// formatting and contains a trailing new line
Statement: strings.TrimSpace(cf["statement"].(string)),
Priority: cf["priority"].(int),
}
log.Printf("[DEBUG] Create Conditions Opts: %#v", opts)
_, err := conn.CreateCondition(&opts)
if err != nil {
return err
}
}
}
// Find differences in domains
if d.HasChange("domain") {
od, nd := d.GetChange("domain")
if od == nil {
od = new(schema.Set)
}
if nd == nil {
nd = new(schema.Set)
}
ods := od.(*schema.Set)
nds := nd.(*schema.Set)
remove := ods.Difference(nds).List()
add := nds.Difference(ods).List()
// Delete removed domains
for _, dRaw := range remove {
df := dRaw.(map[string]interface{})
opts := gofastly.DeleteDomainInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
}
log.Printf("[DEBUG] Fastly Domain removal opts: %#v", opts)
err := conn.DeleteDomain(&opts)
if err != nil {
return err
}
}
// POST new Domains
for _, dRaw := range add {
df := dRaw.(map[string]interface{})
opts := gofastly.CreateDomainInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
}
if v, ok := df["comment"]; ok {
opts.Comment = v.(string)
}
log.Printf("[DEBUG] Fastly Domain Addition opts: %#v", opts)
_, err := conn.CreateDomain(&opts)
if err != nil {
return err
}
}
}
// find difference in backends
if d.HasChange("backend") {
ob, nb := d.GetChange("backend")
if ob == nil {
ob = new(schema.Set)
}
if nb == nil {
nb = new(schema.Set)
}
obs := ob.(*schema.Set)
nbs := nb.(*schema.Set)
removeBackends := obs.Difference(nbs).List()
addBackends := nbs.Difference(obs).List()
// DELETE old Backends
for _, bRaw := range removeBackends {
bf := bRaw.(map[string]interface{})
opts := gofastly.DeleteBackendInput{
Service: d.Id(),
Version: latestVersion,
Name: bf["name"].(string),
}
log.Printf("[DEBUG] Fastly Backend removal opts: %#v", opts)
err := conn.DeleteBackend(&opts)
if err != nil {
return err
}
}
// Find and post new Backends
for _, dRaw := range addBackends {
df := dRaw.(map[string]interface{})
opts := gofastly.CreateBackendInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
Address: df["address"].(string),
AutoLoadbalance: df["auto_loadbalance"].(bool),
SSLCheckCert: df["ssl_check_cert"].(bool),
Port: uint(df["port"].(int)),
BetweenBytesTimeout: uint(df["between_bytes_timeout"].(int)),
ConnectTimeout: uint(df["connect_timeout"].(int)),
ErrorThreshold: uint(df["error_threshold"].(int)),
FirstByteTimeout: uint(df["first_byte_timeout"].(int)),
MaxConn: uint(df["max_conn"].(int)),
Weight: uint(df["weight"].(int)),
}
log.Printf("[DEBUG] Create Backend Opts: %#v", opts)
_, err := conn.CreateBackend(&opts)
if err != nil {
return err
}
}
}
if d.HasChange("header") {
oh, nh := d.GetChange("header")
if oh == nil {
oh = new(schema.Set)
}
if nh == nil {
nh = new(schema.Set)
}
ohs := oh.(*schema.Set)
nhs := nh.(*schema.Set)
remove := ohs.Difference(nhs).List()
add := nhs.Difference(ohs).List()
// Delete removed headers
for _, dRaw := range remove {
df := dRaw.(map[string]interface{})
opts := gofastly.DeleteHeaderInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
}
log.Printf("[DEBUG] Fastly Header removal opts: %#v", opts)
err := conn.DeleteHeader(&opts)
if err != nil {
return err
}
}
// POST new Headers
for _, dRaw := range add {
opts, err := buildHeader(dRaw.(map[string]interface{}))
if err != nil {
log.Printf("[DEBUG] Error building Header: %s", err)
return err
}
opts.Service = d.Id()
opts.Version = latestVersion
log.Printf("[DEBUG] Fastly Header Addition opts: %#v", opts)
_, err = conn.CreateHeader(opts)
if err != nil {
return err
}
}
}
// Find differences in Gzips
if d.HasChange("gzip") {
og, ng := d.GetChange("gzip")
if og == nil {
og = new(schema.Set)
}
if ng == nil {
ng = new(schema.Set)
}
ogs := og.(*schema.Set)
ngs := ng.(*schema.Set)
remove := ogs.Difference(ngs).List()
add := ngs.Difference(ogs).List()
// Delete removed gzip rules
for _, dRaw := range remove {
df := dRaw.(map[string]interface{})
opts := gofastly.DeleteGzipInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
}
log.Printf("[DEBUG] Fastly Gzip removal opts: %#v", opts)
err := conn.DeleteGzip(&opts)
if err != nil {
return err
}
}
// POST new Gzips
for _, dRaw := range add {
df := dRaw.(map[string]interface{})
opts := gofastly.CreateGzipInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
}
if v, ok := df["content_types"]; ok {
if len(v.(*schema.Set).List()) > 0 {
var cl []string
for _, c := range v.(*schema.Set).List() {
cl = append(cl, c.(string))
}
opts.ContentTypes = strings.Join(cl, " ")
}
}
if v, ok := df["extensions"]; ok {
if len(v.(*schema.Set).List()) > 0 {
var el []string
for _, e := range v.(*schema.Set).List() {
el = append(el, e.(string))
}
opts.Extensions = strings.Join(el, " ")
}
}
log.Printf("[DEBUG] Fastly Gzip Addition opts: %#v", opts)
_, err := conn.CreateGzip(&opts)
if err != nil {
return err
}
}
}
// find difference in s3logging
if d.HasChange("s3logging") {
os, ns := d.GetChange("s3logging")
if os == nil {
os = new(schema.Set)
}
if ns == nil {
ns = new(schema.Set)
}
oss := os.(*schema.Set)
nss := ns.(*schema.Set)
removeS3Logging := oss.Difference(nss).List()
addS3Logging := nss.Difference(oss).List()
// DELETE old S3 Log configurations
for _, sRaw := range removeS3Logging {
sf := sRaw.(map[string]interface{})
opts := gofastly.DeleteS3Input{
Service: d.Id(),
Version: latestVersion,
Name: sf["name"].(string),
}
log.Printf("[DEBUG] Fastly S3 Logging removal opts: %#v", opts)
err := conn.DeleteS3(&opts)
if err != nil {
return err
}
}
// POST new/updated S3 Logging
for _, sRaw := range addS3Logging {
sf := sRaw.(map[string]interface{})
// Fastly API will not error if these are omitted, so we throw an error
// if any of these are empty
for _, sk := range []string{"s3_access_key", "s3_secret_key"} {
if sf[sk].(string) == "" {
return fmt.Errorf("[ERR] No %s found for S3 Log stream setup for Service (%s)", sk, d.Id())
}
}
opts := gofastly.CreateS3Input{
Service: d.Id(),
Version: latestVersion,
Name: sf["name"].(string),
BucketName: sf["bucket_name"].(string),
AccessKey: sf["s3_access_key"].(string),
SecretKey: sf["s3_secret_key"].(string),
Period: uint(sf["period"].(int)),