/
terraform_types.go
919 lines (763 loc) · 30.4 KB
/
terraform_types.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
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"bytes"
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/fluxcd/pkg/apis/meta"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta2"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
)
const (
CACertSecretName = "tf-controller.tls"
// RunnerTLSSecretName is the name of the secret containing a TLS cert that will be written to
// the namespace in which a terraform runner is created
RunnerTLSSecretName = "terraform-runner.tls"
RunnerLabel = "infra.contrib.fluxcd.io/terraform"
GitRepositoryIndexKey = ".metadata.gitRepository"
BucketIndexKey = ".metadata.bucket"
OCIRepositoryIndexKey = ".metadata.ociRepository"
BreakTheGlassAnnotation = "break-the-glass.tf-controller/requestedAt"
)
type ReadInputsFromSecretSpec struct {
// +required
Name string `json:"name"`
// +required
As string `json:"as"`
}
// WriteOutputsToSecretSpec defines where to store outputs, and which outputs to be stored.
type WriteOutputsToSecretSpec struct {
// Name is the name of the Secret to be written
// +required
Name string `json:"name"`
// Outputs contain the selected names of outputs to be written
// to the secret. Empty array means writing all outputs, which is default.
// +optional
Outputs []string `json:"outputs,omitempty"`
}
type Variable struct {
// Name is the name of the variable
// +required
Name string `json:"name"`
// +optional
Value *apiextensionsv1.JSON `json:"value,omitempty"`
// +optional
ValueFrom *corev1.EnvVarSource `json:"valueFrom,omitempty"`
}
// TerraformSpec defines the desired state of Terraform
type TerraformSpec struct {
// ApprovePlan specifies name of a plan wanted to approve.
// If its value is "auto", the controller will automatically approve every plan.
// +optional
ApprovePlan string `json:"approvePlan,omitempty"`
// Destroy produces a destroy plan. Applying the plan will destroy all resources.
// +optional
Destroy bool `json:"destroy,omitempty"`
// +optional
BackendConfig *BackendConfigSpec `json:"backendConfig,omitempty"`
// +optional
BackendConfigsFrom []BackendConfigsReference `json:"backendConfigsFrom,omitempty"`
// +optional
Cloud *CloudSpec `json:"cloud,omitempty"`
// +optional
// +kubebuilder:default:=default
Workspace string `json:"workspace,omitempty"`
// List of input variables to set for the Terraform program.
// +optional
Vars []Variable `json:"vars,omitempty"`
// List of references to a Secret or a ConfigMap to generate variables for
// Terraform resources based on its data, selectively by varsKey. Values of the later
// Secret / ConfigMap with the same keys will override those of the former.
// +optional
VarsFrom []VarsReference `json:"varsFrom,omitempty"`
// Values map to the Terraform variable "values", which is an object of arbitrary values.
// It is a convenient way to pass values to Terraform resources without having to define
// a variable for each value. To use this feature, your Terraform file must define the variable "values".
// +optional
Values *apiextensionsv1.JSON `json:"values,omitempty"`
// List of all configuration files to be created in initialization.
// +optional
FileMappings []FileMapping `json:"fileMappings,omitempty"`
// The interval at which to reconcile the Terraform.
// +required
Interval metav1.Duration `json:"interval"`
// The interval at which to retry a previously failed reconciliation.
// The default value is 15 when not specified.
// +optional
RetryInterval *metav1.Duration `json:"retryInterval,omitempty"`
// Path to the directory containing Terraform (.tf) files.
// Defaults to 'None', which translates to the root path of the SourceRef.
// +optional
Path string `json:"path,omitempty"`
// SourceRef is the reference of the source where the Terraform files are stored.
// +required
SourceRef CrossNamespaceSourceReference `json:"sourceRef"`
// Suspend is to tell the controller to suspend subsequent TF executions,
// it does not apply to already started executions. Defaults to false.
// +optional
Suspend bool `json:"suspend,omitempty"`
// Force instructs the controller to unconditionally
// re-plan and re-apply TF resources. Defaults to false.
// +kubebuilder:default:=false
// +optional
Force bool `json:"force,omitempty"`
// +optional
ReadInputsFromSecrets []ReadInputsFromSecretSpec `json:"readInputsFromSecrets,omitempty"`
// A list of target secrets for the outputs to be written as.
// +optional
WriteOutputsToSecret *WriteOutputsToSecretSpec `json:"writeOutputsToSecret,omitempty"`
// Disable automatic drift detection. Drift detection may be resource intensive in
// the context of a large cluster or complex Terraform statefile. Defaults to false.
// +kubebuilder:default:=false
// +optional
DisableDriftDetection bool `json:"disableDriftDetection,omitempty"`
// +optional
// PushSpec *PushSpec `json:"pushSpec,omitempty"`
// +optional
CliConfigSecretRef *corev1.SecretReference `json:"cliConfigSecretRef,omitempty"`
// List of health checks to be performed.
// +optional
HealthChecks []HealthCheck `json:"healthChecks,omitempty"`
// Create destroy plan and apply it to destroy terraform resources
// upon deletion of this object. Defaults to false.
// +kubebuilder:default:=false
// +optional
DestroyResourcesOnDeletion bool `json:"destroyResourcesOnDeletion,omitempty"`
// Name of a ServiceAccount for the runner Pod to provision Terraform resources.
// Default to tf-runner.
// +kubebuilder:default:=tf-runner
// +optional
ServiceAccountName string `json:"serviceAccountName,omitempty"`
// Clean the runner pod up after each reconciliation cycle
// +kubebuilder:default:=true
// +optional
AlwaysCleanupRunnerPod *bool `json:"alwaysCleanupRunnerPod,omitempty"`
// Configure the termination grace period for the runner pod. Use this parameter
// to allow the Terraform process to gracefully shutdown. Consider increasing for
// large, complex or slow-moving Terraform managed resources.
// +kubebuilder:default:=30
// +optional
RunnerTerminationGracePeriodSeconds *int64 `json:"runnerTerminationGracePeriodSeconds,omitempty"`
// RefreshBeforeApply forces refreshing of the state before the apply step.
// +kubebuilder:default:=false
// +optional
RefreshBeforeApply bool `json:"refreshBeforeApply,omitempty"`
// +optional
RunnerPodTemplate RunnerPodTemplate `json:"runnerPodTemplate,omitempty"`
// EnableInventory enables the object to store resource entries as the inventory for external use.
// +optional
EnableInventory bool `json:"enableInventory,omitempty"`
// +optional
TFState *TFStateSpec `json:"tfstate,omitempty"`
// Targets specify the resource, module or collection of resources to target.
// +optional
Targets []string `json:"targets,omitempty"`
// Parallelism limits the number of concurrent operations of Terraform apply step. Zero (0) means using the default value.
// +kubebuilder:default:=0
// +optional
Parallelism int32 `json:"parallelism,omitempty"`
// StoreReadablePlan enables storing the plan in a readable format.
// +kubebuilder:validation:Enum=none;json;human
// +kubebuilder:default:=none
// +optional
StoreReadablePlan string `json:"storeReadablePlan,omitempty"`
// +optional
Webhooks []Webhook `json:"webhooks,omitempty"`
// +optional
DependsOn []meta.NamespacedObjectReference `json:"dependsOn,omitempty"`
// Enterprise is the enterprise configuration placeholder.
// +optional
Enterprise *apiextensionsv1.JSON `json:"enterprise,omitempty"`
// BreakTheGlass specifies if the reconciliation should stop
// and allow interactive shell in case of emergency.
// +optional
BreakTheGlass bool `json:"breakTheGlass,omitempty"`
}
type CloudSpec struct {
// +required
Organization string `json:"organization"`
// +required
Workspaces *CloudWorkspacesSpec `json:"workspaces"`
// +optional
Hostname string `json:"hostname,omitempty"`
// +optional
Token string `json:"token,omitempty"`
}
type CloudWorkspacesSpec struct {
// +optional
Name string `json:"name"`
// +optional
Tags []string `json:"tags,omitempty"`
}
type Webhook struct {
// +kubebuilder:validation:Enum=post-planning
// +kubebuilder:default:=post-planning
// +required
Stage string `json:"stage"`
// +kubebuilder:default:=true
// +optional
Enabled *bool `json:"enabled,omitempty"`
// +required
URL string `json:"url"`
// +kubebuilder:value:Enum=SpecAndPlan,SpecOnly,PlanOnly
// +kubebuilder:default:=SpecAndPlan
// +optional
PayloadType string `json:"payloadType,omitempty"`
// +optional
ErrorMessageTemplate string `json:"errorMessageTemplate,omitempty"`
// +required
TestExpression string `json:"testExpression,omitempty"`
}
func (w Webhook) IsEnabled() bool {
return w.Enabled == nil || *w.Enabled
}
type PlanStatus struct {
// +optional
LastApplied string `json:"lastApplied,omitempty"`
// +optional
Pending string `json:"pending,omitempty"`
// +optional
IsDestroyPlan bool `json:"isDestroyPlan,omitempty"`
// +optional
IsDriftDetectionPlan bool `json:"isDriftDetectionPlan,omitempty"`
}
// TerraformStatus defines the observed state of Terraform
type TerraformStatus struct {
meta.ReconcileRequestStatus `json:",inline"`
// ObservedGeneration is the last reconciled generation.
// +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// +optional
Conditions []metav1.Condition `json:"conditions,omitempty"`
// The last successfully applied revision.
// The revision format for Git sources is <branch|tag>/<commit-sha>.
// +optional
LastAppliedRevision string `json:"lastAppliedRevision,omitempty"`
// LastAttemptedRevision is the revision of the last reconciliation attempt.
// +optional
LastAttemptedRevision string `json:"lastAttemptedRevision,omitempty"`
// LastPlannedRevision is the revision used by the last planning process.
// The result could be either no plan change or a new plan generated.
// +optional
LastPlannedRevision string `json:"lastPlannedRevision,omitempty"`
// LastDriftDetectedAt is the time when the last drift was detected
// +optional
LastDriftDetectedAt *metav1.Time `json:"lastDriftDetectedAt,omitempty"`
// LastAppliedByDriftDetectionAt is the time when the last drift was detected and
// terraform apply was performed as a result
// +optional
LastAppliedByDriftDetectionAt *metav1.Time `json:"lastAppliedByDriftDetectionAt,omitempty"`
// +optional
AvailableOutputs []string `json:"availableOutputs,omitempty"`
// +optional
Plan PlanStatus `json:"plan,omitempty"`
// Inventory contains the list of Terraform resource object references that have been successfully applied.
// +optional
Inventory *ResourceInventory `json:"inventory,omitempty"`
// +optional
Lock LockStatus `json:"lock,omitempty"`
}
// LockStatus defines the observed state of a Terraform State Lock
type LockStatus struct {
// +optional
LastApplied string `json:"lastApplied,omitempty"`
// Pending holds the identifier of the Lock Holder to be used with Force Unlock
// +optional
Pending string `json:"pending,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:resource:shortName=tf
// +kubebuilder:subresource:status
// +kubebuilder:deprecatedversion:warning="v1alpha1 Terraform is deprecated, upgrade to v1alpha2"
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].status",description=""
// +kubebuilder:printcolumn:name="Status",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].message",description=""
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description=""
// Terraform is the Schema for the terraforms API
type Terraform struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec TerraformSpec `json:"spec,omitempty"`
Status TerraformStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// TerraformList contains a list of Terraform
type TerraformList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Terraform `json:"items"`
}
// BackendConfigSpec is for specifying configuration for Terraform's Kubernetes backend
type BackendConfigSpec struct {
// Disable is to completely disable the backend configuration.
// +optional
Disable bool `json:"disable"`
// +optional
SecretSuffix string `json:"secretSuffix,omitempty"`
// +optional
InClusterConfig bool `json:"inClusterConfig,omitempty"`
// +optional
CustomConfiguration string `json:"customConfiguration,omitempty"`
// +optional
ConfigPath string `json:"configPath,omitempty"`
// +optional
Labels map[string]string `json:"labels,omitempty"`
}
// TFStateSpec allows the user to set ForceUnlock
type TFStateSpec struct {
// ForceUnlock a Terraform state if it has become locked for any reason. Defaults to `no`.
//
// This is an Enum and has the expected values of:
//
// - auto
// - yes
// - no
//
// WARNING: Only use `auto` in the cases where you are absolutely certain that
// no other system is using this state, you could otherwise end up in a bad place
// See https://www.terraform.io/language/state/locking#force-unlock for more
// information on the terraform state lock and force unlock.
//
// +optional
// +kubebuilder:validation:Enum:=yes;no;auto
// +kubebuilder:default:string=no
ForceUnlock ForceUnlockEnum `json:"forceUnlock,omitempty"`
// LockIdentifier holds the Identifier required by Terraform to unlock the state
// if it ever gets into a locked state.
//
// You'll need to put the Lock Identifier in here while setting ForceUnlock to
// either `yes` or `auto`.
//
// Leave this empty to do nothing, set this to the value of the `Lock Info: ID: [value]`,
// e.g. `f2ab685b-f84d-ac0b-a125-378a22877e8d`, to force unlock the state.
//
// +optional
LockIdentifier string `json:"lockIdentifier,omitempty"`
}
type ForceUnlockEnum string
const (
ForceUnlockEnumAuto ForceUnlockEnum = "auto"
ForceUnlockEnumYes ForceUnlockEnum = "yes"
ForceUnlockEnumNo ForceUnlockEnum = "no"
)
const (
TerraformKind = "Terraform"
TerraformFinalizer = "finalizers.tf.contrib.fluxcd.io"
MaxConditionMessageLength = 20000
DisabledValue = "disabled"
ApprovePlanAutoValue = "auto"
ApprovePlanDisableValue = "disable"
DefaultWorkspaceName = "default"
)
// The potential reasons that are associated with condition types
const (
ArtifactFailedReason = "ArtifactFailed"
DeletionBlockedByDependants = "DeletionBlockedByDependantsReason"
DependencyNotReadyReason = "DependencyNotReady"
DriftDetectedReason = "DriftDetected"
DriftDetectionFailedReason = "DriftDetectionFailed"
HealthChecksFailedReason = "HealthChecksFailed"
NoDriftReason = "NoDrift"
OutputsWritingFailedReason = "OutputsWritingFailed"
PlannedNoChangesReason = "TerraformPlannedNoChanges"
PlannedWithChangesReason = "TerraformPlannedWithChanges"
PostPlanningWebhookFailedReason = "PostPlanningWebhookFailed"
TFExecApplyFailedReason = "TFExecApplyFailed"
TFExecApplySucceedReason = "TerraformAppliedSucceed"
TFExecForceUnlockReason = "ForceUnlock"
TFExecInitFailedReason = "TFExecInitFailed"
TFExecLockHeldReason = "LockHeld"
TFExecNewFailedReason = "TFExecNewFailed"
TFExecOutputFailedReason = "TFExecOutputFailed"
TFExecPlanFailedReason = "TFExecPlanFailed"
TemplateGenerationFailedReason = "TemplateGenerationFailed"
VarsGenerationFailedReason = "VarsGenerationFailed"
WorkspaceSelectFailedReason = "SelectWorkspaceFailed"
)
// These constants are the Condition Types that the Terraform Resource works with
const (
ConditionTypeApply = "Apply"
ConditionTypeHealthCheck = "HealthCheck"
ConditionTypeOutput = "Output"
ConditionTypePlan = "Plan"
ConditionTypeStateLocked = "StateLocked"
)
// Webhook stages
const (
PostPlanningWebhook = "post-planning"
)
const (
TFDependencyOfPrefix = "tf.dependency.of."
)
// SetTerraformReadiness sets the ReadyCondition, ObservedGeneration, and LastAttemptedRevision, on the Terraform.
func SetTerraformReadiness(terraform *Terraform, status metav1.ConditionStatus, reason, message string, revision string) {
newCondition := metav1.Condition{
Type: meta.ReadyCondition,
Status: status,
Reason: reason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
terraform.Status.ObservedGeneration = terraform.Generation
terraform.Status.LastAttemptedRevision = revision
}
func TerraformApplying(terraform Terraform, revision string, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeApply,
Status: metav1.ConditionUnknown,
Reason: meta.ProgressingReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
if revision != "" {
(&terraform).Status.LastAttemptedRevision = revision
}
return terraform
}
func TerraformOutputsAvailable(terraform Terraform, availableOutputs []string, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeOutput,
Status: metav1.ConditionTrue,
Reason: "TerraformOutputsAvailable",
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
(&terraform).Status.AvailableOutputs = availableOutputs
return terraform
}
func TerraformOutputsWritten(terraform Terraform, revision string, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeOutput,
Status: metav1.ConditionTrue,
Reason: "TerraformOutputsWritten",
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
SetTerraformReadiness(&terraform, metav1.ConditionTrue, "TerraformOutputsWritten", message+": "+revision, revision)
return terraform
}
func TerraformApplied(terraform Terraform, revision string, message string, isDestroyApply bool, entries []ResourceRef) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeApply,
Status: metav1.ConditionTrue,
Reason: TFExecApplySucceedReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
if terraform.Status.Plan.IsDriftDetectionPlan {
(&terraform).Status.LastAppliedByDriftDetectionAt = &metav1.Time{Time: time.Now()}
}
(&terraform).Status.Plan = PlanStatus{
LastApplied: terraform.Status.Plan.Pending,
Pending: "",
IsDestroyPlan: isDestroyApply,
}
if revision != "" {
(&terraform).Status.LastAppliedRevision = revision
}
if len(entries) > 0 {
(&terraform).Status.Inventory = &ResourceInventory{Entries: entries}
}
SetTerraformReadiness(&terraform, metav1.ConditionUnknown, TFExecApplySucceedReason, message+": "+revision, revision)
return terraform
}
func GetPlanIdAndApproveMessage(revision string, message string) (string, string) {
planRev := strings.Replace(revision, "/", "-", 1)
planId := fmt.Sprintf("plan-%s", planRev)
shortPlanId := planId
parts := strings.SplitN(revision, "/", 2)
if len(parts) == 2 {
if len(parts[1]) >= 10 {
shortPlanId = fmt.Sprintf("plan-%s-%s", parts[0], parts[1][0:10])
}
}
approveMessage := fmt.Sprintf("%s: set approvePlan: \"%s\" to approve this plan.", message, shortPlanId)
return planId, approveMessage
}
func TerraformPostPlanningWebhookFailed(terraform Terraform, revision string, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypePlan,
Status: metav1.ConditionFalse,
Reason: PostPlanningWebhookFailedReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
(&terraform).Status.Plan = PlanStatus{
LastApplied: terraform.Status.Plan.LastApplied,
Pending: "",
IsDestroyPlan: terraform.Spec.Destroy,
}
if revision != "" {
(&terraform).Status.LastAttemptedRevision = revision
(&terraform).Status.LastPlannedRevision = revision
}
return terraform
}
func TerraformPlannedWithChanges(terraform Terraform, revision string, forceOrAutoApply bool, message string) Terraform {
planId, approveMessage := GetPlanIdAndApproveMessage(revision, message)
newCondition := metav1.Condition{
Type: ConditionTypePlan,
Status: metav1.ConditionTrue,
Reason: PlannedWithChangesReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
(&terraform).Status.Plan = PlanStatus{
LastApplied: terraform.Status.Plan.LastApplied,
Pending: planId,
IsDestroyPlan: terraform.Spec.Destroy,
IsDriftDetectionPlan: terraform.HasDrift(),
}
if revision != "" {
(&terraform).Status.LastAttemptedRevision = revision
(&terraform).Status.LastPlannedRevision = revision
}
if forceOrAutoApply {
SetTerraformReadiness(&terraform, metav1.ConditionUnknown, PlannedWithChangesReason, message, revision)
} else {
// this is the manual mode, where we don't want to apply the plan
SetTerraformReadiness(&terraform, metav1.ConditionUnknown, PlannedWithChangesReason, approveMessage, revision)
}
return terraform
}
func TerraformPlannedNoChanges(terraform Terraform, revision string, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypePlan,
Status: metav1.ConditionFalse,
Reason: PlannedNoChangesReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
(&terraform).Status.Plan = PlanStatus{
LastApplied: terraform.Status.Plan.LastApplied,
Pending: "",
IsDestroyPlan: terraform.Spec.Destroy,
}
if revision != "" {
(&terraform).Status.LastAttemptedRevision = revision
(&terraform).Status.LastPlannedRevision = revision
}
SetTerraformReadiness(&terraform, metav1.ConditionTrue, PlannedNoChangesReason, message+": "+revision, revision)
return terraform
}
// TerraformProgressing resets the conditions of the given Terraform to a single
// ReadyCondition with status ConditionUnknown.
func TerraformProgressing(terraform Terraform, message string) Terraform {
newCondition := metav1.Condition{
Type: meta.ReadyCondition,
Status: metav1.ConditionUnknown,
Reason: meta.ProgressingReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
return terraform
}
// TerraformNotReady registers a failed apply attempt of the given Terraform.
func TerraformNotReady(terraform Terraform, revision, reason, message string) Terraform {
SetTerraformReadiness(&terraform, metav1.ConditionFalse, reason, trimString(message, MaxConditionMessageLength), revision)
if revision != "" {
terraform.Status.LastAttemptedRevision = revision
}
return terraform
}
func TerraformAppliedFailResetPlanAndNotReady(terraform Terraform, revision, reason, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeApply,
Status: metav1.ConditionFalse,
Reason: "TerraformAppliedFail",
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
terraform = TerraformNotReady(terraform, revision, reason, message)
terraform.Status.Plan.Pending = ""
return terraform
}
func TerraformDriftDetected(terraform Terraform, revision, reason, message string) Terraform {
(&terraform).Status.LastDriftDetectedAt = &metav1.Time{Time: time.Now()}
SetTerraformReadiness(&terraform, metav1.ConditionFalse, reason, trimString(message, MaxConditionMessageLength), revision)
return terraform
}
func TerraformNoDrift(terraform Terraform, revision, reason, message string) Terraform {
SetTerraformReadiness(&terraform, metav1.ConditionTrue, reason, message+": "+revision, revision)
return terraform
}
func TerraformHealthCheckFailed(terraform Terraform, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeHealthCheck,
Status: metav1.ConditionFalse,
Reason: HealthChecksFailedReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
return terraform
}
func TerraformHealthCheckSucceeded(terraform Terraform, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeHealthCheck,
Status: metav1.ConditionTrue,
Reason: "HealthChecksSucceed",
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
return terraform
}
// TerraformForceUnlock will set a new condition on the Terraform resource indicating
// that we are attempting to force unlock it.
func TerraformForceUnlock(terraform Terraform, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeStateLocked,
Status: metav1.ConditionFalse,
Reason: TFExecForceUnlockReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
if terraform.Status.Lock.Pending != "" && terraform.Status.Lock.LastApplied != terraform.Status.Lock.Pending {
terraform.Status.Lock.LastApplied = terraform.Status.Lock.Pending
}
terraform.Status.Lock.Pending = ""
return terraform
}
// TerraformStateLocked will set a new condition on the Terraform resource indicating
// that the resource has been locked.
func TerraformStateLocked(terraform Terraform, lockID, message string) Terraform {
newCondition := metav1.Condition{
Type: ConditionTypeStateLocked,
Status: metav1.ConditionTrue,
Reason: TFExecLockHeldReason,
Message: trimString(message, MaxConditionMessageLength),
}
apimeta.SetStatusCondition(terraform.GetStatusConditions(), newCondition)
SetTerraformReadiness(&terraform, metav1.ConditionFalse, newCondition.Reason, newCondition.Message, "")
if terraform.Status.Lock.Pending != "" && terraform.Status.Lock.LastApplied != terraform.Status.Lock.Pending {
terraform.Status.Lock.LastApplied = terraform.Status.Lock.Pending
}
terraform.Status.Lock.Pending = lockID
return terraform
}
// HasDrift returns true if drift has been detected since the last successful apply
func (in Terraform) HasDrift() bool {
for _, condition := range in.Status.Conditions {
if condition.Type == ConditionTypeApply &&
condition.Status == metav1.ConditionTrue &&
in.Status.LastDriftDetectedAt != nil &&
(*in.Status.LastDriftDetectedAt).After(condition.LastTransitionTime.Time) {
return true
}
}
return false
}
// GetDependsOn returns the list of dependencies, namespace scoped.
func (in Terraform) GetDependsOn() []meta.NamespacedObjectReference {
return in.Spec.DependsOn
}
// GetRetryInterval returns the retry interval
func (in Terraform) GetRetryInterval() time.Duration {
if in.Spec.RetryInterval != nil {
return in.Spec.RetryInterval.Duration
}
// The default retry interval is 15 seconds.
return 15 * time.Second
}
// GetStatusConditions returns a pointer to the Status.Conditions slice.
func (in *Terraform) GetStatusConditions() *[]metav1.Condition {
return &in.Status.Conditions
}
func (in *Terraform) WorkspaceName() string {
if in.Spec.Workspace != "" {
return in.Spec.Workspace
}
return DefaultWorkspaceName
}
func (in Terraform) ToBytes(scheme *runtime.Scheme) ([]byte, error) {
return runtime.Encode(
serializer.NewCodecFactory(scheme).LegacyCodec(
corev1.SchemeGroupVersion,
GroupVersion,
sourcev1.GroupVersion,
), &in)
}
func (in *Terraform) FromBytes(b []byte, scheme *runtime.Scheme) error {
return runtime.DecodeInto(
serializer.NewCodecFactory(scheme).LegacyCodec(
corev1.SchemeGroupVersion,
GroupVersion,
sourcev1.GroupVersion,
), b, in)
}
func (in *Terraform) GetRunnerHostname(ip string) string {
prefix := strings.ReplaceAll(ip, ".", "-")
return fmt.Sprintf("%s.%s.pod.cluster.local", prefix, in.Namespace)
}
func (in *TerraformSpec) GetAlwaysCleanupRunnerPod() bool {
if in.AlwaysCleanupRunnerPod == nil {
return true
}
return *in.AlwaysCleanupRunnerPod
}
func (c *CloudSpec) IsValid() bool {
if c.Organization == "" {
return false
}
if c.Workspaces == nil {
return false
}
if c.Workspaces.Name == "" && c.Workspaces.Tags == nil {
return false
}
return true
}
func (c *CloudSpec) ToHCL() string {
var buf bytes.Buffer
buf.WriteString("terraform {\n")
buf.WriteString(" cloud {\n")
buf.WriteString(fmt.Sprintf(" organization = %q\n", c.Organization))
buf.WriteString(fmt.Sprintf(" workspaces {\n"))
if c.Workspaces.Name != "" {
buf.WriteString(fmt.Sprintf(" name = %q\n", c.Workspaces.Name))
}
if len(c.Workspaces.Tags) > 0 {
tags := "[\"" + strings.Join(c.Workspaces.Tags, "\", \"") + "\"]"
buf.WriteString(fmt.Sprintf(" tags = %s\n", tags))
}
buf.WriteString(fmt.Sprintf(" }\n"))
buf.WriteString(fmt.Sprintf(" hostname = %q\n", c.Hostname))
buf.WriteString(fmt.Sprintf(" token = %q\n", c.Token))
buf.WriteString(fmt.Sprintf(" }\n"))
buf.WriteString(fmt.Sprintf("}\n"))
return buf.String()
}
// trimString takes in a string and an integer limit, and returns a new string with a maximum length of limit characters.
// If the length of the input string is greater than limit, the returned string will be truncated to limit characters
// and "..." will be appended to the end.
// If limit is less than 3, it will be set to 3 before continuing.
// It correctly handles unicode characters by using utf8.RuneCountInString to get the number of runes in the string.
func trimString(str string, limit int) string {
if limit < 3 {
limit = 3
}
if utf8.RuneCountInString(str) <= limit {
return str
}
runes := []rune(str)
return string(runes[:limit]) + "..."
}
func init() {
SchemeBuilder.Register(&Terraform{}, &TerraformList{})
}