-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_package.go
More file actions
3212 lines (2872 loc) · 116 KB
/
Copy pathresource_package.go
File metadata and controls
3212 lines (2872 loc) · 116 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
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
// Copyright 2024-2026 Defense Unicorns
// SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-Defense-Unicorns-Commercial
package provider
import (
"context"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"math"
"math/big"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/goccy/go-yaml"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"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/objectdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-go/tftypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
udsCluster "github.com/defenseunicorns/terraform-provider-uds/internal/cluster"
"github.com/defenseunicorns/terraform-provider-uds/internal/logging"
udsPackager "github.com/defenseunicorns/terraform-provider-uds/internal/packager"
udsValidator "github.com/defenseunicorns/terraform-provider-uds/internal/provider/validator"
zarfAPI "github.com/zarf-dev/zarf/src/api"
"github.com/zarf-dev/zarf/src/api/v1alpha1"
"github.com/zarf-dev/zarf/src/pkg/ocischeme"
zarfPackager "github.com/zarf-dev/zarf/src/pkg/packager"
zarfFilters "github.com/zarf-dev/zarf/src/pkg/packager/filters"
"github.com/zarf-dev/zarf/src/pkg/packager/layout"
zarfSigning "github.com/zarf-dev/zarf/src/pkg/signing"
zarfState "github.com/zarf-dev/zarf/src/pkg/state"
zarfValue "github.com/zarf-dev/zarf/src/pkg/value"
zarfZoci "github.com/zarf-dev/zarf/src/pkg/zoci"
zarfTypes "github.com/zarf-dev/zarf/src/types"
"oras.land/oras-go/v2/registry"
)
var (
errDuplicatePackage = errors.New("package already exists")
errPackageExistenceCheck = errors.New("failed to check for existing package")
)
// deployedPackageIdentity is authoritative only after the returned Zarf state
// has been checked against the resource ID.
type deployedPackageIdentity struct {
ID string
Name string
Namespace string
Package zarfState.DeployedPackage
}
type remoteIdentityError struct{ reason string }
func (e *remoteIdentityError) Error() string { return e.reason }
// packageAbsentError marks a confirmed remote absence separately from a lookup
// failure so lifecycle callers can preserve their distinct state semantics.
type packageAbsentError struct{}
func (e *packageAbsentError) Error() string { return "deployed package was not found" }
type stateIdentityError struct{ reason string }
func (e *stateIdentityError) Error() string { return e.reason }
type canonicalNameMismatchError struct {
deployedName string
canonicalName string
namespace string
}
func (e *canonicalNameMismatchError) Error() string {
return fmt.Sprintf("deployed package name %q does not match canonical source package name %q", e.deployedName, e.canonicalName)
}
type canonicalSourceError struct{}
func (e *canonicalSourceError) Error() string {
return "could not load source package metadata needed to verify its canonical name"
}
// deploymentAttemptedError marks failures after packager.Deploy was invoked
// without changing the error text shown to users.
type deploymentAttemptedError struct {
cause error
}
func (e *deploymentAttemptedError) Error() string {
return e.cause.Error()
}
func (e *deploymentAttemptedError) Unwrap() error {
return e.cause
}
// Ensure provider defined types fully satisfy framework interfaces.
var (
_ resource.Resource = &PackageResource{}
_ resource.ResourceWithImportState = &PackageResource{}
_ resource.ResourceWithModifyPlan = &PackageResource{}
_ resource.ResourceWithConfigValidators = &PackageResource{}
)
const (
clusterTimeoutMinutes = 5
componentBlockDeprecationMessage = "The component block is deprecated. Use optional_components to select optional components. The component block will be removed in a future version."
componentOverrideBlockDeprecationMessage = "Component overrides are deprecated and will no longer be supported in a future version. Use the top-level values or sensitive_values attributes to supply Helm chart values through Zarf package values."
)
type packageSignatureVerifier func(context.Context, *layout.PackageLayout, zarfSigning.VerifyBlobOptions) error
// NewPackageResource creates a new instance of the package resource.
func NewPackageResource(providerConfig *udsProviderConfig, packager udsPackager.Packager, packageComponentFilter udsPackager.PackageComponentFilter, cluster udsCluster.Cluster) resource.Resource {
if providerConfig == nil {
providerConfig = &udsProviderConfig{}
}
if providerConfig.OCISchemeNegotiator == nil {
providerConfig.OCISchemeNegotiator = ocischeme.New(ocischeme.Options{TTL: ociSchemeNegotiatorTTL})
}
if packager == nil {
packager = udsPackager.NewPackager()
}
if packageComponentFilter == nil {
packageComponentFilter = udsPackager.NewPackageComponentFilter()
}
if cluster == nil {
cluster = udsCluster.NewCluster()
}
return &PackageResource{
providerConfig: providerConfig,
packager: packager,
packageFilter: packageComponentFilter,
cluster: cluster,
verifyPackageSignatureFunc: defaultPackageSignatureVerifier,
}
}
func defaultPackageSignatureVerifier(ctx context.Context, pkgLayout *layout.PackageLayout, opts zarfSigning.VerifyBlobOptions) error {
return pkgLayout.VerifyPackageSignature(ctx, opts)
}
// PackageResourceModel describes the resource data model.
type PackageResourceModel struct {
ID types.String `tfsdk:"id"`
Source types.String `tfsdk:"source"`
Architecture types.String `tfsdk:"architecture"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
SignatureVerification types.Object `tfsdk:"signature_verification"`
Namespace types.String `tfsdk:"namespace"`
Components types.Set `tfsdk:"component"` // Set of ComponentModel objects (TODO: remove when component block is removed)
OptionalComponents types.Set `tfsdk:"optional_components"` // Set of string component names (alpha)
Vars types.Set `tfsdk:"vars"` // Set of VariableModel objects
SensitiveVars types.Set `tfsdk:"sensitive_vars"` // Set of VariableModel objects
Values types.Dynamic `tfsdk:"values"`
SensitiveValues types.Dynamic `tfsdk:"sensitive_values"`
// readonly metadata
Name types.String `tfsdk:"name"`
Kind types.String `tfsdk:"kind"` // Kind reflects the type of UDS package; either ZarfInit or ZarfPackage
Version types.String `tfsdk:"version"`
Metadata types.Object `tfsdk:"metadata"`
ConnectStrings types.Set `tfsdk:"connect_strings"` // Set of ConnectString objects
// zarf package variables are written automatically
// into the computed `set_variables` map.
// All variables exported from the package are persisted to this map and
// treated as sensitive in state regardless of their original sensitivity.
SetVariables types.Map `tfsdk:"set_variables"`
}
// ComponentModel represents a UDS package component configuration.
// TODO: remove when component block is removed
type ComponentModel struct {
Name types.String `tfsdk:"name"`
Overrides types.Set `tfsdk:"override"` // Set of ComponentChartValuesModel objects
}
// ComponentChartValuesModel represents a helm chart override values configuration for a package component.
// TODO: remove when component block is removed
type ComponentChartValuesModel struct {
ChartName types.String `tfsdk:"chart_name"`
Values types.Set `tfsdk:"values"` // Set of HelmChartPathValueModel objects
SensitiveValues types.Set `tfsdk:"sensitive_values"` // Set of HelmChartPathValueModel objects
}
// HelmChartPathValueModel represents a path/value pair for setting helm chart values
// TODO: remove when component block is removed
type HelmChartPathValueModel struct {
Path types.String `tfsdk:"path"`
Value types.String `tfsdk:"value"`
}
// VariableModel represents a name/value pair for setting UDS package variables
type VariableModel struct {
Name types.String `tfsdk:"name"`
Value types.String `tfsdk:"value"`
}
// KeylessVerificationModel holds Sigstore/OIDC keyless signature verification configuration.
type KeylessVerificationModel struct {
CertificateIdentity types.String `tfsdk:"certificate_identity"`
CertificateIdentityRegexp types.String `tfsdk:"certificate_identity_regexp"`
CertificateOIDCIssuer types.String `tfsdk:"certificate_oidc_issuer"`
CertificateOIDCIssuerRegexp types.String `tfsdk:"certificate_oidc_issuer_regexp"`
TrustedRoot types.String `tfsdk:"trusted_root"`
InsecureIgnoreTlog types.Bool `tfsdk:"insecure_ignore_tlog"`
UseSignedTimestamps types.Bool `tfsdk:"use_signed_timestamps"`
}
var keylessVerificationAttrTypes = map[string]attr.Type{
"certificate_identity": types.StringType,
"certificate_identity_regexp": types.StringType,
"certificate_oidc_issuer": types.StringType,
"certificate_oidc_issuer_regexp": types.StringType,
"trusted_root": types.StringType,
"insecure_ignore_tlog": types.BoolType,
"use_signed_timestamps": types.BoolType,
}
// SignatureVerificationModel holds all signature verification configuration for a UDS package.
type SignatureVerificationModel struct {
Verify types.Bool `tfsdk:"verify"`
PublicKey types.String `tfsdk:"public_key"`
Keyless types.Object `tfsdk:"keyless"`
}
var signatureVerificationAttrTypes = map[string]attr.Type{
"verify": types.BoolType,
"public_key": types.StringType,
"keyless": types.ObjectType{AttrTypes: keylessVerificationAttrTypes},
}
var connectStringAttrTypes = map[string]attr.Type{
"name": types.StringType,
"description": types.StringType,
}
var packageMetadataAttrTypes = map[string]attr.Type{
"name": types.StringType,
"description": types.StringType,
"version": types.StringType,
"status": types.StringType,
"generation": types.Int64Type,
"digest": types.StringType,
}
var defaultSignatureVerification = types.ObjectValueMust(
signatureVerificationAttrTypes,
map[string]attr.Value{
"verify": types.BoolValue(true),
"public_key": types.StringNull(),
"keyless": types.ObjectNull(keylessVerificationAttrTypes),
},
)
// Metadata sets the resource type name.
func (r *PackageResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_package"
}
// Schema defines the schema for the resource.
func (r *PackageResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Deploys and manages a UDS package.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
MarkdownDescription: "Identifier for the deployed UDS package.",
Computed: true,
},
"name": schema.StringAttribute{
MarkdownDescription: "Name of the UDS Package.",
Computed: true,
},
"source": schema.StringAttribute{
MarkdownDescription: "OCI distribution reference (including oci:// scheme) or local file path (absolute or relative) to the package.",
Required: true,
Validators: []validator.String{
udsValidator.PackageSourceValidator(),
},
},
"architecture": schema.StringAttribute{
MarkdownDescription: "System architecture of the target cluster. Defaults to the provider default architecture.",
Optional: true,
Computed: true,
Validators: []validator.String{
stringvalidator.OneOf("amd64", "arm64"),
},
},
"version": schema.StringAttribute{
MarkdownDescription: "Version of the deployed UDS package.",
Computed: true,
},
"signature_verification": schema.SingleNestedAttribute{
MarkdownDescription: "Signature verification configuration. Omit to use defaults (verification enabled, no key).",
Optional: true,
Computed: true,
Default: objectdefault.StaticValue(defaultSignatureVerification),
Attributes: map[string]schema.Attribute{
"verify": schema.BoolAttribute{
MarkdownDescription: "When true, verify the signature of a signed UDS package. When false, skip package signature verification.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(true),
},
"public_key": schema.StringAttribute{
MarkdownDescription: "Raw public key value to validate against a key-signed UDS package. Mutually exclusive with `keyless`.",
Optional: true,
},
"keyless": schema.SingleNestedAttribute{
MarkdownDescription: "Keyless (Sigstore/OIDC) signature verification configuration. Mutually exclusive with `public_key`.",
Optional: true,
Attributes: map[string]schema.Attribute{
"certificate_identity": schema.StringAttribute{
MarkdownDescription: "Required identity claim in the signing certificate. Mutually exclusive with `certificate_identity_regexp`.",
Optional: true,
},
"certificate_identity_regexp": schema.StringAttribute{
MarkdownDescription: "Regex-based alternative to `certificateIdentity` for pattern matching. Mutually exclusive with `certificate_identity`.",
Optional: true,
},
"certificate_oidc_issuer": schema.StringAttribute{
MarkdownDescription: "Required OIDC issuer claim in the signing certificate. Mutually exclusive with `certificate_oidc_issuer_regexp`.",
Optional: true,
},
"certificate_oidc_issuer_regexp": schema.StringAttribute{
MarkdownDescription: "Regex-based variant of `certificateOIDCIssuer`. Mutually exclusive with `certificate_oidc_issuer`.",
Optional: true,
},
"trusted_root": schema.StringAttribute{
MarkdownDescription: "Sigstore TrustedRoot JSON content for keyless signature verification. Omit to use Zarf's embedded TrustedRoot.",
Optional: true,
},
"insecure_ignore_tlog": schema.BoolAttribute{
MarkdownDescription: "Skip Rekor transparency log inclusion verification. Set to true only for air-gapped or private Sigstore infrastructure.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"use_signed_timestamps": schema.BoolAttribute{
MarkdownDescription: "Verify RFC3161 signed timestamps in the Sigstore verification bundle. Auto-enabled when the bundle contains TSA timestamp data.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
},
},
},
},
"timeouts": timeouts.Attributes(ctx, timeouts.Opts{
Create: true,
Read: true,
Update: true,
Delete: true,
CreateDescription: "Timeout for package deployment (default 30 m). Covers cluster connection, package load, and Helm/Zarf execution. If deployment fails after package state may have been recorded, the provider performs a separate recovery lookup for up to 5 m to preserve that state. This recovery window is additional to the configured timeout and remains bounded by the overall operation deadline or cancellation.",
ReadDescription: "Total read-operation wall-clock timeout (default 5 m). Covers cluster connection and state retrieval.",
UpdateDescription: "Timeout for package update (default 30 m). Covers cluster connection, package load, and redeployment. Failed updates return their error within this timeout; no separate failed-operation recovery lookup is performed.",
DeleteDescription: "Total delete-operation wall-clock timeout (default 30 m). Covers cluster connection, package load, and removal.",
}),
"kind": schema.StringAttribute{
MarkdownDescription: "Kind of UDS package; ZarfInitConfig or ZarfPackageConfig.",
Computed: true,
},
"metadata": &schema.SingleNestedAttribute{
Computed: true,
MarkdownDescription: "Metadata retrieved from the UDS package (zarf.yaml).",
Attributes: map[string]schema.Attribute{
"name": &schema.StringAttribute{
Computed: true,
MarkdownDescription: "Name of the UDS package. Used to identify the deployed UDS package.",
},
"description": &schema.StringAttribute{
Computed: true,
MarkdownDescription: "Description of the UDS package, from the zarf.yaml file.",
},
"version": &schema.StringAttribute{
Computed: true,
MarkdownDescription: "Version of the UDS package, from the zarf.yaml file.",
},
"status": &schema.StringAttribute{
Computed: true,
MarkdownDescription: "Deployment status of the UDS package.",
},
"generation": &schema.Int64Attribute{
Computed: true,
MarkdownDescription: "Deployment generation of the UDS package.",
},
"digest": &schema.StringAttribute{
Computed: true,
MarkdownDescription: "Digest of the deployed UDS package.",
},
},
},
"vars": schema.SetNestedAttribute{
MarkdownDescription: "UDS package variables to set.",
Optional: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
MarkdownDescription: "Name of the variable to set.",
Required: true,
},
"value": schema.StringAttribute{
MarkdownDescription: "Value for the variable to set.",
Required: true,
},
},
},
Validators: []validator.Set{
func() validator.Set {
v, _ := udsValidator.NewBlockStringAttributeUniquenessValidator("var", "name")
return v
}(),
},
},
"sensitive_vars": schema.SetNestedAttribute{
MarkdownDescription: "Sensitive UDS package variables to set.",
Optional: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
MarkdownDescription: "Name of the variable to set.",
Required: true,
},
"value": schema.StringAttribute{
MarkdownDescription: "Value for the variable to set.",
Required: true,
Sensitive: true,
},
},
},
Validators: []validator.Set{
func() validator.Set {
v, _ := udsValidator.NewBlockStringAttributeUniquenessValidator("sensitive_var", "name")
return v
}(),
},
},
"namespace": schema.StringAttribute{
MarkdownDescription: "[Alpha] Namespace in which to deploy the UDS package.",
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"optional_components": schema.SetAttribute{
MarkdownDescription: "[Alpha] Set of optional package component names to install. Case-sensitive. Mutually exclusive with `component` blocks — specifying both is a validation error. When omitted or set to an empty list, only required package components are installed.",
Optional: true,
Computed: true,
ElementType: types.StringType,
},
"connect_strings": schema.SetNestedAttribute{
Computed: true,
MarkdownDescription: "Connect strings for connecting to services deployed by the package.",
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Computed: true,
MarkdownDescription: "Name of the service/connection.",
},
"description": schema.StringAttribute{
Computed: true,
MarkdownDescription: "Description of the service/compute-resource that this connect string is for.",
},
},
},
},
"set_variables": schema.MapAttribute{
MarkdownDescription: "Computed map of zarf variables set for this package.",
Computed: true,
ElementType: types.StringType,
Sensitive: true,
},
"values": schema.DynamicAttribute{
MarkdownDescription: "[Alpha] Zarf package values to apply at deploy time. Packages with a values schema are validated against that schema. Cannot be used with component blocks.",
Optional: true,
},
"sensitive_values": schema.DynamicAttribute{
MarkdownDescription: "[Alpha] Sensitive Zarf package values to apply at deploy time. Packages with a values schema are validated against that schema. Values are redacted from Terraform/OpenTofu output. Cannot be used with component blocks.",
Optional: true,
Sensitive: true,
},
},
Blocks: map[string]schema.Block{
// TODO: remove when component block is removed
"component": schema.SetNestedBlock{
MarkdownDescription: "[Deprecated] Legacy component selection and override configuration. Use `optional_components` to select optional components. Mutually exclusive with `optional_components`.",
DeprecationMessage: componentBlockDeprecationMessage,
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Required: true,
MarkdownDescription: "Name of the component.",
},
},
Blocks: map[string]schema.Block{
"override": schema.SetNestedBlock{
MarkdownDescription: "[Deprecated] Component overrides will no longer be supported in a future version. Use the top-level `values` or `sensitive_values` attributes to supply Helm chart values through Zarf package values.",
DeprecationMessage: componentOverrideBlockDeprecationMessage,
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"chart_name": schema.StringAttribute{
Required: true,
MarkdownDescription: "Name of the Helm chart to set values for.",
},
"values": schema.SetNestedAttribute{
MarkdownDescription: "Set of path values to set for the chart.",
Optional: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"path": schema.StringAttribute{
MarkdownDescription: "The dot-notation path in the chart values to set.",
Required: true,
},
"value": schema.StringAttribute{
MarkdownDescription: "The raw YAML value to set at the specified path.",
Required: true,
},
},
},
Validators: []validator.Set{
func() validator.Set {
v, _ := udsValidator.NewBlockStringAttributeUniquenessValidator("values", "path")
return v
}(),
},
},
"sensitive_values": schema.SetNestedAttribute{
MarkdownDescription: "Set of sensitive key-value overrides for the chart.",
Optional: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"path": schema.StringAttribute{
MarkdownDescription: "The dot-notation path in the chart values to set.",
Required: true,
},
"value": schema.StringAttribute{
MarkdownDescription: "The raw YAML sensitive value to set at the specified path.",
Required: true,
Sensitive: true,
},
},
},
Validators: []validator.Set{
func() validator.Set {
v, _ := udsValidator.NewBlockStringAttributeUniquenessValidator("sensitive_values", "path")
return v
}(),
},
},
},
},
Validators: []validator.Set{
func() validator.Set {
v, _ := udsValidator.NewBlockStringAttributeUniquenessValidator("override", "chart_name")
return v
}(),
},
},
},
},
Validators: []validator.Set{
func() validator.Set {
v, _ := udsValidator.NewBlockStringAttributeUniquenessValidator("component", "name")
return v
}(),
},
},
},
}
}
// PackageResource defines the resource implementation.
type PackageResource struct {
providerConfig *udsProviderConfig
packager udsPackager.Packager
cluster udsCluster.Cluster
packageFilter udsPackager.PackageComponentFilter
verifyPackageSignatureFunc packageSignatureVerifier
}
// ValidateConfig ensures validation between interdependant fields within a PackageResourceModel.
func (r *PackageResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var model PackageResourceModel
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
validateUniqueVarNames(model, resp)
validateSignatureVerificationAttributes(ctx, model, resp)
// TODO: remove when component block is removed
validateComponentBlockOptionalComponentsMutualExclusivity(model, resp)
validateValuesComponentMutualExclusivity(model, resp)
}
// Configure configures the resource with provider data.
func (r *PackageResource) Configure(_ context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
r.providerConfig = req.ProviderData.(*udsProviderConfig)
// Initialize the packager if it wasn't set in NewPackageResource
if r.packager == nil {
r.packager = udsPackager.NewPackager()
}
if r.cluster == nil {
r.cluster = udsCluster.NewCluster()
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
operationCtx := logging.WithPackageContext(ctx, "create", "", "")
operationCompleted := false
startedAt := time.Now()
defer func() {
if operationCompleted {
logging.PackageCompleted(operationCtx, time.Since(startedAt))
return
}
err := errors.New("package create did not complete")
if resp.Diagnostics.HasError() {
err = errors.New(resp.Diagnostics.Errors()[0].Detail())
}
logging.PackageFailed(operationCtx, "", err)
}()
var plan PackageResourceModel
diags := req.Plan.Get(operationCtx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
operationCtx = logging.WithPackageContext(operationCtx, "create", "", plan.Namespace.ValueString())
createTimeout, timeoutDiags := plan.Timeouts.Create(operationCtx, 30*time.Minute)
resp.Diagnostics.Append(timeoutDiags...)
if resp.Diagnostics.HasError() {
return
}
timeoutCtx, cancel := context.WithTimeout(operationCtx, createTimeout)
defer cancel()
var err error
plan, err = r.deployAsNew(timeoutCtx, plan)
if !plan.Name.IsNull() && !plan.Name.IsUnknown() {
operationCtx = logging.WithPackageContext(operationCtx, "create", plan.Name.ValueString(), plan.Namespace.ValueString())
}
if err != nil {
var optErr *optionalComponentsValidationError
if errors.As(err, &optErr) {
resp.Diagnostics.AddAttributeError(path.Root("optional_components"), "Invalid optional components", optErr.Error())
} else {
var deploymentErr *deploymentAttemptedError
if errors.As(err, &deploymentErr) {
r.recoverCreateState(operationCtx, plan, resp)
}
resp.Diagnostics.AddError(
"Error creating package",
lifecycleErrorDetail(timeoutCtx, "create", err),
)
}
return
}
refreshedPlan, found, refreshErr := r.refreshStateFromCluster(timeoutCtx, plan)
if refreshErr != nil {
r.recoverCreateState(operationCtx, plan, resp)
resp.Diagnostics.AddError(
"Error creating package",
lifecycleErrorDetail(timeoutCtx, "create", refreshErr),
)
return
}
if found {
preservePlannedPackageAttributes(&refreshedPlan, &plan)
plan = refreshedPlan
}
diags = resp.State.Set(timeoutCtx, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
operationCompleted = true
}
func (r *PackageResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
if req.State.Raw.IsNull() {
return
}
var data PackageResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
readTimeout, diags := data.Timeouts.Read(ctx, 5*time.Minute)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
timeoutCtx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
identity, err := r.lookupVerifiedDeployedPackage(timeoutCtx, data.ID.ValueString())
var absentErr *packageAbsentError
if errors.As(err, &absentErr) {
resp.Diagnostics.AddWarning(
"Deployed package not found",
"Could not find the deployed package identified by state - removing resource",
)
resp.State.RemoveResource(timeoutCtx)
return
}
if err != nil {
resp.Diagnostics.AddError(
"Deployed package identity could not be verified",
identityErrorDetail(err),
)
return
}
resp.Diagnostics.Append(populateStateFromDeployedPackage(&data, identity.Package)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(timeoutCtx, &data)...)
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
operationCtx := logging.WithPackageContext(ctx, "update", "", "")
operationCompleted := false
startedAt := time.Now()
defer func() {
if operationCompleted {
logging.PackageCompleted(operationCtx, time.Since(startedAt))
return
}
err := errors.New("package update did not complete")
if resp.Diagnostics.HasError() {
err = errors.New(resp.Diagnostics.Errors()[0].Detail())
}
logging.PackageFailed(operationCtx, "", err)
}()
var plan PackageResourceModel
diags := req.Plan.Get(operationCtx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
operationCtx = logging.WithPackageContext(operationCtx, "update", "", plan.Namespace.ValueString())
// Check if there are any components in the already existing plan that need to be removed
var oldPlan PackageResourceModel
diags = req.State.Get(operationCtx, &oldPlan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
if !oldPlan.Name.IsNull() && !oldPlan.Name.IsUnknown() {
operationCtx = logging.WithPackageContext(operationCtx, "update", oldPlan.Name.ValueString(), plan.Namespace.ValueString())
}
stateOnlyUpdate, err := isStateOnlyUpdate(req.Plan, req.State)
if err != nil {
resp.Diagnostics.AddError("Error comparing update changes", err.Error())
return
}
if stateOnlyUpdate {
oldPlan.Timeouts = plan.Timeouts
resp.Diagnostics.Append(resp.State.Set(operationCtx, oldPlan)...)
if !resp.Diagnostics.HasError() {
operationCompleted = true
}
return
}
updateTimeout, timeoutDiags := plan.Timeouts.Update(operationCtx, 30*time.Minute)
resp.Diagnostics.Append(timeoutDiags...)
if resp.Diagnostics.HasError() {
return
}
timeoutCtx, cancel := context.WithTimeout(operationCtx, updateTimeout)
defer cancel()
identity, err := r.lookupVerifiedDeployedPackage(timeoutCtx, oldPlan.ID.ValueString())
var absentErr *packageAbsentError
if errors.As(err, &absentErr) {
resp.Diagnostics.AddError("Deployed package not found", "The package recorded in state no longer exists. Update is blocked to avoid deploying a different package identity.")
return
}
if err != nil {
resp.Diagnostics.AddError("Deployed package identity could not be verified", identityErrorDetail(err))
return
}
if err := r.verifyCanonicalPackageName(timeoutCtx, plan, identity); err != nil {
resp.Diagnostics.AddAttributeError(path.Root("source"), canonicalIdentitySummary(err), canonicalIdentityDetail(err))
return
}
plan, err = r.deployAsNewOrUpdate(timeoutCtx, plan, oldPlan, identity)
if !plan.Name.IsNull() && !plan.Name.IsUnknown() {
operationCtx = logging.WithPackageContext(operationCtx, "update", plan.Name.ValueString(), plan.Namespace.ValueString())
}
if err != nil {
var optErr *optionalComponentsValidationError
var canonicalErr *canonicalNameMismatchError
if errors.As(err, &canonicalErr) {
resp.Diagnostics.AddAttributeError(path.Root("source"), canonicalIdentitySummary(err), canonicalIdentityDetail(err))
} else if errors.As(err, &optErr) {
resp.Diagnostics.AddAttributeError(path.Root("optional_components"), "Invalid optional components", optErr.Error())
} else {
resp.Diagnostics.AddError(
"Error updating package",
lifecycleErrorDetail(timeoutCtx, "update", err),
)
}
return
}
if resp.Diagnostics.HasError() {
return
}
refreshedPlan, found, refreshErr := r.refreshStateFromCluster(timeoutCtx, plan)
if refreshErr != nil {
resp.Diagnostics.AddError(
"Error updating package",
lifecycleErrorDetail(timeoutCtx, "update", refreshErr),
)
return
}
if found {
preservePlannedPackageAttributes(&refreshedPlan, &plan)
plan = refreshedPlan
}
diags = resp.State.Set(timeoutCtx, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
operationCompleted = true
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *PackageResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
operationCtx := logging.WithPackageContext(ctx, "delete", "", "")
operationCompleted := false
startedAt := time.Now()
defer func() {
if operationCompleted {
logging.PackageCompleted(operationCtx, time.Since(startedAt))
return
}
err := errors.New("package delete did not complete")
if resp.Diagnostics.HasError() {
err = errors.New(resp.Diagnostics.Errors()[0].Detail())
}
logging.PackageFailed(operationCtx, "", err)
}()
var data PackageResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(operationCtx, &data)...)
if resp.Diagnostics.HasError() {
return
}
operationCtx = logging.WithPackageContext(operationCtx, "delete", data.Name.ValueString(), data.Namespace.ValueString())
deleteTimeout, timeoutDiags := data.Timeouts.Delete(operationCtx, 30*time.Minute)
resp.Diagnostics.Append(timeoutDiags...)
if resp.Diagnostics.HasError() {
return
}
timeoutCtx, cancel := context.WithTimeout(operationCtx, deleteTimeout)
defer cancel()
lookupCtx, lookupCancel := withClusterTimeout(timeoutCtx)
defer lookupCancel()
identity, err := r.lookupVerifiedDeployedPackage(lookupCtx, data.ID.ValueString())
var absentErr *packageAbsentError
if errors.As(err, &absentErr) {
operationCompleted = true
return
}
if err != nil {
resp.Diagnostics.AddError("Deployed package identity could not be verified", identityErrorDetail(err))
return
}
clusterCtx, clusterCancel := withClusterTimeout(timeoutCtx)
defer clusterCancel()
c, err := r.cluster.NewWithWait(clusterCtx)
if err != nil {
resp.Diagnostics.AddError("Could not connect to cluster", lifecycleErrorDetail(timeoutCtx, "delete", err))
return
}
zarfTimeout, err := zarfOperationTimeout(timeoutCtx)
if err != nil {
resp.Diagnostics.AddError(
"Package removal could not start",
lifecycleErrorDetail(timeoutCtx, "delete", err),
)
return
}
removeOpt := zarfPackager.RemoveOptions{
NamespaceOverride: identity.Namespace,
Cluster: c,
Timeout: zarfTimeout,
}
if err := r.packager.Remove(timeoutCtx, zarfAPI.NewPackageDefinitionFromV1alpha1(identity.Package.Data), removeOpt); err != nil {
resp.Diagnostics.AddError(
"Error removing package",
lifecycleErrorDetail(timeoutCtx, "delete", err),
)
return
}
operationCompleted = true
}
// ModifyPlan handles plan modifications for computed attributes that depend on provider configuration
func (r *PackageResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
// Only modify if we have a plan (not a destroy operation)
if req.Plan.Raw.IsNull() {
return
}
var plan PackageResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
ctx = logging.WithPackageContext(ctx, "plan", plan.Name.ValueString(), plan.Namespace.ValueString())
var config PackageResourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
// If architecture is not explicitly set in config, set it to provider default
if config.Architecture.IsNull() && r.providerConfig != nil {
defaultArch := r.providerConfig.DefaultArchitecture
tflog.Debug(ctx, "ModifyPlan: Setting architecture to provider default", map[string]any{
"DefaultArchitecture": defaultArch,
"PlanArchitecture": plan.Architecture.ValueString(),
})
plan.Architecture = types.StringValue(defaultArch)
}
plan = normalizeOptionalComponentsPlan(config, plan)
resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
if !req.State.Raw.IsNull() {
stateOnlyUpdate, err := isStateOnlyUpdate(resp.Plan, req.State)
if err != nil {
resp.Diagnostics.AddError("Error comparing planned changes", err.Error())
return
}
if stateOnlyUpdate {