-
Notifications
You must be signed in to change notification settings - Fork 371
/
resource_helm_release.go
2221 lines (1967 loc) · 70.3 KB
/
resource_helm_release.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 helm
import (
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
pathpkg "path"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"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/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"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"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/pkg/errors"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/downloader"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/postrender"
"helm.sh/helm/v3/pkg/registry"
"helm.sh/helm/v3/pkg/release"
"k8s.io/helm/pkg/strvals"
"sigs.k8s.io/yaml"
)
var (
_ resource.Resource = &HelmReleaseResource{}
_ resource.ResourceWithUpgradeState = &HelmReleaseResource{}
_ resource.ResourceWithModifyPlan = &HelmReleaseResource{}
_ resource.ResourceWithImportState = &HelmReleaseResource{}
)
type HelmReleaseResource struct {
meta *Meta
}
func NewHelmReleaseResource() resource.Resource {
return &HelmReleaseResource{}
}
type HelmReleaseModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Repository types.String `tfsdk:"repository"`
Repository_Key_File types.String `tfsdk:"repository_key_file"`
Repository_Cert_File types.String `tfsdk:"repository_cert_file"`
Repository_Ca_File types.String `tfsdk:"repository_ca_file"`
Repository_Username types.String `tfsdk:"repository_username"`
Repository_Password types.String `tfsdk:"repository_password"`
Pass_Credentials types.Bool `tfsdk:"pass_credentials"`
Chart types.String `tfsdk:"chart"`
Version types.String `tfsdk:"version"`
Devel types.Bool `tfsdk:"devel"`
Values types.List `tfsdk:"values"`
Set types.Set `tfsdk:"set"`
Set_list types.List `tfsdk:"set_list"`
Set_Sensitive types.Set `tfsdk:"set_sensitive"`
Namespace types.String `tfsdk:"namespace"`
Verify types.Bool `tfsdk:"verify"`
Keyring types.String `tfsdk:"keyring"`
Timeout types.Int64 `tfsdk:"timeout"`
Disable_Webhooks types.Bool `tfsdk:"disable_webhooks"`
Disable_Crd_Hooks types.Bool `tfsdk:"disable_crd_hooks"`
Reset_Values types.Bool `tfsdk:"reset_values"`
Reuse_Values types.Bool `tfsdk:"reuse_values"`
Force_Update types.Bool `tfsdk:"force_update"`
Recreate_Pods types.Bool `tfsdk:"recreate_pods"`
Cleanup_On_Fail types.Bool `tfsdk:"cleanup_on_fail"`
Max_History types.Int64 `tfsdk:"max_history"`
Atomic types.Bool `tfsdk:"atomic"`
Skip_Crds types.Bool `tfsdk:"skip_crds"`
Render_Subchart_Notes types.Bool `tfsdk:"render_subchart_notes"`
Disable_Openapi_Validation types.Bool `tfsdk:"disable_openapi_validation"`
Wait types.Bool `tfsdk:"wait"`
Wait_For_Jobs types.Bool `tfsdk:"wait_for_jobs"`
Status types.String `tfsdk:"status"`
Dependency_Update types.Bool `tfsdk:"dependency_update"`
Replace types.Bool `tfsdk:"replace"`
Description types.String `tfsdk:"description"`
Create_Namespace types.Bool `tfsdk:"create_namespace"`
Postrender types.List `tfsdk:"postrender"`
Lint types.Bool `tfsdk:"lint"`
Manifest types.String `tfsdk:"manifest"`
Metadata types.List `tfsdk:"metadata"`
}
var defaultAttributes = map[string]interface{}{
"verify": false,
"timeout": 300,
"wait": true,
"wait_for_jobs": false,
"disable_webhooks": false,
"atomic": false,
"render_subchart_notes": true,
"disable_openapi_validation": false,
"disable_crd_hooks": false,
"force_update": false,
"reset_values": false,
"reuse_values": false,
"recreate_pods": false,
"max_history": 0,
"skip_crds": false,
"cleanup_on_fail": false,
"dependency_update": false,
"replace": false,
"create_namespace": false,
"lint": false,
"pass_credentials": false,
}
type releaseMetaData struct {
Name types.String `tfsdk:"name"`
Revision types.Int64 `tfsdk:"revision"`
Namespace types.String `tfsdk:"namespace"`
Chart types.String `tfsdk:"chart"`
Version types.String `tfsdk:"version"`
App_Version types.String `tfsdk:"app_version"`
Values types.String `tfsdk:"values"`
}
type setResourceModel struct {
Name types.String `tfsdk:"name"`
Value types.String `tfsdk:"value"`
Type types.String `tfsdk:"type"`
}
type set_listResourceModel struct {
Name types.String `tfsdk:"name"`
Value types.List `tfsdk:"value"`
}
type set_sensitiveResourceModel struct {
Name types.String `tfsdk:"name"`
Value types.String `tfsdk:"value"`
Type types.String `tfsdk:"type"`
}
type postrenderModel struct {
Binary_Path types.String `tfsdk:"binary_path"`
Args types.List `tfsdk:"args"`
}
type suppressDescriptionPlanModifier struct{}
func (m suppressDescriptionPlanModifier) Description(ctx context.Context) string {
return "Suppress changes if the new description is an empty string"
}
func (m suppressDescriptionPlanModifier) MarkdownDescription(ctx context.Context) string {
return m.Description(ctx)
}
func (m suppressDescriptionPlanModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) {
if req.PlanValue.IsNull() || req.PlanValue.ValueString() == "" {
resp.PlanValue = req.StateValue
}
}
func suppressDescription() planmodifier.String {
return suppressDescriptionPlanModifier{}
}
type suppressDevelPlanModifier struct{}
func (m suppressDevelPlanModifier) Description(ctx context.Context) string {
return "Suppress changes if the version is set"
}
func (m suppressDevelPlanModifier) MarkdownDescription(ctx context.Context) string {
return m.Description(ctx)
}
func (m suppressDevelPlanModifier) PlanModifyBool(ctx context.Context, req planmodifier.BoolRequest, resp *planmodifier.BoolResponse) {
var version types.String
req.Plan.GetAttribute(ctx, path.Root("version"), &version)
if !version.IsNull() && version.ValueString() != "" {
resp.PlanValue = req.StateValue
}
}
func suppressDevel() planmodifier.Bool {
return suppressDevelPlanModifier{}
}
// Supress Keyring
type suppressKeyringPlanModifier struct{}
func (m suppressKeyringPlanModifier) Description(ctx context.Context) string {
return "Suppress changes if verify is false"
}
func (m suppressKeyringPlanModifier) MarkdownDescription(ctx context.Context) string {
return m.Description(ctx)
}
func (m suppressKeyringPlanModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) {
var verify types.Bool
req.Plan.GetAttribute(ctx, path.Root("verify"), &verify)
if !verify.IsNull() && !verify.ValueBool() {
resp.PlanValue = req.StateValue
}
}
func suppressKeyring() planmodifier.String {
return suppressKeyringPlanModifier{}
}
type NamespacePlanModifier struct{}
func (m NamespacePlanModifier) Description(context.Context) string {
return "Sets the namespace value from the HELM_NAMESPACE environment variable or defaults to 'default'."
}
func (m NamespacePlanModifier) MarkdownDescription(ctx context.Context) string {
return m.Description(ctx)
}
func (m NamespacePlanModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) {
var namespace types.String
diags := req.Plan.GetAttribute(ctx, path.Root("namespace"), &namespace)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
if namespace.IsNull() || namespace.ValueString() == "" {
envNamespace := os.Getenv("HELM_NAMESPACE")
if envNamespace == "" {
envNamespace = "default"
}
resp.PlanValue = types.StringValue(envNamespace)
}
}
func NewNamespacePlanModifier() planmodifier.String {
return &NamespacePlanModifier{}
}
func (r *HelmReleaseResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_release"
}
func (r *HelmReleaseResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Schema to define attributes that are available in the resource",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
},
"name": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Validators: []validator.String{
stringvalidator.LengthBetween(1, 53),
},
Description: "Release name. The length must not be longer than 53 characters",
},
"repository": schema.StringAttribute{
Optional: true,
Description: "Repository where to locate the requested chart. If it is a URL, the chart is installed without installing the repository",
},
"repository_key_file": schema.StringAttribute{
Optional: true,
Description: "The repositories cert key file",
},
"repository_cert_file": schema.StringAttribute{
Optional: true,
Description: "The repositories cert file",
},
"repository_ca_file": schema.StringAttribute{
Optional: true,
Description: "The Repositories CA file",
},
"repository_username": schema.StringAttribute{
Optional: true,
Description: "Username for HTTP basic authentication",
},
"repository_password": schema.StringAttribute{
Optional: true,
Sensitive: true,
Description: "Password for HTTP basic authentication",
},
"pass_credentials": schema.BoolAttribute{
Optional: true,
Description: "Pass credentials to all domains",
Computed: true,
Default: booldefault.StaticBool(false),
},
"chart": schema.StringAttribute{
Required: true,
Description: "Chart name to be installed. A path may be used",
},
"version": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "Specify the exact chart version to install. If this is not specified, the latest version is installed",
},
"devel": schema.BoolAttribute{
Optional: true,
Description: "Use chart development versions, too. Equivalent to version '>0.0.0-0'. If 'version' is set, this is ignored",
PlanModifiers: []planmodifier.Bool{
suppressDevel(),
},
},
"values": schema.ListAttribute{
Optional: true,
Description: "List of values in raw YAML format to pass to helm",
ElementType: types.StringType,
},
"namespace": schema.StringAttribute{
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
NewNamespacePlanModifier(),
},
Description: "Namespace to install the release into",
},
"verify": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Verify the package before installing it.",
},
"keyring": schema.StringAttribute{
Optional: true,
Description: "Location of public keys used for verification, Used only if 'verify is true'",
PlanModifiers: []planmodifier.String{
suppressKeyring(),
},
},
"timeout": schema.Int64Attribute{
Optional: true,
Computed: true,
Default: int64default.StaticInt64(300),
Description: "Time in seconds to wait for any individual kubernetes operation",
},
"disable_webhooks": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Prevent hooks from running",
},
"disable_crd_hooks": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Prevent CRD hooks from running, but run other hooks. See helm install --no-crd-hook",
},
"reuse_values": schema.BoolAttribute{
Optional: true,
Computed: true,
Description: "When upgrading, reuse the last release's values and merge in any overrides. If 'reset_values' is specified, this is ignored",
Default: booldefault.StaticBool(false),
},
"reset_values": schema.BoolAttribute{
Optional: true,
Computed: true,
Description: "When upgrading, reset the values to the ones built into the chart",
Default: booldefault.StaticBool(false),
},
"force_update": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Force resource update through delete/recreate if needed.",
},
"recreate_pods": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Perform pods restart during upgrade/rollback",
},
"cleanup_on_fail": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Allow deletion of new resources created in this upgrade when upgrade fails",
},
"max_history": schema.Int64Attribute{
Optional: true,
Computed: true,
Default: int64default.StaticInt64(0),
Description: "Limit the maximum number of revisions saved per release. Use 0 for no limit",
},
"atomic": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "If set, installation process purges chart on fail. The wait flag will be set automatically if atomic is used",
},
"skip_crds": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "If set, no CRDs will be installed. By default, CRDs are installed if not already present",
},
"render_subchart_notes": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
Description: "If set, render subchart notes along with the parent",
},
"disable_openapi_validation": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "If set, the installation process will not validate rendered templates against the Kubernetes OpenAPI Schema",
},
"wait": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
Description: "Will wait until all resources are in a ready state before marking the release as successful.",
},
"wait_for_jobs": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "If wait is enabled, will wait until all Jobs have been completed before marking the release as successful.",
},
"status": schema.StringAttribute{
Computed: true,
Description: "Status of the release",
},
"dependency_update": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Run helm dependency update before installing the chart",
},
"replace": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Re-use the given name, even if that name is already used. This is unsafe in production",
},
"description": schema.StringAttribute{
Optional: true,
Description: "Add a custom description",
PlanModifiers: []planmodifier.String{
suppressDescription(),
},
},
"create_namespace": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Create the namespace if it does not exist",
},
"lint": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
Description: "Run helm lint when planning",
},
"manifest": schema.StringAttribute{
Description: "The rendered manifest as JSON.",
Computed: true,
},
"metadata": schema.ListNestedAttribute{
Description: "Status of the deployed release.",
Computed: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Computed: true,
Description: "Name is the name of the release",
},
"revision": schema.Int64Attribute{
Computed: true,
Description: "Version is an int32 which represents the version of the release",
},
"namespace": schema.StringAttribute{
Computed: true,
Description: "Namespace is the kubernetes namespace of the release",
},
"chart": schema.StringAttribute{
Computed: true,
Description: "The name of the chart",
},
"version": schema.StringAttribute{
Computed: true,
Description: "A SemVer 2 conformant version string of the chart",
},
"app_version": schema.StringAttribute{
Computed: true,
Description: "The version number of the application being deployed",
},
"values": schema.StringAttribute{
Computed: true,
Description: "Set of extra values. added to the chart. The sensitive data is cloaked. JSON encoded.",
},
},
},
},
},
Blocks: map[string]schema.Block{
"set": schema.SetNestedBlock{
Description: "Custom values to be merged with the values",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
},
"value": schema.StringAttribute{
Required: true,
},
"type": schema.StringAttribute{
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
Validators: []validator.String{
stringvalidator.OneOf("auto", "string"),
},
},
},
},
},
"set_list": schema.ListNestedBlock{
Description: "Custom sensitive values to be merged with the values",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
},
"value": schema.ListAttribute{
Required: true,
ElementType: types.StringType,
},
},
},
},
"set_sensitive": schema.SetNestedBlock{
Description: "Custom sensitive values to be merged with the values",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
},
"value": schema.StringAttribute{
Required: true,
Sensitive: true,
},
"type": schema.StringAttribute{
Optional: true,
Validators: []validator.String{
stringvalidator.OneOf("auto", "string"),
},
},
},
},
},
// single nested
"postrender": schema.ListNestedBlock{
Validators: []validator.List{
listvalidator.SizeAtMost(1),
},
Description: "Postrender command config",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"binary_path": schema.StringAttribute{
Required: true,
Description: "The common binary path",
},
"args": schema.ListAttribute{
Optional: true,
Description: "An argument to the post-renderer (can specify multiple)",
ElementType: types.StringType,
},
},
},
},
},
// Indicating schema has undergone changes
Version: 1,
}
}
func (r *HelmReleaseResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Ensure that the ProviderData is not nil
if req.ProviderData == nil {
return
}
// Assert that the ProviderData is of type *Meta
meta, ok := req.ProviderData.(*Meta)
if !ok {
resp.Diagnostics.AddError(
"Provider Configuration Error",
fmt.Sprintf("Unexpected ProviderData type: %T", req.ProviderData),
)
return
}
tflog.Debug(ctx, fmt.Sprintf("Configured meta: %+v", meta))
r.meta = meta
}
// maps version 0 state to the upgrade function.
// If terraform detects data with version 0, we call upgrade to upgrade the state to the current schema version "1"
func (r *HelmReleaseResource) UpgradeState(ctx context.Context) map[int64]resource.StateUpgrader {
return map[int64]resource.StateUpgrader{
0: {
StateUpgrader: stateUpgradeV0toV1,
},
}
}
func stateUpgradeV0toV1(ctx context.Context, req resource.UpgradeStateRequest, resp *resource.UpgradeStateResponse) {
var priorState map[string]interface{}
diags := req.State.Get(ctx, &priorState)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
if priorState["pass_credentials"] == nil {
priorState["pass_credentials"] = false
}
if priorState["wait_for_jobs"] == nil {
priorState["wait_for_jobs"] = false
}
diags = resp.State.Set(ctx, priorState)
resp.Diagnostics.Append(diags...)
}
const sensitiveContentValue = "(sensitive value)"
func cloakSetValue(values map[string]interface{}, valuePath string) {
pathKeys := strings.Split(valuePath, ".")
sensitiveKey := pathKeys[len(pathKeys)-1]
parentPathKeys := pathKeys[:len(pathKeys)-1]
m := values
for _, key := range parentPathKeys {
v, ok := m[key].(map[string]interface{})
if !ok {
return
}
m = v
}
m[sensitiveKey] = sensitiveContentValue
}
func mergeMaps(a, b map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{}, len(a))
for k, v := range a {
out[k] = v
}
for k, v := range b {
if vMap, ok := v.(map[string]interface{}); ok {
if bv, ok := out[k]; ok {
if bvMap, ok := bv.(map[string]interface{}); ok {
out[k] = mergeMaps(bvMap, vMap)
continue
}
}
}
out[k] = v
}
return out
}
func (r *HelmReleaseResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var state HelmReleaseModel
diags := req.Plan.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Plan state on Create: %+v", state))
meta := r.meta
if meta == nil {
resp.Diagnostics.AddError("Initialization Error", "Meta instance is not initialized")
return
}
namespace := state.Namespace.ValueString()
actionConfig, err := meta.GetHelmConfiguration(ctx, namespace)
if err != nil {
resp.Diagnostics.AddError("Error getting helm configuration", fmt.Sprintf("Unable to get Helm configuration for namespace %s: %s", namespace, err))
return
}
ociDiags := OCIRegistryLogin(ctx, actionConfig, meta.RegistryClient, state.Repository.ValueString(), state.Chart.ValueString(), state.Repository_Username.ValueString(), state.Repository_Password.ValueString())
resp.Diagnostics.Append(ociDiags...)
if resp.Diagnostics.HasError() {
return
}
client := action.NewInstall(actionConfig)
cpo, chartName, cpoDiags := chartPathOptions(&state, meta, &client.ChartPathOptions)
resp.Diagnostics.Append(cpoDiags...)
if resp.Diagnostics.HasError() {
return
}
c, path, chartDiags := getChart(ctx, &state, meta, chartName, cpo)
resp.Diagnostics.Append(chartDiags...)
if resp.Diagnostics.HasError() {
return
}
updated, depDiags := checkChartDependencies(ctx, &state, c, path, meta)
resp.Diagnostics.Append(depDiags...)
if resp.Diagnostics.HasError() {
return
} else if updated {
c, err = loader.Load(path)
if err != nil {
resp.Diagnostics.AddError("Error loading chart", fmt.Sprintf("Could not load chart: %s", err))
return
}
}
values, valuesDiags := getValues(ctx, &state)
resp.Diagnostics.Append(valuesDiags...)
if resp.Diagnostics.HasError() {
return
}
err = isChartInstallable(c)
if err != nil {
resp.Diagnostics.AddError("Error checking if chart is installable", fmt.Sprintf("Chart is not installable: %s", err))
return
}
client.ClientOnly = false
client.DryRun = false
client.DisableHooks = state.Disable_Webhooks.ValueBool()
client.Wait = state.Wait.ValueBool()
client.WaitForJobs = state.Wait_For_Jobs.ValueBool()
client.Devel = state.Devel.ValueBool()
client.DependencyUpdate = state.Dependency_Update.ValueBool()
client.Timeout = time.Duration(state.Timeout.ValueInt64()) * time.Second
client.Namespace = state.Namespace.ValueString()
client.ReleaseName = state.Name.ValueString()
client.Atomic = state.Atomic.ValueBool()
client.SkipCRDs = state.Skip_Crds.ValueBool()
client.SubNotes = state.Render_Subchart_Notes.ValueBool()
client.DisableOpenAPIValidation = state.Disable_Openapi_Validation.ValueBool()
client.Replace = state.Replace.ValueBool()
client.Description = state.Description.ValueString()
client.CreateNamespace = state.Create_Namespace.ValueBool()
if !state.Postrender.IsNull() {
tflog.Debug(ctx, "Postrender is not null")
// Extract the list of postrender configurations
var postrenderList []postrenderModel
postrenderDiags := state.Postrender.ElementsAs(ctx, &postrenderList, false)
resp.Diagnostics.Append(postrenderDiags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Postrender list extracted: %+v", postrenderList))
// Since postrender is defined as a list but can only have one element, we fetch the first item
if len(postrenderList) > 0 {
prModel := postrenderList[0]
binaryPath := prModel.Binary_Path.ValueString()
argsList := prModel.Args.Elements()
var args []string
for _, arg := range argsList {
args = append(args, arg.(basetypes.StringValue).ValueString())
}
tflog.Debug(ctx, fmt.Sprintf("Creating post-renderer with binary path: %s and args: %v", binaryPath, args))
pr, err := postrender.NewExec(binaryPath, args...)
if err != nil {
resp.Diagnostics.AddError("Error creating post-renderer", fmt.Sprintf("Could not create post-renderer: %s", err))
return
}
client.PostRenderer = pr
}
}
rel, err := client.Run(c, values)
if err != nil && rel == nil {
resp.Diagnostics.AddError("installation failed", err.Error())
return
}
if err != nil && rel != nil {
exists, existsDiags := resourceReleaseExists(ctx, state.Name.ValueString(), state.Namespace.ValueString(), meta)
resp.Diagnostics.Append(existsDiags...)
if resp.Diagnostics.HasError() {
return
}
if !exists {
resp.Diagnostics.AddError("installation failed", err.Error())
return
}
diags := setReleaseAttributes(ctx, &state, rel, meta)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(diag.NewWarningDiagnostic("Helm release created with warnings", fmt.Sprintf("Helm release %q was created but has a failed status. Use the `helm` command to investigate the error, correct it, then run Terraform again.", client.ReleaseName)))
resp.Diagnostics.Append(diag.NewErrorDiagnostic("Helm release error", err.Error()))
return
}
diags = setReleaseAttributes(ctx, &state, rel, meta)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
func (r *HelmReleaseResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state HelmReleaseModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Current state before changes: %+v", state))
meta := r.meta
if meta == nil {
resp.Diagnostics.AddError(
"Meta not set",
"The meta information is not set for the resource",
)
return
}
exists, diags := resourceReleaseExists(ctx, state.Name.ValueString(), state.Namespace.ValueString(), meta)
if !exists {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
logID := fmt.Sprintf("[resourceReleaseRead: %s]", state.Name.ValueString())
tflog.Debug(ctx, fmt.Sprintf("%s Started", logID))
c, err := meta.GetHelmConfiguration(ctx, state.Namespace.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error getting helm configuration",
fmt.Sprintf("Unable to get Helm configuration for namespace %s: %s", state.Namespace.ValueString(), err),
)
return
}
release, err := getRelease(ctx, meta, c, state.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error getting release",
fmt.Sprintf("Unable to get Helm release %s: %s", state.Name.ValueString(), err.Error()),
)
return
}
diags = setReleaseAttributes(ctx, &state, release, meta)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
resp.Diagnostics.AddError(
"Error setting release attributes",
fmt.Sprintf("Unable to set attributes for helm release %s", state.Name.ValueString()),
)
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &state)...)
}
func (r *HelmReleaseResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan HelmReleaseModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Current state of the resource before update operation is applied
var state HelmReleaseModel
diags = req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
logID := fmt.Sprintf("[resourceReleaseUpdate: %s]", state.Name.ValueString())
tflog.Debug(ctx, fmt.Sprintf("%s Started", logID))
meta := r.meta
namespace := state.Namespace.ValueString()
tflog.Debug(ctx, fmt.Sprintf("%s Getting helm configuration for namespace: %s", logID, namespace))
actionConfig, err := meta.GetHelmConfiguration(ctx, namespace)
if err != nil {
tflog.Debug(ctx, fmt.Sprintf("%s Failed to get helm configuration: %v", logID, err))
resp.Diagnostics.AddError("Error getting helm configuration", fmt.Sprintf("Unable to get Helm configuration for namespace %s: %s", namespace, err))
return
}
ociDiags := OCIRegistryLogin(ctx, actionConfig, meta.RegistryClient, state.Repository.ValueString(), state.Chart.ValueString(), state.Repository_Username.ValueString(), state.Repository_Password.ValueString())
resp.Diagnostics.Append(ociDiags...)
if resp.Diagnostics.HasError() {
return
}
client := action.NewUpgrade(actionConfig)
cpo, chartName, cpoDiags := chartPathOptions(&plan, meta, &client.ChartPathOptions)
resp.Diagnostics.Append(cpoDiags...)
if resp.Diagnostics.HasError() {
return
}
c, path, chartDiags := getChart(ctx, &plan, meta, chartName, cpo)
resp.Diagnostics.Append(chartDiags...)
if resp.Diagnostics.HasError() {
return
}
// Check and update the chart's depenedcies if it's needed
updated, depDiags := checkChartDependencies(ctx, &plan, c, path, meta)
resp.Diagnostics.Append(depDiags...)
if resp.Diagnostics.HasError() {
return
} else if updated {
c, err = loader.Load(path)
if err != nil {
resp.Diagnostics.AddError("Error loading chart", fmt.Sprintf("Could not load chart: %s", err))
return
}
}
client.Devel = plan.Devel.ValueBool()
client.Namespace = plan.Namespace.ValueString()
client.Timeout = time.Duration(plan.Timeout.ValueInt64()) * time.Second
client.Wait = plan.Wait.ValueBool()
client.WaitForJobs = plan.Wait_For_Jobs.ValueBool()
client.DryRun = false
client.DisableHooks = plan.Disable_Webhooks.ValueBool()
client.Atomic = plan.Atomic.ValueBool()
client.SkipCRDs = plan.Skip_Crds.ValueBool()
client.SubNotes = plan.Render_Subchart_Notes.ValueBool()
client.DisableOpenAPIValidation = plan.Disable_Openapi_Validation.ValueBool()
client.Force = plan.Force_Update.ValueBool()
client.ResetValues = plan.Reset_Values.ValueBool()
client.ReuseValues = plan.Reuse_Values.ValueBool()
client.Recreate = plan.Recreate_Pods.ValueBool()
client.MaxHistory = int(plan.Max_History.ValueInt64())
client.CleanupOnFail = plan.Cleanup_On_Fail.ValueBool()
client.Description = plan.Description.ValueString()
if !plan.Postrender.IsNull() {
// Extract the list of postrender configurations
var postrenderList []postrenderModel
postrenderDiags := plan.Postrender.ElementsAs(ctx, &postrenderList, false)
resp.Diagnostics.Append(postrenderDiags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, fmt.Sprintf("Initial postrender values update method: %+v", postrenderList))
// Since postrender is defined as a list but can only have one element, we fetch the first item
if len(postrenderList) > 0 {
prModel := postrenderList[0]
binaryPath := prModel.Binary_Path.ValueString()
argsList := prModel.Args.Elements()
var args []string
for _, arg := range argsList {