-
Notifications
You must be signed in to change notification settings - Fork 130
/
terraform_controller.go
1891 lines (1648 loc) · 58.3 KB
/
terraform_controller.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
/*
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 controllers
import (
"bytes"
"context"
"crypto/sha1"
"crypto/sha256"
"encoding/json"
"fmt"
"html/template"
"io"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"sort"
"strings"
"time"
"github.com/fluxcd/pkg/apis/meta"
"github.com/fluxcd/pkg/runtime/events"
"github.com/fluxcd/pkg/runtime/metrics"
"github.com/fluxcd/pkg/runtime/predicates"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
"github.com/go-logr/logr"
"github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/terraform-exec/tfexec"
infrav1 "github.com/weaveworks/tf-controller/api/v1alpha1"
"github.com/weaveworks/tf-controller/mtls"
"github.com/weaveworks/tf-controller/runner"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
kuberecorder "k8s.io/client-go/tools/record"
"k8s.io/client-go/tools/reference"
"sigs.k8s.io/cli-utils/pkg/kstatus/polling"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
// TerraformReconciler reconciles a Terraform object
type TerraformReconciler struct {
client.Client
httpClient *retryablehttp.Client
EventRecorder kuberecorder.EventRecorder
ExternalEventRecorder *events.Recorder
MetricsRecorder *metrics.Recorder
StatusPoller *polling.StatusPoller
Scheme *runtime.Scheme
CertRotator *mtls.CertRotator
RunnerGRPCPort int
}
//+kubebuilder:rbac:groups=infra.contrib.fluxcd.io,resources=terraforms,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=infra.contrib.fluxcd.io,resources=terraforms/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=infra.contrib.fluxcd.io,resources=terraforms/finalizers,verbs=get;create;update;patch;delete
//+kubebuilder:rbac:groups=source.toolkit.fluxcd.io,resources=buckets;gitrepositories,verbs=get;list;watch
//+kubebuilder:rbac:groups=source.toolkit.fluxcd.io,resources=buckets/status;gitrepositories/status,verbs=get
//+kubebuilder:rbac:groups="",resources=configmaps;secrets;serviceaccounts,verbs=get;list;watch
//+kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Terraform object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *TerraformReconciler) Reconcile(ctx context.Context, req ctrl.Request) (retResult ctrl.Result, retErr error) {
// TODO need to think about many controller instances are sharing the same secret
// should be blocked if cert is not ready yet
if r.CertRotator.IsCertReady(ctx) == false {
return ctrl.Result{Requeue: true}, fmt.Errorf("server cert not ready yet")
}
log := ctrl.LoggerFrom(ctx)
reconcileStart := time.Now()
var terraform infrav1.Terraform
if err := r.Get(ctx, req.NamespacedName, &terraform); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Record suspended status metric
defer r.recordSuspensionMetric(ctx, terraform)
// Add our finalizer if it does not exist
if !controllerutil.ContainsFinalizer(&terraform, infrav1.TerraformFinalizer) {
controllerutil.AddFinalizer(&terraform, infrav1.TerraformFinalizer)
if err := r.Update(ctx, &terraform); err != nil {
log.Error(err, "unable to register finalizer")
return ctrl.Result{}, err
}
}
// TODO create Runner Pod
// TODO wait for the Runner Pod to start
runnerClient, closeConn, err := r.LookupOrCreateRunner(ctx, terraform)
if err != nil {
log.Error(err, "unable to lookup or create runner")
if closeConn != nil {
if err := closeConn(); err != nil {
log.Error(err, "unable to close connection")
}
}
return ctrl.Result{}, err
}
log.Info("runner is running")
defer func(ctx context.Context, cli client.Client, terraform infrav1.Terraform) {
if closeConn != nil {
if err := closeConn(); err != nil {
log.Error(err, "unable to close connection")
retErr = err
}
}
if os.Getenv("INSECURE_LOCAL_RUNNER") == "1" {
// nothing to delete
return
}
if terraform.Spec.AlwaysCleanupRunnerPod == true {
podKey := types.NamespacedName{Namespace: terraform.Namespace, Name: fmt.Sprintf("%s-tf-runner", terraform.Name)}
var pod corev1.Pod
if err := cli.Get(ctx, podKey, &pod); err != nil {
if !apierrors.IsNotFound(err) {
log.Error(err, "unable to get pod for cleaning up")
retErr = err
}
return
}
if err := cli.Delete(ctx, &pod); err != nil {
log.Error(err, "unable to delete pod")
retErr = err
return
}
}
}(ctx, r.Client, terraform)
// resolve source reference
sourceObj, err := r.getSource(ctx, terraform)
// Examine if the object is under deletion
if !terraform.ObjectMeta.DeletionTimestamp.IsZero() {
return r.finalize(ctx, terraform, runnerClient, sourceObj)
}
// Return early if the Terraform is suspended.
if terraform.Spec.Suspend {
log.Info("Reconciliation is suspended for this object")
return ctrl.Result{}, nil
}
if err != nil {
if apierrors.IsNotFound(err) {
msg := fmt.Sprintf("Source '%s' not found", terraform.Spec.SourceRef.String())
terraform = infrav1.TerraformNotReady(terraform, "", infrav1.ArtifactFailedReason, msg)
if err := r.patchStatus(ctx, req.NamespacedName, terraform.Status); err != nil {
log.Error(err, "unable to update status for source not found")
return ctrl.Result{Requeue: true}, err
}
r.recordReadinessMetric(ctx, terraform)
log.Info(msg)
// do not requeue immediately, when the source is created the watcher should trigger a reconciliation
return ctrl.Result{RequeueAfter: terraform.GetRetryInterval()}, nil
} else {
// retry on transient errors
return ctrl.Result{Requeue: true}, err
}
}
if sourceObj.GetArtifact() == nil {
msg := "Source is not ready, artifact not found"
terraform = infrav1.TerraformNotReady(terraform, "", infrav1.ArtifactFailedReason, msg)
if err := r.patchStatus(ctx, req.NamespacedName, terraform.Status); err != nil {
log.Error(err, "unable to update status for artifact not found")
return ctrl.Result{Requeue: true}, err
}
r.recordReadinessMetric(ctx, terraform)
log.Info(msg)
// do not requeue immediately, when the artifact is created the watcher should trigger a reconciliation
return ctrl.Result{RequeueAfter: terraform.GetRetryInterval()}, nil
}
// If revision is changed, and there's no intend to apply,
// we should clear the Pending Plan to trigger re-plan
if sourceObj.GetArtifact().Revision != terraform.Status.LastAttemptedRevision && !r.shouldApply(terraform) {
terraform.Status.Plan.Pending = ""
if err := r.Status().Update(ctx, &terraform); err != nil {
log.Error(err, "unable to update status to clear pending plan (revision != last attempted)")
return ctrl.Result{Requeue: true}, err
}
}
// Return early if it's manually mode and pending
if terraform.Status.Plan.Pending != "" && !r.forceOrAutoApply(terraform) && !r.shouldApply(terraform) {
log.Info("reconciliation is stopped to wait for a manual approve")
return ctrl.Result{}, nil
}
// reconcile Terraform by applying the latest revision
reconciledTerraform, reconcileErr := r.reconcile(ctx, runnerClient, *terraform.DeepCopy(), sourceObj)
if err := r.patchStatus(ctx, req.NamespacedName, reconciledTerraform.Status); err != nil {
log.Error(err, "unable to update status after reconciliation")
return ctrl.Result{Requeue: true}, err
}
r.recordReadinessMetric(ctx, reconciledTerraform)
if reconcileErr != nil && reconcileErr.Error() == infrav1.DriftDetectedReason {
log.Error(reconcileErr, fmt.Sprintf("Drift detected after %s, next try in %s",
time.Since(reconcileStart).String(),
terraform.GetRetryInterval().String()),
"revision",
sourceObj.GetArtifact().Revision)
r.fireEvent(ctx, reconciledTerraform, sourceObj.GetArtifact().Revision, events.EventSeverityError, reconcileErr.Error(), nil)
return ctrl.Result{RequeueAfter: terraform.GetRetryInterval()}, nil
} else if reconcileErr != nil {
// broadcast the reconciliation failure and requeue at the specified retry interval
log.Error(reconcileErr, fmt.Sprintf("Reconciliation failed after %s, next try in %s",
time.Since(reconcileStart).String(),
terraform.GetRetryInterval().String()),
"revision",
sourceObj.GetArtifact().Revision)
r.fireEvent(ctx, reconciledTerraform, sourceObj.GetArtifact().Revision, events.EventSeverityError, reconcileErr.Error(), nil)
return ctrl.Result{RequeueAfter: terraform.GetRetryInterval()}, nil
}
if reconciledTerraform.Status.Plan.Pending != "" && !r.forceOrAutoApply(reconciledTerraform) {
log.Info("Reconciliation is stopped to wait for a manual approve")
return ctrl.Result{}, nil
}
// next reconcile is .Spec.Interval in the future
return ctrl.Result{RequeueAfter: terraform.Spec.Interval.Duration}, nil
}
func (r *TerraformReconciler) shouldDetectDrift(terraform infrav1.Terraform, revision string) bool {
// Please do not optimize this logic, as we'd like others to easily understand the logics behind this behaviour.
// return false when drift detection is disabled
if terraform.Spec.DisableDriftDetection == true {
return false
}
// not support when Destroy == true
if terraform.Spec.Destroy == true {
return false
}
// new object
if terraform.Status.LastAppliedRevision == "" &&
terraform.Status.LastPlannedRevision == "" &&
terraform.Status.LastAttemptedRevision == "" {
return false
}
// thing worked normally, no change pending
// then, we do drift detection
if terraform.Status.LastAttemptedRevision == terraform.Status.LastAppliedRevision &&
terraform.Status.LastAttemptedRevision == terraform.Status.LastPlannedRevision &&
terraform.Status.LastAttemptedRevision == revision &&
terraform.Status.Plan.Pending == "" {
return true
}
// last time source changed with non-TF file, so we planned but no changes
// this time, it needs drift detection
if terraform.Status.LastAttemptedRevision == terraform.Status.LastPlannedRevision &&
terraform.Status.LastAttemptedRevision == revision &&
terraform.Status.Plan.Pending == "" {
return true
}
return false
}
func (r *TerraformReconciler) forceOrAutoApply(terraform infrav1.Terraform) bool {
return terraform.Spec.Force || terraform.Spec.ApprovePlan == infrav1.ApprovePlanAutoValue
}
func (r *TerraformReconciler) shouldPlan(terraform infrav1.Terraform) bool {
// Please do not optimize this logic, as we'd like others to easily understand the logics behind this behaviour.
if terraform.Spec.Force {
return true
}
if terraform.Status.Plan.Pending == "" {
return true
} else if terraform.Status.Plan.Pending != "" {
return false
}
return false
}
func (r *TerraformReconciler) shouldApply(terraform infrav1.Terraform) bool {
// Please do not optimize this logic, as we'd like others to easily understand the logics behind this behaviour.
if terraform.Spec.Force {
return true
}
if terraform.Spec.ApprovePlan == "" {
return false
} else if terraform.Spec.ApprovePlan == infrav1.ApprovePlanAutoValue && terraform.Status.Plan.Pending != "" {
return true
} else if terraform.Spec.ApprovePlan == terraform.Status.Plan.Pending {
return true
} else if strings.HasPrefix(terraform.Status.Plan.Pending, terraform.Spec.ApprovePlan) {
return true
}
return false
}
func (r *TerraformReconciler) shouldWriteOutputs(terraform infrav1.Terraform, outputs map[string]tfexec.OutputMeta) bool {
if terraform.Spec.WriteOutputsToSecret != nil && len(outputs) > 0 {
return true
}
return false
}
func (r *TerraformReconciler) shouldDoHealthChecks(terraform infrav1.Terraform) bool {
if terraform.Spec.HealthChecks == nil || len(terraform.Spec.HealthChecks) < 1 {
return false
}
var applyCondition metav1.Condition
var hcCondition metav1.Condition
for _, c := range terraform.Status.Conditions {
if c.Type == "Apply" {
applyCondition = c
} else if c.Type == "HealthCheck" {
hcCondition = c
}
}
// health checks were previously performed but failed
// do health check again
if hcCondition.Reason == infrav1.HealthChecksFailedReason {
return true
}
// terraform was applied and no health check performed yet
// do health check
if applyCondition.Reason == infrav1.TFExecApplySucceedReason &&
hcCondition.Reason == "" {
return true
}
return false
}
type LocalPrintfer struct {
logger logr.Logger
}
func (l LocalPrintfer) Printf(format string, v ...interface{}) {
l.logger.Info(fmt.Sprintf(format, v...))
}
func (r *TerraformReconciler) reconcile(ctx context.Context, runnerClient runner.RunnerClient, terraform infrav1.Terraform, sourceObj sourcev1.Source) (retTerraform infrav1.Terraform, retErr error) {
log := ctrl.LoggerFrom(ctx)
revision := sourceObj.GetArtifact().Revision
objectKey := types.NamespacedName{Namespace: terraform.Namespace, Name: terraform.Name}
var (
tfInstance string
tmpDir string
err error
)
terraform, tfInstance, tmpDir, err = r.setupTerraform(ctx, runnerClient, terraform, sourceObj, revision, objectKey)
defer func() {
cleanupDirReply, err := runnerClient.CleanupDir(ctx, &runner.CleanupDirRequest{TmpDir: tmpDir})
if err != nil {
log.Error(err, "clean up error")
retErr = err
return
}
if cleanupDirReply != nil {
log.Info(fmt.Sprintf("clean up dir: %s", cleanupDirReply.Message))
}
}()
if err != nil {
return terraform, err
}
if r.shouldDetectDrift(terraform, revision) {
var driftDetectionErr error // declared here to avoid shadowing on terraform variable
terraform, driftDetectionErr = r.detectDrift(ctx, terraform, tfInstance, runnerClient, revision)
// immediately return if no drift - reconciliation will retry normally
if driftDetectionErr == nil {
return terraform, nil
}
// immediately return if err is not about drift
if driftDetectionErr.Error() != infrav1.DriftDetectedReason {
return terraform, driftDetectionErr
}
// immediately return if drift is detected but it's not "force" or "auto"
if driftDetectionErr.Error() == infrav1.DriftDetectedReason && !r.forceOrAutoApply(terraform) {
return terraform, driftDetectionErr
}
// ok, patch and continue
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status after drift detection")
return terraform, err
}
}
// return early if we're in drift-detection-only mode
if terraform.Spec.ApprovePlan == infrav1.ApprovePlanDisableValue {
log.Info("approve plan disabled")
return terraform, nil
}
if r.shouldPlan(terraform) {
terraform, err = r.plan(ctx, terraform, tfInstance, runnerClient, revision)
if err != nil {
return terraform, err
}
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status after planing")
return terraform, err
}
}
outputs := map[string]tfexec.OutputMeta{}
if r.shouldApply(terraform) {
terraform, err = r.apply(ctx, terraform, tfInstance, runnerClient, revision, &outputs)
if err != nil {
return terraform, err
}
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status after applying")
return terraform, err
}
} else {
log.Info("should apply == false")
}
if r.shouldWriteOutputs(terraform, outputs) {
terraform, err = r.writeOutput(ctx, terraform, runnerClient, outputs, revision)
if err != nil {
return terraform, err
}
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status after writing outputs")
return terraform, err
}
}
if r.shouldDoHealthChecks(terraform) {
terraform, err = r.doHealthChecks(ctx, terraform, runnerClient)
if err != nil {
return terraform, err
}
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status after doing health checks")
return terraform, err
}
}
return terraform, nil
}
func (r *TerraformReconciler) setupTerraform(ctx context.Context, runnerClient runner.RunnerClient, terraform infrav1.Terraform, sourceObj sourcev1.Source, revision string, objectKey types.NamespacedName) (infrav1.Terraform, string, string, error) {
log := ctrl.LoggerFrom(ctx)
tfInstance := "0"
tmpDir := ""
terraform = infrav1.TerraformProgressing(terraform, "Initializing")
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status before Terraform initialization")
return terraform, tfInstance, tmpDir, err
}
// download artifact and extract files
buf, err := r.downloadAsBytes(sourceObj.GetArtifact())
if err != nil {
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.ArtifactFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
uploadAndExtractReply, err := runnerClient.UploadAndExtract(ctx, &runner.UploadAndExtractRequest{
Namespace: terraform.Namespace,
Name: terraform.Name,
TarGz: buf.Bytes(),
Path: terraform.Spec.Path,
})
if err != nil {
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.ArtifactFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
workingDir := uploadAndExtractReply.WorkingDir
tmpDir = uploadAndExtractReply.TmpDir
var backendConfig string
DisableTFK8SBackend := os.Getenv("DISABLE_TF_K8S_BACKEND") == "1"
if terraform.Spec.BackendConfig != nil {
backendConfig = fmt.Sprintf(`
terraform {
backend "kubernetes" {
secret_suffix = "%s"
in_cluster_config = %v
config_path = "%s"
namespace = "%s"
}
}
`,
terraform.Spec.BackendConfig.SecretSuffix,
terraform.Spec.BackendConfig.InClusterConfig,
terraform.Spec.BackendConfig.ConfigPath,
terraform.Namespace)
} else if DisableTFK8SBackend && terraform.Spec.BackendConfig == nil {
backendConfig = `
terraform {
backend "local" { }
}`
} else if terraform.Spec.BackendConfig == nil {
// TODO must be tested in cluster only
backendConfig = fmt.Sprintf(`
terraform {
backend "kubernetes" {
secret_suffix = "%s"
in_cluster_config = true
namespace = "%s"
}
}
`, terraform.Name, terraform.Namespace)
}
if r.backendCompletelyDisable(terraform) {
log.Info("BackendConfig is completely disabled")
} else {
writeBackendConfigReply, err := runnerClient.WriteBackendConfig(ctx,
&runner.WriteBackendConfigRequest{
DirPath: workingDir,
BackendConfig: []byte(backendConfig),
})
log.Info(fmt.Sprintf("write backend config: %s", writeBackendConfigReply.Message))
if err != nil {
return terraform, tfInstance, tmpDir, err
}
}
var tfrcFilepath string
if terraform.Spec.CliConfigSecretRef != nil {
cliConfigSecretRef := *(terraform.Spec.CliConfigSecretRef.DeepCopy())
if cliConfigSecretRef.Namespace == "" {
cliConfigSecretRef.Namespace = terraform.Namespace
}
processCliConfigReply, err := runnerClient.ProcessCliConfig(ctx, &runner.ProcessCliConfigRequest{
DirPath: workingDir,
Namespace: cliConfigSecretRef.Namespace,
Name: cliConfigSecretRef.Name,
})
if err != nil {
err = fmt.Errorf("cannot process cli config: %s", err.Error())
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecNewFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
tfrcFilepath = processCliConfigReply.FilePath
}
lookPathReply, err := runnerClient.LookPath(ctx,
&runner.LookPathRequest{
File: "terraform",
})
execPath := lookPathReply.ExecPath
if err != nil {
err = fmt.Errorf("cannot find Terraform binary: %s in %s", err, os.Getenv("PATH"))
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecNewFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
newTerraformReply, err := runnerClient.NewTerraform(ctx,
&runner.NewTerraformRequest{
// TarGz: tarGzBytes,
WorkingDir: workingDir,
ExecPath: execPath,
})
if err != nil {
err = fmt.Errorf("error running NewTerraform: %s", err)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecNewFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
tfInstance = newTerraformReply.Id
envs := map[string]string{}
disableTestLogging := os.Getenv("DISABLE_TF_LOGS") == "1"
if !disableTestLogging {
envs["DISABLE_TF_LOGS"] = "1"
}
if tfrcFilepath != "" {
envs["TF_CLI_CONFIG_FILE"] = tfrcFilepath
if setEnvReply, err := runnerClient.SetEnv(ctx,
&runner.SetEnvRequest{
TfInstance: tfInstance,
Envs: envs,
}); err != nil {
err = fmt.Errorf("error setting env for Terraform: %s %s", err, setEnvReply.Message)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecInitFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
}
log.Info("new terraform", "workingDir", workingDir)
// TODO we currently use a fork version of TFExec to workaround the forceCopy bug
// https://github.com/hashicorp/terraform-exec/issues/262
/*
initOpts := []tfexec.InitOption{tfexec.Upgrade(true), tfexec.ForceCopy(true)}
if r.backendCompletelyDisable(terraform) {
initOpts = append(initOpts, tfexec.ForceCopy(false))
}
*/
initRequest := &runner.InitRequest{
TfInstance: tfInstance,
Upgrade: true,
ForceCopy: true,
}
if r.backendCompletelyDisable(terraform) {
initRequest.ForceCopy = false
}
initReply, err := runnerClient.Init(ctx, initRequest)
if err != nil {
err = fmt.Errorf("error running Init: %s", err)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecInitFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
log.Info(fmt.Sprintf("init reply: %s", initReply.Message))
log.Info("tfexec initialized terraform")
terraformBytes, err := terraform.ToBytes(r.Scheme)
if err != nil {
// transient error?
return terraform, tfInstance, tmpDir, err
}
generateVarsForTFReply, err := runnerClient.GenerateVarsForTF(ctx, &runner.GenerateVarsForTFRequest{
Terraform: terraformBytes,
WorkingDir: workingDir,
})
if err != nil {
// transient error?
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.VarsGenerationFailedReason,
err.Error(),
), tfInstance, tmpDir, err
}
log.Info(fmt.Sprintf("generate vars from tf: %s", generateVarsForTFReply.Message))
log.Info("generated var files from spec")
return terraform, tfInstance, tmpDir, nil
}
func (r *TerraformReconciler) detectDrift(ctx context.Context, terraform infrav1.Terraform, tfInstance string, runnerClient runner.RunnerClient, revision string) (infrav1.Terraform, error) {
log := ctrl.LoggerFrom(ctx)
log.Info("calling detectDrift ...")
const (
driftFilename = "tfdrift"
)
planRequest := &runner.PlanRequest{
TfInstance: tfInstance,
Out: driftFilename,
Refresh: true,
}
if r.backendCompletelyDisable(terraform) {
planRequest.Out = ""
planRequest.Refresh = true
}
planReply, err := runnerClient.Plan(ctx, planRequest)
if err != nil {
err = fmt.Errorf("error running Plan: %s", err)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.DriftDetectionFailedReason,
err.Error(),
), err
}
drifted := planReply.Drifted
log.Info(fmt.Sprintf("plan for drift: %s found drift: %v", planReply.Message, planReply.Drifted))
if drifted {
var rawOutput string
if r.backendCompletelyDisable(terraform) {
rawOutput = "not available"
} else {
showPlanFileRawReply, err := runnerClient.ShowPlanFileRaw(ctx, &runner.ShowPlanFileRawRequest{
TfInstance: tfInstance,
Filename: driftFilename,
})
if err != nil {
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.DriftDetectionFailedReason,
err.Error(),
), err
}
rawOutput = showPlanFileRawReply.RawOutput
log.Info(fmt.Sprintf("show plan: %s", showPlanFileRawReply.RawOutput))
}
// If drift detected & we use the auto mode, then we continue
terraform = infrav1.TerraformDriftDetected(terraform, revision, infrav1.DriftDetectedReason, rawOutput)
return terraform, fmt.Errorf(infrav1.DriftDetectedReason)
}
terraform = infrav1.TerraformNoDrift(terraform, revision, infrav1.NoDriftReason, "No drift")
return terraform, nil
}
func (r *TerraformReconciler) plan(ctx context.Context, terraform infrav1.Terraform, tfInstance string, runnerClient runner.RunnerClient, revision string) (infrav1.Terraform, error) {
log := ctrl.LoggerFrom(ctx)
log.Info("calling plan ...")
objectKey := types.NamespacedName{Namespace: terraform.Namespace, Name: terraform.Name}
terraform = infrav1.TerraformProgressing(terraform, "Terraform Planning")
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status before Terraform planning")
return terraform, err
}
const tfplanFilename = "tfplan"
planRequest := &runner.PlanRequest{
TfInstance: tfInstance,
Out: tfplanFilename,
Refresh: true, // be careful, refresh requires to be true by default
}
if r.backendCompletelyDisable(terraform) {
planRequest.Out = ""
}
// check if destroy is set to true or
// the object is being deleted and DestroyResourcesOnDeletion is set to true
if terraform.Spec.Destroy ||
!terraform.ObjectMeta.DeletionTimestamp.IsZero() &&
terraform.Spec.DestroyResourcesOnDeletion {
log.Info("plan to destroy")
planRequest.Destroy = true
}
planReply, err := runnerClient.Plan(ctx, planRequest)
if err != nil {
err = fmt.Errorf("error running Plan: %s", err)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecPlanFailedReason,
err.Error(),
), err
}
drifted := planReply.Drifted
log.Info(fmt.Sprintf("plan: %s, found drift: %v", planReply.Message, drifted))
saveTFPlanReply, err := runnerClient.SaveTFPlan(ctx, &runner.SaveTFPlanRequest{
TfInstance: tfInstance,
BackendCompletelyDisable: r.backendCompletelyDisable(terraform),
Name: terraform.Name,
Namespace: terraform.Namespace,
Uuid: string(terraform.GetUID()),
Revision: revision,
})
if err != nil {
err = fmt.Errorf("error saving plan secret: %s", err)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecPlanFailedReason,
err.Error(),
), err
}
log.Info(fmt.Sprintf("save tfplan: %s", saveTFPlanReply.Message))
if drifted {
terraform = infrav1.TerraformPlannedWithChanges(terraform, revision, "Plan generated")
} else {
terraform = infrav1.TerraformPlannedNoChanges(terraform, revision, "Plan no changes")
}
return terraform, nil
}
func (r *TerraformReconciler) backendCompletelyDisable(terraform infrav1.Terraform) bool {
return terraform.Spec.BackendConfig != nil && terraform.Spec.BackendConfig.Disable == true
}
func (r *TerraformReconciler) apply(ctx context.Context, terraform infrav1.Terraform, tfInstance string, runnerClient runner.RunnerClient, revision string, outputs *map[string]tfexec.OutputMeta) (infrav1.Terraform, error) {
const (
TFPlanName = "tfplan"
)
log := ctrl.LoggerFrom(ctx)
objectKey := types.NamespacedName{Namespace: terraform.Namespace, Name: terraform.Name}
terraform = infrav1.TerraformProgressing(terraform, "Applying")
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "unable to update status before Terraform applying")
return terraform, err
}
loadTFPlanReply, err := runnerClient.LoadTFPlan(ctx, &runner.LoadTFPlanRequest{
TfInstance: tfInstance,
Name: terraform.Name,
Namespace: terraform.Namespace,
BackendCompletelyDisable: r.backendCompletelyDisable(terraform),
PendingPlan: terraform.Status.Plan.Pending,
})
if err != nil {
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecApplyFailedReason,
err.Error(),
), err
}
log.Info(fmt.Sprintf("load tf plan: %s", loadTFPlanReply.Message))
terraform = infrav1.TerraformApplying(terraform, revision, "Apply started")
if err := r.patchStatus(ctx, objectKey, terraform.Status); err != nil {
log.Error(err, "error recording apply status: %s", err)
return terraform, err
}
applyRequest := &runner.ApplyRequest{
TfInstance: tfInstance,
}
if r.backendCompletelyDisable(terraform) {
// do nothing
} else {
applyRequest.DirOrPlan = TFPlanName
}
var isDestroyApplied bool
// this a special case, when backend is completely disabled.
// we need to use "destroy" command instead of apply
if r.backendCompletelyDisable(terraform) && terraform.Spec.Destroy == true {
destroyReply, err := runnerClient.Destroy(ctx, &runner.DestroyRequest{
TfInstance: tfInstance,
})
log.Info(fmt.Sprintf("destroy: %s", destroyReply.Message))
if err != nil {
err = fmt.Errorf("error running Destroy: %s", err)
return infrav1.TerraformAppliedFailResetPlanAndNotReady(
terraform,
revision,
infrav1.TFExecApplyFailedReason,
err.Error(),
), err
}
isDestroyApplied = true
} else {
applyReply, err := runnerClient.Apply(ctx, applyRequest)
if err != nil {
err = fmt.Errorf("error running Apply: %s", err)
return infrav1.TerraformAppliedFailResetPlanAndNotReady(
terraform,
revision,
infrav1.TFExecApplyFailedReason,
err.Error(),
), err
}
log.Info(fmt.Sprintf("apply: %s", applyReply.Message))
isDestroyApplied = terraform.Status.Plan.IsDestroyPlan
}
terraform = infrav1.TerraformApplied(terraform, revision, "Applied successfully", isDestroyApplied)
outputReply, err := runnerClient.Output(ctx, &runner.OutputRequest{
TfInstance: tfInstance,
})
if err != nil {
// TODO should not be this Error
// warning-like status is enough
err = fmt.Errorf("error running Output: %s", err)
return infrav1.TerraformNotReady(
terraform,
revision,
infrav1.TFExecOutputFailedReason,
err.Error(),
), err
}
*outputs = convertOutputs(outputReply.Outputs)
var availableOutputs []string
for k := range *outputs {
availableOutputs = append(availableOutputs, k)
}
if len(availableOutputs) > 0 {
sort.Strings(availableOutputs)
terraform = infrav1.TerraformOutputsAvailable(terraform, availableOutputs, "Outputs available")
}
return terraform, nil
}
func convertOutputs(outputs map[string]*runner.OutputMeta) map[string]tfexec.OutputMeta {
result := map[string]tfexec.OutputMeta{}
for k, v := range outputs {