-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathutils.go
More file actions
935 lines (824 loc) · 21.4 KB
/
Copy pathutils.go
File metadata and controls
935 lines (824 loc) · 21.4 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
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
package common
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
akeyless_api "github.com/akeylesslabs/akeyless-go/v5"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func DiffSuppressDuration(_, old, new string, _ *schema.ResourceData) bool {
// Parse both durations and compare them
oldDuration, oldErr := time.ParseDuration(old)
newDuration, newErr := time.ParseDuration(new)
// If both parse successfully, compare the durations
if oldErr == nil && newErr == nil {
return oldDuration == newDuration
}
// If parsing fails, fall back to string comparison
return old == new
}
func DiffSuppressOnLeadingSlash(_, old, new string, _ *schema.ResourceData) bool {
return EnsureLeadingSlash(old) == EnsureLeadingSlash(new)
}
func DiffSuppressOnSlashes(_, old, new string, _ *schema.ResourceData) bool {
return strings.Trim(old, "/") == strings.Trim(new, "/")
}
var allLetters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var lowerLetters = []rune("abcdefghijklmnopqrstuvwxyz")
func GenerateRandomAlphaNumericString(length int) string {
s := make([]rune, length)
for i := range s {
s[i] = allLetters[rand.Intn(len(allLetters))]
}
return string(s)
}
func GenerateRandomLowercasedString(length int) string {
s := make([]rune, length)
for i := range s {
s[i] = lowerLetters[rand.Intn(len(lowerLetters))]
}
return string(s)
}
func ExpandStringList(configured []interface{}) []string {
vs := make([]string, 0, len(configured))
for _, v := range configured {
val, ok := v.(string)
if ok && val != "" {
vs = append(vs, val)
}
}
return vs
}
func ExpandStringMap(raw map[string]interface{}) map[string]string {
out := make(map[string]string, len(raw))
for k, v := range raw {
out[k] = v.(string)
}
return out
}
func ErrorDiagnostics(message string) diag.Diagnostic {
return diag.Diagnostic{
Severity: diag.Error,
Summary: message,
}
}
func WarningDiagnostics(message string) diag.Diagnostic {
return diag.Diagnostic{
Severity: diag.Warning,
Summary: message,
}
}
func GetAkeylessPtr(ptr any, val any) {
switch ptr.(type) {
case *string:
if v, ok := val.(string); ok {
a := ptr.(*string)
*a = v
return
}
case **string:
if v, ok := val.(string); ok {
a := ptr.(**string)
*a = akeyless_api.PtrString(v)
return
}
case *[]string:
a := ptr.(*[]string)
if v, ok := val.(string); ok {
*a = []string{v}
return
}
if v, ok := val.([]string); ok {
*a = v
return
}
case **[]string:
a := ptr.(**[]string)
if v, ok := val.(string); ok {
*a = &[]string{v}
return
}
if v, ok := val.([]string); ok {
*a = &v
return
}
case **bool:
if v, ok := val.(bool); ok {
a := ptr.(**bool)
*a = akeyless_api.PtrBool(v)
return
}
case *bool:
if v, ok := val.(bool); ok {
a := ptr.(*bool)
*a = v
return
}
case **int64:
if v, ok := val.(int); ok {
a := ptr.(**int64)
*a = akeyless_api.PtrInt64(int64(v))
return
}
case **int32:
if v, ok := val.(int); ok {
a := ptr.(**int32)
*a = akeyless_api.PtrInt32(int32(v))
return
}
case **int:
if v, ok := val.(int); ok {
a := ptr.(**int)
*a = akeyless_api.PtrInt(v)
return
}
case *int64:
if v, ok := val.(int); ok {
a := ptr.(*int64)
*a = int64(v)
return
}
case *int32:
if v, ok := val.(int); ok {
a := ptr.(*int32)
*a = int32(v)
return
}
case *int:
if v, ok := val.(int); ok {
a := ptr.(*int)
*a = v
return
}
case **float32:
if v, ok := val.(float32); ok {
a := ptr.(**float32)
*a = akeyless_api.PtrFloat32(v)
return
}
case **float64:
if v, ok := val.(float64); ok {
a := ptr.(**float64)
*a = akeyless_api.PtrFloat64(v)
return
}
case **time.Time:
if v, ok := val.(time.Time); ok {
a := ptr.(**time.Time)
*a = akeyless_api.PtrTime(v)
return
}
case *float32:
if v, ok := val.(float32); ok {
a := ptr.(*float32)
*a = v
return
}
case *float64:
if v, ok := val.(float64); ok {
a := ptr.(*float64)
*a = v
return
}
case *time.Time:
if v, ok := val.(time.Time); ok {
a := ptr.(*time.Time)
*a = v
return
}
case **map[string]string:
if v, ok := val.(map[string]interface{}); ok {
mapString := make(map[string]string)
for key, value := range v {
strKey := fmt.Sprintf("%v", key)
strValue := fmt.Sprintf("%v", value)
mapString[strKey] = strValue
}
a := ptr.(**map[string]string)
*a = &mapString
return
}
default:
panic("invalid type")
//*ptr = val
}
}
func GetTargetName(itemTargetsAssoc []akeyless_api.ItemTargetAssociation) string {
if len(itemTargetsAssoc) == 0 {
return ""
}
targets := itemTargetsAssoc
if len(targets) == 1 {
if targets[0].TargetName == nil {
return ""
}
return *targets[0].TargetName
}
names := make([]string, 0)
for _, t := range targets {
if t.TargetName != nil {
names = append(names, *t.TargetName)
}
}
return strings.Join(names, ",")
}
func GetTargetType(itemTargetsAssoc []akeyless_api.ItemTargetAssociation) string {
if len(itemTargetsAssoc) == 0 {
return ""
}
return itemTargetsAssoc[0].GetTargetType()
}
func GetRotatorUscSync(associatedItems []akeyless_api.ItemUSCSyncAssociation, uscName, remoteSecretName string) (namespace, filterSecretValue string, exists bool) {
normalizedUscName := strings.TrimPrefix(uscName, "/")
for _, assoc := range associatedItems {
if assoc.ItemName == nil || strings.TrimPrefix(*assoc.ItemName, "/") != normalizedUscName {
continue
}
if assoc.Attributes == nil {
return "", "", false
}
attr := *assoc.Attributes
if attr.SecretName == nil || *attr.SecretName != remoteSecretName {
return "", "", false
}
return attr.GetNamespace(), attr.GetJqSecretFilter(), true
}
return "", "", false
}
func GetTagsForUpdate(d *schema.ResourceData, name, token string, newTags []string,
client akeyless_api.V2ApiService) ([]string, []string, error) {
ctx := context.Background()
item := akeyless_api.GetTags{
Name: name,
Token: &token,
}
oldTags, _, err := client.GetTags(ctx).Body(item).Execute()
if err != nil {
return nil, nil, err
}
if len(oldTags) == 0 {
return newTags, nil, nil
}
add := difference(newTags, oldTags)
remove := difference(oldTags, newTags)
return add, remove, nil
}
// difference returns the elements in `a` that aren't in `b`.
func difference(a, b []string) []string {
mb := make(map[string]struct{}, len(b))
for _, x := range b {
mb[x] = struct{}{}
}
var diff []string
for _, x := range a {
if _, found := mb[x]; !found {
diff = append(diff, x)
}
}
return diff
}
func GetSraWithDescribeItem(d *schema.ResourceData, path, token string, client akeyless_api.V2ApiService) error {
ctx := context.Background()
item := akeyless_api.DescribeItem{
Name: path,
ShowVersions: akeyless_api.PtrBool(false),
Token: &token,
}
itemOut, _, err := client.DescribeItem(ctx).Body(item).Execute()
if err != nil {
return err
}
return GetSraFromItem(d, itemOut)
}
func GetSraFromItem(d *schema.ResourceData, item *akeyless_api.Item) error {
if item.GetItemGeneralInfo().SecureRemoteAccessDetails == nil {
return nil
}
itemType := *item.ItemType
sra := item.GetItemGeneralInfo().SecureRemoteAccessDetails
return GetSra(d, sra, itemType)
}
func GetSra(d *schema.ResourceData, sra *akeyless_api.SecureRemoteAccess, itemType string) error {
var err error
if sra == nil {
return nil
}
if _, ok := sra.GetEnableOk(); ok {
err = d.Set("secure_access_enable", strconv.FormatBool(sra.GetEnable()))
if err != nil {
return err
}
}
if s, ok := sra.GetUrlOk(); ok {
err = d.Set("secure_access_url", s)
if err != nil {
return err
}
}
if s, ok := sra.GetBastionApiOk(); ok {
err = d.Set("secure_access_bastion_api", s)
if err != nil {
return err
}
}
if s, ok := sra.GetBastionSshOk(); ok {
err = d.Set("secure_access_bastion_ssh", s)
if err != nil {
return err
}
}
if s, ok := sra.GetSshUserOk(); ok {
if itemType == "STATIC_SECRET" {
err = d.Set("secure_access_ssh_user", s)
if err != nil {
return err
}
} else { //cert-issuer
err = d.Set("secure_access_ssh_creds_user", s)
if err != nil {
return err
}
}
}
// if s, ok := sra.GetIsCliOk(); ok && *s {
// err = d.Set("secure_access_ssh_creds", s)
// if err != nil {
// return err
// }
// }
if s, ok := sra.GetUseInternalBastionOk(); ok && *s {
err = d.Set("secure_access_use_internal_bastion", s)
if err != nil {
return err
}
}
if s, ok := sra.GetNativeOk(); ok && *s {
err = d.Set("secure_access_aws_native_cli", s)
if err != nil {
return err
}
}
if s, ok := sra.GetHostOk(); ok {
if len(s) == 1 && (s)[0] == "" {
s = []string{}
}
err = d.Set("secure_access_host", s)
if err != nil {
return err
}
}
if s, ok := sra.GetIsWebOk(); ok && *s {
err = d.Set("secure_access_web", s)
if err != nil {
return err
}
}
if s, ok := sra.GetWebProxyOk(); ok && *s {
err = d.Set("secure_access_web_proxy", s)
if err != nil {
return err
}
}
if s, ok := sra.GetIsolatedOk(); ok && *s {
err = d.Set("secure_access_web_browsing", s)
if err != nil {
return err
}
}
if s, ok := sra.GetDomainOk(); ok {
err = d.Set("secure_access_rdp_domain", s)
if err != nil {
return err
}
}
if s, ok := sra.GetRdpUserOk(); ok {
err = d.Set("secure_access_rdp_user", s)
if err != nil {
return err
}
}
if s, ok := sra.GetAllowProvidingExternalUsernameOk(); ok && *s {
err = d.Set("secure_access_allow_external_user", s)
if err != nil {
return err
}
}
if s, ok := sra.GetSchemaOk(); ok {
err = d.Set("secure_access_db_schema", s)
if err != nil {
return err
}
}
if s, ok := sra.GetDbNameOk(); ok {
err = d.Set("secure_access_db_name", s)
if err != nil {
return err
}
}
if s, ok := sra.GetAccountIdOk(); ok {
err = d.Set("secure_access_aws_account_id", s)
if err != nil {
return err
}
}
if s, ok := sra.GetRegionOk(); ok {
err = d.Set("secure_access_aws_region", s)
if err != nil {
return err
}
}
if s, ok := sra.GetBastionIssuerOk(); ok {
err = d.Set("secure_access_certificate_issuer", s)
if err != nil {
return err
}
}
if s, ok := sra.GetEndpointOk(); ok {
err = d.Set("secure_access_cluster_endpoint", s)
if err != nil {
return err
}
}
if s, ok := sra.GetDashboardUrlOk(); ok {
err = d.Set("secure_access_dashboard_url", s)
if err != nil {
return err
}
}
if s, ok := sra.GetAllowPortForwardingOk(); ok && *s {
err = d.Set("secure_access_allow_port_forwading", s)
if err != nil {
return err
}
}
return nil
}
func GetFieldjsonTagName(tag string, s interface{}) (fieldname string) {
rt := reflect.TypeOf(s)
if rt.Kind() != reflect.Struct {
//panic("bad type")
return ""
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
v := strings.Split(f.Tag.Get("json"), ",")[0] // use split to ignore tag "options" like omitempty, etc.
if v == tag {
return f.Name
}
}
return ""
}
func GetErrorOnUpdateParam(d *schema.ResourceData, paramNames []string) error {
changed := []string{}
for _, paramName := range paramNames {
if d.HasChange(paramName) {
// need to explicit rollback param due to unresolved bug in terraform:
// https://github.com/hashicorp/terraform-provider-helm/issues/472
old, _ := d.GetChange(paramName)
d.Set(paramName, old)
changed = append(changed, paramName)
}
}
if len(changed) > 0 {
changedParams := "\"" + strings.Join(changed, "\", \"") + "\""
return fmt.Errorf("update of %s is not allowed", changedParams)
}
return nil
}
func ConvertNanoSecondsIntoDurationString(nano int64) string {
nanoUnix := time.Unix(0, nano)
duration := nanoUnix.Sub(time.Unix(0, 0))
return duration.String()
}
func ReadAndEncodeFile(fileName string) (string, error) {
bytes, err := os.ReadFile(fileName)
if err != nil {
return "", err
}
data := base64.StdEncoding.EncodeToString(bytes)
if len(data) == 0 {
return "", errors.New("")
}
return data, nil
}
func Base64Encode(input string) string {
return base64.StdEncoding.EncodeToString([]byte(input))
}
func Base64Decode(input string) (string, error) {
b, err := base64.StdEncoding.DecodeString(input)
return string(b), err
}
func EnsureLeadingSlash(path string) string {
if len(path) != 0 && !strings.HasPrefix(path, "/") {
return "/" + path
}
return path
}
func SetDataByPrefixSlash(d *schema.ResourceData, key, returnedValue, existValue string) error {
if "/"+returnedValue == existValue || returnedValue == "/"+existValue {
return d.Set(key, existValue)
}
return d.Set(key, returnedValue)
}
// SecondsToTimeString converts a total number of seconds to a formatted string like "1d2h3m4s".
func SecondsToTimeString(totalSeconds int) string {
const secondsInAMinute = 60
const secondsInAnHour = secondsInAMinute * 60
const secondsInADay = secondsInAnHour * 24
days := totalSeconds / secondsInADay
remainSeconds := totalSeconds % secondsInADay
hours := remainSeconds / secondsInAnHour
remainSeconds %= secondsInAnHour
minutes := remainSeconds / secondsInAMinute
remainSeconds %= secondsInAMinute
seconds := remainSeconds
var result strings.Builder
if days > 0 {
result.WriteString(fmt.Sprintf("%dd", days))
}
if hours > 0 {
result.WriteString(fmt.Sprintf("%dh", hours))
}
if minutes > 0 {
result.WriteString(fmt.Sprintf("%dm", minutes))
}
if seconds > 0 || result.Len() == 0 {
result.WriteString(fmt.Sprintf("%ds", seconds))
}
return result.String()
}
// TimeStringToSeconds converts a formatted time string like "365d", "8760h", "1d2h3m4s"
// back to total seconds. Returns -1 if the string cannot be parsed.
func TimeStringToSeconds(s string) int {
total := 0
current := 0
for _, c := range s {
if c >= '0' && c <= '9' {
current = current*10 + int(c-'0')
} else {
switch c {
case 'd':
total += current * 86400
case 'h':
total += current * 3600
case 'm':
total += current * 60
case 's':
total += current
default:
return -1
}
current = 0
}
}
if current > 0 {
total += current
}
return total
}
func ExtractLogForwardingFormat(isJson bool) string {
if isJson {
return "json"
}
return "text"
}
func ReadExpirationEventInParam(expirationEvents []akeyless_api.CertificateExpirationEvent) []string {
var expirationEventsList []string
for _, e := range expirationEvents {
seconds := e.GetSecondsBefore()
days := seconds / 60 / 60 / 24
expirationEventsList = append(expirationEventsList, strconv.FormatInt(days, 10))
}
return expirationEventsList
}
func ReadRotationEventInParam(expirationEvents []akeyless_api.NextAutoRotationEvent) []string {
var expirationEventsList []string
for _, e := range expirationEvents {
seconds := e.GetSecondsBefore()
days := seconds / 60 / 60 / 24
expirationEventsList = append(expirationEventsList, strconv.FormatInt(days, 10))
}
return expirationEventsList
}
func ReadAuthExpirationEventInParam(expirationEvents []akeyless_api.AuthExpirationEvent) []string {
var expirationEventsList []string
for _, e := range expirationEvents {
seconds := e.GetSecondsBefore()
days := seconds / 60 / 60 / 24
expirationEventsList = append(expirationEventsList, strconv.FormatInt(days, 10))
}
return expirationEventsList
}
// IsCICDEnv returns true if the test is running in Terraform CI/CD pipeline.
// Terraform CI/CD pipeline is using a restricted user that have 1 deny rule for some items path.
// This deny rule is reflected in the number of role rules that are returned (extra rule).
// Note:
// - except for this restriction, the user has an admin privileges.
// - the account is dedicated for terraform CI/CD pipeline tests and should not contain any sensitive data.
func IsCICDEnv() bool {
if strings.ToLower(os.Getenv("GITHUB_ACTIONS")) == "true" {
return true
}
return false
}
func HandleError(msg string, resp *http.Response, err error) error {
return handleError(nil, msg, resp, err, false)
}
func HandleReadError(d *schema.ResourceData, msg string, resp *http.Response, err error) error {
return handleError(d, msg, resp, err, true)
}
func handleError(d *schema.ResourceData, msg string, resp *http.Response, err error, cleanup bool) error {
if err == nil {
return nil
}
// err is informative
var apiErr akeyless_api.GenericOpenAPIError
if errors.As(err, &apiErr) {
return fmt.Errorf("%s: %s", msg, string(apiErr.Body()))
}
// resp is informative
if resp != nil && resp.Body != nil {
if errorMsg, errRead := io.ReadAll(resp.Body); errRead == nil {
return fmt.Errorf("%s: %s", msg, string(errorMsg))
}
}
// not found
if resp != nil && resp.StatusCode == http.StatusNotFound {
if cleanup && d != nil {
// The resource was deleted outside of the current Terraform workspace, so invalidate this resource
d.SetId("")
}
return fmt.Errorf("%s: not found: %w", msg, err)
}
return fmt.Errorf("%s: %w", msg, err)
}
func ValidateEventForwarderUpdateParams(d *schema.ResourceData) error {
paramsMustNotUpdate := []string{"runner_type", "every"}
return GetErrorOnUpdateParam(d, paramsMustNotUpdate)
}
func SetCommonEventForwarderVars(d *schema.ResourceData, rOut *akeyless_api.NotiForwarder) error {
if rOut.Paths != nil {
err := setEventSourceLocations(d, rOut.Paths)
if err != nil {
return err
}
}
if rOut.EventTypes != nil {
err := d.Set("event_types", rOut.EventTypes)
if err != nil {
return err
}
}
if rOut.ProtectionKey != nil {
if !strings.Contains(*rOut.ProtectionKey, "__account-def-secrets-key__") {
err := d.Set("key", *rOut.ProtectionKey)
if err != nil {
return err
}
}
}
if rOut.RunnerType != nil {
err := d.Set("runner_type", *rOut.RunnerType)
if err != nil {
return err
}
}
if rOut.TimespanInSeconds != nil {
err := d.Set("every", fmt.Sprintf("%d", *rOut.TimespanInSeconds/3600))
if err != nil {
return err
}
}
if rOut.Comment != nil {
err := d.Set("description", *rOut.Comment)
if err != nil {
return err
}
}
return nil
}
func setEventSourceLocations(d *schema.ResourceData, paths []string) error {
if len(paths) == 0 {
return nil
}
items := make([]string, 0)
authMethods := make([]string, 0)
targets := make([]string, 0)
gateways := make([]string, 0)
for _, path := range paths {
if strings.HasPrefix(path, "item:") {
items = append(items, strings.TrimPrefix(path, "item:"))
} else if strings.HasPrefix(path, "auth_method:") {
authMethods = append(authMethods, strings.TrimPrefix(path, "auth_method:"))
} else if strings.HasPrefix(path, "target:") {
targets = append(targets, strings.TrimPrefix(path, "target:"))
} else if strings.HasPrefix(path, "gateway:") {
gateways = append(gateways, strings.TrimPrefix(path, "gateway:"))
}
}
currentItemsSet := d.Get("items_event_source_locations").(*schema.Set)
currentItems := ExpandStringList(currentItemsSet.List())
if areListsDifferent(currentItems, items) {
err := d.Set("items_event_source_locations", items)
if err != nil {
return err
}
}
currentAMSet := d.Get("auth_methods_event_source_locations").(*schema.Set)
currentAM := ExpandStringList(currentAMSet.List())
if areListsDifferent(currentAM, authMethods) {
err := d.Set("auth_methods_event_source_locations", authMethods)
if err != nil {
return err
}
}
currentTargetsSet := d.Get("targets_event_source_locations").(*schema.Set)
currentTargets := ExpandStringList(currentTargetsSet.List())
if areListsDifferent(currentTargets, targets) {
err := d.Set("targets_event_source_locations", targets)
if err != nil {
return err
}
}
// we can't set gateways_event_source_locations as input is URL list but output is ClusterId list
gatewaysLen := d.Get("gateways_event_source_locations").(*schema.Set).Len()
if gatewaysLen > 0 && gatewaysLen != len(gateways) {
return fmt.Errorf("gateway event source locations should be set. Expected %d, got %d", gatewaysLen, len(gateways))
}
return nil
}
func areListsDifferent(a, b []string) bool {
if len(a) != len(b) {
return true
}
mapA := make(map[string]struct{}, len(a))
for _, item := range a {
mapA[EnsureLeadingSlash(item)] = struct{}{}
}
for _, itemB := range b {
item := EnsureLeadingSlash(itemB)
if _, exists := mapA[item]; !exists {
return true
}
delete(mapA, item)
}
if len(mapA) > 0 {
return true
}
return false
}
func GetOriginalProductTypeConvention(d *schema.ResourceData, productTypes []string) []string {
productTypeSet := d.Get("product_type").(*schema.Set)
origProductTypes := ExpandStringList(productTypeSet.List())
for _, origProductType := range origProductTypes {
if origProductType == "ca" {
for j, productType := range productTypes {
if productType == "cm" {
productTypes[j] = origProductType
break
}
}
}
if origProductType == "dp" {
for j, productType := range productTypes {
if productType == "adp" {
productTypes[j] = origProductType
break
}
}
}
if origProductType == "pm" {
for j, productType := range productTypes {
if productType == "apm" {
productTypes[j] = origProductType
break
}
}
}
}
return productTypes
}
func GetItemNameByID(client akeyless_api.V2ApiService, token string, itemID int64) (string, error) {
body := akeyless_api.DescribeItem{
ItemId: &itemID,
Token: &token,
}
rOut, resp, err := client.DescribeItem(context.Background()).Body(body).Execute()
if err != nil {
return "", HandleError("can't resolve item name from id", resp, err)
}
if rOut.ItemName != nil {
return *rOut.ItemName, nil
}
return "", nil
}