-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathrepository.go
1057 lines (912 loc) · 35.2 KB
/
repository.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 repository
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"github.com/go-resty/resty/v2"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/setdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
sdkv2_diag "github.com/hashicorp/terraform-plugin-sdk/v2/diag"
sdkv2_schema "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/jfrog/terraform-provider-shared/client"
"github.com/jfrog/terraform-provider-shared/packer"
"github.com/jfrog/terraform-provider-shared/testutil"
"github.com/jfrog/terraform-provider-shared/unpacker"
"github.com/jfrog/terraform-provider-shared/util"
utilfw "github.com/jfrog/terraform-provider-shared/util/fw"
utilsdk "github.com/jfrog/terraform-provider-shared/util/sdk"
sdkv2_validator "github.com/jfrog/terraform-provider-shared/validator"
validatorfw_string "github.com/jfrog/terraform-provider-shared/validator/fw/string"
"golang.org/x/exp/slices"
)
const (
AlpinePackageType = "alpine"
AnsiblePackageType = "ansible"
BowerPackageType = "bower"
CargoPackageType = "cargo"
ChefPackageType = "chef"
CocoapodsPackageType = "cocoapods"
ComposerPackageType = "composer"
CondaPackageType = "conda"
ConanPackageType = "conan"
CranPackageType = "cran"
DebianPackageType = "debian"
DockerPackageType = "docker"
GemsPackageType = "gems"
GenericPackageType = "generic"
GitLFSPackageType = "gitlfs"
GoPackageType = "go"
GradlePackageType = "gradle"
HelmPackageType = "helm"
HelmOCIPackageType = "helmoci"
HuggingFacePackageType = "huggingfaceml"
IvyPackageType = "ivy"
MachineLearningType = "machinelearning"
MavenPackageType = "maven"
NPMPackageType = "npm"
NugetPackageType = "nuget"
OCIPackageType = "oci"
OpkgPackageType = "opkg"
P2PackageType = "p2"
PubPackageType = "pub"
PuppetPackageType = "puppet"
PyPiPackageType = "pypi"
RPMPackageType = "rpm"
SBTPackageType = "sbt"
SwiftPackageType = "swift"
TerraformBackendPackageType = "terraformbackend"
TerraformModulePackageType = "terraform_module"
TerraformProviderPackageType = "terraform_provider"
TerraformPackageType = "terraform"
VagrantPackageType = "vagrant"
VCSPackageType = "vcs"
)
var PackageNameLookup = map[string]string{
BowerPackageType: "Bower",
ChefPackageType: "Chef",
CocoapodsPackageType: "CocoaPods",
ComposerPackageType: "Composer",
CondaPackageType: "Conda",
CranPackageType: "CRAN",
GemsPackageType: "Gems",
GenericPackageType: "Generic",
GitLFSPackageType: "GitLfs",
GoPackageType: "Go",
GradlePackageType: "Gradle",
HelmPackageType: "Helm",
HuggingFacePackageType: "HuggingFace ML",
IvyPackageType: "Ivy",
NPMPackageType: "Npm",
OpkgPackageType: "Opkg",
PubPackageType: "Pub",
PuppetPackageType: "Puppet",
PyPiPackageType: "PyPi",
SBTPackageType: "SBT",
SwiftPackageType: "Swift",
TerraformBackendPackageType: "Terraform Backend",
VagrantPackageType: "Vagrant",
}
func NewRepositoryResource(packageType, packageName, rclass string, resourceModelType, apiModelType reflect.Type) BaseResource {
return BaseResource{
JFrogResource: util.JFrogResource{
TypeName: fmt.Sprintf("artifactory_%s_%s_repository", rclass, packageType),
CollectionEndpoint: "artifactory/api/repositories",
DocumentEndpoint: "artifactory/api/repositories/{key}",
},
Description: fmt.Sprintf("Provides a resource to creates a %s repository.", packageName),
PackageType: packageType,
Rclass: rclass,
ResourceModelType: resourceModelType,
APIModelType: apiModelType,
}
}
type BaseResource struct {
util.JFrogResource
Description string
PackageType string
Rclass string
ResourceModelType reflect.Type
APIModelType reflect.Type
}
func (r BaseResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
if r.ProviderData == nil {
return
}
var projectEnviroments types.Set
resp.Diagnostics.Append(req.Config.GetAttribute(ctx, path.Root("project_environments"), &projectEnviroments)...)
if resp.Diagnostics.HasError() {
return
}
// If project_environments is not configured, return without warning.
if projectEnviroments.IsNull() || projectEnviroments.IsUnknown() {
return
}
var envs []string
resp.Diagnostics.Append(projectEnviroments.ElementsAs(ctx, &envs, false)...)
if resp.Diagnostics.HasError() {
return
}
isSupported, err := util.CheckVersion(r.ProviderData.ArtifactoryVersion, CustomProjectEnvironmentSupportedVersion)
if err != nil {
resp.Diagnostics.AddError(
"Failed to check Artifactory version",
err.Error(),
)
return
}
if isSupported {
if len(envs) == 2 {
resp.Diagnostics.AddError(
"Too many project environment",
fmt.Sprintf("for Artifactory %s or later, only one environment can be assigned to a repository", CustomProjectEnvironmentSupportedVersion),
)
return
}
} else { // Before 7.53.1
for _, env := range envs {
if !slices.Contains(ProjectEnvironmentsSupported, env) {
resp.Diagnostics.AddError(
"Invalid project_environment not allowed",
env,
)
return
}
}
}
}
func (r *BaseResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
if r.ResourceModelType == nil || r.APIModelType == nil {
resp.Diagnostics.AddError(
"ResourceModelType or APIModelType is nil",
"",
)
return
}
go util.SendUsageResourceCreate(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
plan := reflect.New(r.ResourceModelType).Interface().(ResourceModelIface)
plan.GetCreateResourcePlanData(ctx, req, resp)
if resp.Diagnostics.HasError() {
return
}
repo, d := plan.ToAPIModel(ctx, r.PackageType)
if d != nil {
resp.Diagnostics.Append(d...)
}
if resp.Diagnostics.HasError() {
return
}
var jfrogErrors util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("key", plan.KeyString()).
SetBody(repo).
SetError(&jfrogErrors).
Put(r.DocumentEndpoint)
if err != nil {
utilfw.UnableToCreateResourceError(resp, err.Error())
return
}
if response.IsError() {
utilfw.UnableToCreateResourceError(resp, jfrogErrors.String())
return
}
plan.SetCreateResourceStateData(ctx, resp)
}
func (r *BaseResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
go util.SendUsageResourceRead(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
state := reflect.New(r.ResourceModelType).Interface().(ResourceModelIface)
state.GetReadResourceStateData(ctx, req, resp)
if resp.Diagnostics.HasError() {
return
}
// Convert from Terraform data model into API data model
repo := reflect.New(r.APIModelType).Interface()
var jfrogErrors util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("key", state.KeyString()).
SetResult(repo).
SetError(&jfrogErrors).
Get(r.DocumentEndpoint)
if err != nil {
utilfw.UnableToRefreshResourceError(resp, err.Error())
return
}
// Treat HTTP 400 Bad Request or 404 Not Found status as a signal to recreate resource
// and return early
if response.StatusCode() == http.StatusBadRequest || response.StatusCode() == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
if response.IsError() {
utilfw.UnableToRefreshResourceError(resp, jfrogErrors.String())
return
}
// Convert from the API data model to the Terraform data model
// and refresh any attribute values.
resp.Diagnostics.Append(state.FromAPIModel(ctx, repo)...)
if resp.Diagnostics.HasError() {
return
}
state.SetReadResourceStateData(ctx, resp)
}
func (r *BaseResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
go util.SendUsageResourceUpdate(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
plan := reflect.New(r.ResourceModelType).Interface().(ResourceModelIface)
plan.GetUpdateResourcePlanData(ctx, req, resp)
if resp.Diagnostics.HasError() {
return
}
state := reflect.New(r.ResourceModelType).Interface().(ResourceModelIface)
state.GetUpdateResourceStateData(ctx, req, resp)
if resp.Diagnostics.HasError() {
return
}
repo, d := plan.ToAPIModel(ctx, r.PackageType)
if d != nil {
resp.Diagnostics.Append(d...)
}
if resp.Diagnostics.HasError() {
return
}
key := plan.KeyString()
var jfrogErrors util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("key", key).
SetBody(repo).
SetError(&jfrogErrors).
Post(r.DocumentEndpoint)
if err != nil {
utilfw.UnableToUpdateResourceError(resp, err.Error())
return
}
if response.IsError() {
utilfw.UnableToUpdateResourceError(resp, jfrogErrors.String())
return
}
planProjectKey := plan.ProjectKeyValue()
stateProjectKey := state.ProjectKeyValue()
if !planProjectKey.Equal(stateProjectKey) {
oldProjectKey := stateProjectKey.ValueString()
newProjectKey := planProjectKey.ValueString()
assignToProject := oldProjectKey == "" && len(newProjectKey) > 0
unassignFromProject := len(oldProjectKey) > 0 && newProjectKey == ""
var err error
if assignToProject {
err = AssignRepoToProject(key, newProjectKey, r.ProviderData.Client)
} else if unassignFromProject {
err = UnassignRepoFromProject(key, r.ProviderData.Client)
}
if err != nil {
resp.Diagnostics.AddError(
"Failed to assign/unassign repository to project",
err.Error(),
)
return
}
}
plan.SetUpdateResourceStateData(ctx, resp)
}
func (r *BaseResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
go util.SendUsageResourceDelete(ctx, r.ProviderData.Client.R(), r.ProviderData.ProductId, r.TypeName)
var key types.String
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("key"), &key)...)
var jfrogErrors util.JFrogErrors
response, err := r.ProviderData.Client.R().
SetPathParam("key", key.ValueString()).
SetError(&jfrogErrors).
Delete(r.DocumentEndpoint)
if err != nil {
utilfw.UnableToDeleteResourceError(resp, err.Error())
return
}
// Return error if the HTTP status code is not 200 OK
if response.StatusCode() != http.StatusOK {
utilfw.UnableToDeleteResourceError(resp, jfrogErrors.String())
return
}
// If the logic reaches here, it implicitly succeeded and will remove
// the resource from state if there are no other errors.
}
// ImportState imports the resource into the Terraform state.
func (r *BaseResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("key"), req, resp)
}
type ResourceModelIface interface {
KeyString() string
ToAPIModel(ctx context.Context, packageType string) (interface{}, diag.Diagnostics)
FromAPIModel(ctx context.Context, apiModel interface{}) diag.Diagnostics
GetCreateResourcePlanData(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse)
SetCreateResourceStateData(ctx context.Context, resp *resource.CreateResponse)
GetReadResourceStateData(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse)
SetReadResourceStateData(ctx context.Context, resp *resource.ReadResponse)
GetUpdateResourcePlanData(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse)
GetUpdateResourceStateData(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse)
SetUpdateResourceStateData(ctx context.Context, resp *resource.UpdateResponse)
ProjectKeyValue() basetypes.StringValue
}
type BaseResourceModel struct {
Key types.String `tfsdk:"key"`
ProjectKey types.String `tfsdk:"project_key"`
ProjectEnvironments types.Set `tfsdk:"project_environments"`
Description types.String `tfsdk:"description"`
Notes types.String `tfsdk:"notes"`
IncludesPattern types.String `tfsdk:"includes_pattern"`
ExcludesPattern types.String `tfsdk:"excludes_pattern"`
}
func (r BaseResourceModel) KeyString() string {
return r.Key.ValueString()
}
func (r BaseResourceModel) ProjectKeyValue() basetypes.StringValue {
return r.ProjectKey
}
func (r BaseResourceModel) ToAPIModel(ctx context.Context, rclass, packageType string) (interface{}, diag.Diagnostics) {
diags := diag.Diagnostics{}
var projectEnviroments []string
d := r.ProjectEnvironments.ElementsAs(ctx, &projectEnviroments, false)
if d != nil {
diags.Append(d...)
}
return BaseAPIModel{
Key: r.Key.ValueString(),
ProjectKey: r.ProjectKey.ValueString(),
ProjectEnvironments: projectEnviroments,
Rclass: rclass,
PackageType: packageType,
Description: r.Description.ValueString(),
Notes: r.Notes.ValueString(),
IncludesPattern: r.IncludesPattern.ValueString(),
ExcludesPattern: r.ExcludesPattern.ValueString(),
}, diags
}
func (r *BaseResourceModel) FromAPIModel(ctx context.Context, apiModel interface{}) diag.Diagnostics {
diags := diag.Diagnostics{}
model := apiModel.(BaseAPIModel)
r.Key = types.StringValue(model.Key)
r.ProjectKey = types.StringValue(model.ProjectKey)
r.Description = types.StringValue(model.Description)
r.Notes = types.StringValue(model.Notes)
r.IncludesPattern = types.StringValue(model.IncludesPattern)
r.ExcludesPattern = types.StringValue(model.ExcludesPattern)
envs, ds := types.SetValueFrom(ctx, types.StringType, model.ProjectEnvironments)
if ds.HasError() {
diags.Append(ds...)
return diags
}
r.ProjectEnvironments = envs
return diags
}
type BaseAPIModel struct {
Key string `json:"key"`
ProjectKey string `json:"projectKey"`
ProjectEnvironments []string `json:"environments"`
Rclass string `json:"rclass"`
PackageType string `json:"packageType"`
Description string `json:"description"`
Notes string `json:"notes"`
IncludesPattern string `json:"includesPattern"`
ExcludesPattern string `json:"excludesPattern"`
RepoLayoutRef string `json:"repoLayoutRef"`
}
var BaseAttributes = map[string]schema.Attribute{
"key": schema.StringAttribute{
Required: true,
Validators: []validator.String{
validatorfw_string.RepoKey(),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
MarkdownDescription: "A mandatory identifier for the repository that must be unique. Must be 1 - 64 alphanumeric and hyphen characters. It cannot contain spaces or special characters.",
},
"project_key": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
Validators: []validator.String{
validatorfw_string.ProjectKey(),
},
MarkdownDescription: "Project key for assigning this repository to. Must be 2 - 32 lowercase alphanumeric and hyphen characters. When assigning repository to a project, repository key must be prefixed with project key, separated by a dash.",
},
"project_environments": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
Computed: true,
Default: setdefault.StaticValue(types.SetValueMust(types.StringType, []attr.Value{})),
Validators: []validator.Set{
setvalidator.SizeBetween(0, 2),
},
MarkdownDescription: "Project environment for assigning this repository to. Allow values: \"DEV\", \"PROD\", or one of custom environment. " +
"Before Artifactory 7.53.1, up to 2 values (\"DEV\" and \"PROD\") are allowed. From 7.53.1 onward, only one value is allowed. " +
"The attribute should only be used if the repository is already assigned to the existing project. If not, " +
"the attribute will be ignored by Artifactory, but will remain in the Terraform state, which will create " +
"state drift during the update.",
},
"description": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
MarkdownDescription: "Public description.",
},
"notes": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
MarkdownDescription: "Internal description.",
},
"includes_pattern": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString("**/*"),
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
},
MarkdownDescription: "List of comma-separated artifact patterns to include when evaluating artifact requests in the form of `x/y/**/z/*`. " +
"When used, only artifacts matching one of the include patterns are served. By default, all artifacts are included (`**/*`).",
},
"excludes_pattern": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
MarkdownDescription: "List of artifact patterns to exclude when evaluating artifact requests, in the form of `x/y/**/z/*`." +
"By default no artifacts are excluded.",
},
}
func RepoLayoutRefAttribute(repositoryType string, packageType string) map[string]schema.Attribute {
var defaultRepoLayout string
if v, ok := defaultRepoLayoutMap[packageType].SupportedRepoTypes[repositoryType]; ok && v {
defaultRepoLayout = defaultRepoLayoutMap[packageType].RepoLayoutRef
}
return map[string]schema.Attribute{
"repo_layout_ref": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(defaultRepoLayout),
Description: "Sets the layout that the repository should use for storing and identifying modules. A recommended layout that corresponds to the package type defined is suggested, and index packages uploaded and calculate metadata accordingly.",
},
}
}
var PrimaryKeyPairRefAttribute = map[string]schema.Attribute{
"primary_keypair_ref": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
MarkdownDescription: "Primary keypair used to sign artifacts. Default value is empty.",
},
}
var SecondaryKeyPairRefAttribute = map[string]schema.Attribute{
"secondary_keypair_ref": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
MarkdownDescription: "Secondary keypair used to sign artifacts.",
},
}
var CompressionFormatsAttribute = map[string]schema.Attribute{
"index_compression_formats": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
Computed: true,
Default: setdefault.StaticValue(types.SetValueMust(types.StringType, []attr.Value{types.StringValue("bz2")})),
},
}
// SDKv2
var BaseSchemaV1 = map[string]*sdkv2_schema.Schema{
"key": {
Type: sdkv2_schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: sdkv2_validator.RepoKey,
Description: "A mandatory identifier for the repository that must be unique. Must be 1 - 64 alphanumeric and hyphen characters. It cannot contain spaces or special characters.",
},
"project_key": {
Type: sdkv2_schema.TypeString,
Optional: true,
ValidateDiagFunc: sdkv2_validator.ProjectKey,
Description: "Project key for assigning this repository to. Must be 2 - 32 lowercase alphanumeric and hyphen characters. When assigning repository to a project, repository key must be prefixed with project key, separated by a dash.",
},
"project_environments": {
Type: sdkv2_schema.TypeSet,
Elem: &sdkv2_schema.Schema{Type: sdkv2_schema.TypeString},
MinItems: 0,
MaxItems: 2,
Set: sdkv2_schema.HashString,
Optional: true,
Computed: true,
Description: "Project environment for assigning this repository to. Allow values: \"DEV\", \"PROD\", or one of custom environment. " +
"Before Artifactory 7.53.1, up to 2 values (\"DEV\" and \"PROD\") are allowed. From 7.53.1 onward, only one value is allowed. " +
"The attribute should only be used if the repository is already assigned to the existing project. If not, " +
"the attribute will be ignored by Artifactory, but will remain in the Terraform state, which will create " +
"state drift during the update.",
},
"package_type": {
Type: sdkv2_schema.TypeString,
Required: false,
Computed: true,
ForceNew: true,
},
"description": {
Type: sdkv2_schema.TypeString,
Optional: true,
Description: "Public description.",
},
"notes": {
Type: sdkv2_schema.TypeString,
Optional: true,
Description: "Internal description.",
},
"includes_pattern": {
Type: sdkv2_schema.TypeString,
Optional: true,
Default: "**/*",
Description: "List of comma-separated artifact patterns to include when evaluating artifact requests in the form of `x/y/**/z/*`. " +
"When used, only artifacts matching one of the include patterns are served. By default, all artifacts are included (`**/*`).",
},
"excludes_pattern": {
Type: sdkv2_schema.TypeString,
Optional: true,
Description: "List of artifact patterns to exclude when evaluating artifact requests, in the form of `x/y/**/z/*`." +
"By default no artifacts are excluded.",
},
"repo_layout_ref": {
Type: sdkv2_schema.TypeString,
Optional: true,
// The default value in the UI is simple-default, in API maven-2-default. Provider will always override it ro math the UI.
ValidateDiagFunc: ValidateRepoLayoutRefSchemaOverride,
Description: "Sets the layout that the repository should use for storing and identifying modules. A recommended layout that corresponds to the package type defined is suggested, and index packages uploaded and calculate metadata accordingly.",
},
}
var ProxySchemaSDKv2 = map[string]*sdkv2_schema.Schema{
"proxy": {
Type: sdkv2_schema.TypeString,
Optional: true,
Description: "Proxy key from Artifactory Proxies settings. Can't be set if `disable_proxy = true`.",
},
"disable_proxy": {
Type: sdkv2_schema.TypeBool,
Optional: true,
Default: false,
Description: "When set to `true`, the proxy is disabled, and not returned in the API response body. If there is a default proxy set for the Artifactory instance, it will be ignored, too. Introduced since Artifactory 7.41.7.",
},
}
var CompressionFormatsSDKv2 = map[string]*sdkv2_schema.Schema{
"index_compression_formats": {
Type: sdkv2_schema.TypeSet,
Elem: &sdkv2_schema.Schema{
Type: sdkv2_schema.TypeString,
},
Set: sdkv2_schema.HashString,
Optional: true,
},
}
var AlpinePrimaryKeyPairRefSDKv2 = map[string]*sdkv2_schema.Schema{
"primary_keypair_ref": {
Type: sdkv2_schema.TypeString,
Optional: true,
Description: "Used to sign index files in Alpine Linux repositories. " +
"See: https://www.jfrog.com/confluence/display/JFROG/Alpine+Linux+Repositories#AlpineLinuxRepositories-SigningAlpineLinuxIndex",
},
}
var PrimaryKeyPairRefSDKv2 = map[string]*sdkv2_schema.Schema{
"primary_keypair_ref": {
Type: sdkv2_schema.TypeString,
Optional: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotEmpty),
Description: "Primary keypair used to sign artifacts. Default value is empty.",
},
}
var SecondaryKeyPairRefSDKv2 = map[string]*sdkv2_schema.Schema{
"secondary_keypair_ref": {
Type: sdkv2_schema.TypeString,
Optional: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotEmpty),
Description: "Secondary keypair used to sign artifacts.",
},
}
type PrimaryKeyPairRefParam struct {
PrimaryKeyPairRefSDKv2 string `hcl:"primary_keypair_ref" json:"primaryKeyPairRef"`
}
type SecondaryKeyPairRefParam struct {
SecondaryKeyPairRefSDKv2 string `hcl:"secondary_keypair_ref" json:"secondaryKeyPairRef"`
}
type ReadFunc func(d *sdkv2_schema.ResourceData, m interface{}) error
// Constructor Must return a pointer to a struct. When just returning a struct, resty gets confused and thinks it's a map
type Constructor func() (interface{}, error)
func Create(ctx context.Context, d *sdkv2_schema.ResourceData, m interface{}, unpack unpacker.UnpackFunc) sdkv2_diag.Diagnostics {
repo, key, err := unpack(d)
if err != nil {
return sdkv2_diag.FromErr(err)
}
// repo must be a pointer
res, err := m.(util.ProviderMetadata).Client.R().
AddRetryCondition(client.RetryOnMergeError).
SetBody(repo).
SetPathParam("key", key).
Put(RepositoriesEndpoint)
if err != nil {
return sdkv2_diag.FromErr(err)
}
if res.IsError() {
return sdkv2_diag.Errorf("%s", res.String())
}
d.SetId(key)
return nil
}
func MkRepoCreate(unpack unpacker.UnpackFunc, read sdkv2_schema.ReadContextFunc) sdkv2_schema.CreateContextFunc {
return func(ctx context.Context, d *sdkv2_schema.ResourceData, m interface{}) sdkv2_diag.Diagnostics {
err := Create(ctx, d, m, unpack)
if err != nil {
return err
}
return read(ctx, d, m)
}
}
func MkRepoRead(pack packer.PackFunc, construct Constructor) sdkv2_schema.ReadContextFunc {
return func(ctx context.Context, d *sdkv2_schema.ResourceData, m interface{}) sdkv2_diag.Diagnostics {
repo, err := construct()
if err != nil {
return sdkv2_diag.FromErr(err)
}
// repo must be a pointer
resp, err := m.(util.ProviderMetadata).Client.R().
SetResult(repo).
SetPathParam("key", d.Id()).
Get(RepositoriesEndpoint)
if err != nil {
return sdkv2_diag.FromErr(err)
}
if resp.StatusCode() == http.StatusBadRequest || resp.StatusCode() == http.StatusNotFound {
d.SetId("")
return nil
}
if resp.IsError() {
return sdkv2_diag.Errorf("%s", resp.String())
}
return sdkv2_diag.FromErr(pack(repo, d))
}
}
func Update(ctx context.Context, d *sdkv2_schema.ResourceData, m interface{}, unpack unpacker.UnpackFunc) sdkv2_diag.Diagnostics {
repo, key, err := unpack(d)
if err != nil {
return sdkv2_diag.FromErr(err)
}
resp, err := m.(util.ProviderMetadata).Client.R().
AddRetryCondition(client.RetryOnMergeError).
SetBody(repo).
SetPathParam("key", d.Id()).
Post(RepositoriesEndpoint)
if err != nil {
return sdkv2_diag.FromErr(err)
}
if resp.IsError() {
return sdkv2_diag.Errorf("%s", resp.String())
}
d.SetId(key)
projectKeyChanged := d.HasChange("project_key")
if projectKeyChanged {
old, newProject := d.GetChange("project_key")
oldProjectKey := old.(string)
newProjectKey := newProject.(string)
assignToProject := oldProjectKey == "" && len(newProjectKey) > 0
unassignFromProject := len(oldProjectKey) > 0 && newProjectKey == ""
var err error
if assignToProject {
err = AssignRepoToProject(key, newProjectKey, m.(util.ProviderMetadata).Client)
} else if unassignFromProject {
err = UnassignRepoFromProject(key, m.(util.ProviderMetadata).Client)
}
if err != nil {
return sdkv2_diag.FromErr(err)
}
}
return nil
}
func MkRepoUpdate(unpack unpacker.UnpackFunc, read sdkv2_schema.ReadContextFunc) sdkv2_schema.UpdateContextFunc {
return func(ctx context.Context, d *sdkv2_schema.ResourceData, m interface{}) sdkv2_diag.Diagnostics {
err := Update(ctx, d, m, unpack)
if err != nil {
return err
}
return read(ctx, d, m)
}
}
func AssignRepoToProject(repoKey string, projectKey string, client *resty.Client) error {
_, err := client.R().
SetPathParams(map[string]string{
"repoKey": repoKey,
"projectKey": projectKey,
}).
Put("access/api/v1/projects/_/attach/repositories/{repoKey}/{projectKey}")
return err
}
func UnassignRepoFromProject(repoKey string, client *resty.Client) error {
_, err := client.R().
SetPathParam("repoKey", repoKey).
Delete("access/api/v1/projects/_/attach/repositories/{repoKey}")
return err
}
type RepositoryFileList struct {
URI string `json:"uri"`
Files []json.RawMessage `json:"files"`
}
func GetArtifactCount(repoKey string, client *resty.Client) (int, error) {
var fileList RepositoryFileList
resp, err := client.R().
SetPathParam("repo_key", repoKey).
SetQueryParams(map[string]string{
"list": "",
"deep": "1",
"listFolders": "0",
}).
SetResult(&fileList).
Get("artifactory/api/storage/{repo_key}")
if err != nil {
return -1, err
}
if resp.IsError() {
return -1, fmt.Errorf("%s", resp.String())
}
return len(fileList.Files), nil
}
func DeleteRepo(ctx context.Context, d *sdkv2_schema.ResourceData, m interface{}) sdkv2_diag.Diagnostics {
resp, err := m.(util.ProviderMetadata).Client.R().
AddRetryCondition(client.RetryOnMergeError).
SetPathParam("key", d.Id()).
Delete(RepositoriesEndpoint)
if err != nil {
return sdkv2_diag.FromErr(err)
}
if resp.StatusCode() == http.StatusBadRequest || resp.StatusCode() == http.StatusNotFound {
d.SetId("")
return nil
}
if resp.IsError() {
return sdkv2_diag.Errorf("%s", resp.String())
}
return nil
}
func Retry400(response *resty.Response, _ error) bool {
return response.StatusCode() == http.StatusBadRequest
}
var PackageTypesLikeGradle = []string{
GradlePackageType,
SBTPackageType,
IvyPackageType,
}
var ProjectEnvironmentsSupported = []string{"DEV", "PROD"}
func RepoLayoutRefSDKv2Schema(repositoryType string, packageType string) map[string]*sdkv2_schema.Schema {
return map[string]*sdkv2_schema.Schema{
"repo_layout_ref": {
Type: sdkv2_schema.TypeString,
Optional: true,
DefaultFunc: func() (interface{}, error) {
var ref interface{}
ref, err := GetDefaultRepoLayoutRef(repositoryType, packageType)
return ref, err
},
Description: fmt.Sprintf("Repository layout key for the %s repository", repositoryType),
},
}
}
// HandleResetWithNonExistentValue Special handling for field that requires non-existant value for RT
//
// Artifactory REST API will not accept empty string or null to reset value to not set
// Instead, using a non-existant value works as a workaround
// To ensure we don't accidentally set the value to a valid value, we use a UUID v4 string
func HandleResetWithNonExistentValue(d *utilsdk.ResourceData, key string) string {
value := d.GetString(key, false)
// When value has changed and is empty string, then it has been removed from
// the Terraform configuration.
if value == "" && d.HasChange(key) {
return fmt.Sprintf("non-existant-value-%d", testutil.RandomInt())
}
return value
}
const CustomProjectEnvironmentSupportedVersion = "7.53.1"
func ProjectEnvironmentsDiff(ctx context.Context, diff *sdkv2_schema.ResourceDiff, meta interface{}) error {
if data, ok := diff.GetOk("project_environments"); ok {
projectEnvironments := data.(*sdkv2_schema.Set).List()
providerMetadata := meta.(util.ProviderMetadata)
isSupported, err := util.CheckVersion(providerMetadata.ArtifactoryVersion, CustomProjectEnvironmentSupportedVersion)
if err != nil {
return fmt.Errorf("failed to check version %s", err)
}
if isSupported {
if len(projectEnvironments) == 2 {
return fmt.Errorf("for Artifactory %s or later, only one environment can be assigned to a repository", CustomProjectEnvironmentSupportedVersion)
}
} else { // Before 7.53.1
projectEnvironments := data.(*sdkv2_schema.Set).List()
for _, projectEnvironment := range projectEnvironments {
if !slices.Contains(ProjectEnvironmentsSupported, projectEnvironment.(string)) {
return fmt.Errorf("project_environment %s not allowed", projectEnvironment)
}
}
}
}
return nil
}
func VerifyDisableProxy(_ context.Context, diff *sdkv2_schema.ResourceDiff, _ interface{}) error {
disableProxy := diff.Get("disable_proxy").(bool)
proxy := diff.Get("proxy").(string)
if disableProxy && len(proxy) > 0 {
return fmt.Errorf("if `disable_proxy` is set to `true`, `proxy` can't be set")
}
return nil
}
func MkResourceSchema(skeemas map[int16]map[string]*sdkv2_schema.Schema, packer packer.PackFunc, unpack unpacker.UnpackFunc, constructor Constructor) *sdkv2_schema.Resource {
var reader = MkRepoRead(packer, constructor)
return &sdkv2_schema.Resource{
CreateContext: MkRepoCreate(unpack, reader),
ReadContext: reader,
UpdateContext: MkRepoUpdate(unpack, reader),
DeleteContext: DeleteRepo,
Importer: &sdkv2_schema.ResourceImporter{
StateContext: sdkv2_schema.ImportStatePassthroughContext,
},
Schema: skeemas[1],
SchemaVersion: 1,
StateUpgraders: []sdkv2_schema.StateUpgrader{