/
terraform_controller.go
3290 lines (2956 loc) · 102 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
package controllers
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"math"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
tfv1beta1 "github.com/galleybytes/tofu-kubed/pkg/apis/tf/v1beta1"
"github.com/galleybytes/tofu-kubed/pkg/utils"
"github.com/go-logr/logr"
getter "github.com/hashicorp/go-getter"
localcache "github.com/patrickmn/go-cache"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
runtimecontroller "sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
//go:embed scripts/tf.sh
var defaultInlineTerraformTaskExecutionFile string
//go:embed scripts/setup.sh
var defaultInlineSetupTaskExecutionFile string
//go:embed scripts/noop.sh
var defaultInlineNoOpExecutionFile string
// ReconcileTerraform reconciles a Terraform object
type ReconcileTerraform struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
Client client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
Log logr.Logger
MaxConcurrentReconciles int
Cache *localcache.Cache
GlobalEnvFromConfigmapData map[string]string
GlobalEnvFromSecretData map[string][]byte
GlobalEnvSuffix string
// InheritNodeSelector to use the controller's nodeSelectors for every task created by the controller.
// Value of this field will come from the owning deployment and cached.
InheritNodeSelector bool
NodeSelectorCacheKey string
// InheritAffinity to use the controller's affinity rules for every task created by the controller
// Value of this field will come from the owning deployment and cached.
InheritAffinity bool
AffinityCacheKey string
// InheritTolerations to use the controller's tolerations for every task created by the controller
// Value of this field will come from the owning deployment and cached.
InheritTolerations bool
TolerationsCacheKey string
}
// createEnvFromSources adds any of the global environment vars defined at the controller scope
// and generates a configmap or secret that will be loaded into the resource Task pods.
//
// TODO Each time a new generation is created of the tfo resource, this "global" env from vars should
// generate a new configap and secret. The reason for this is to prevent a generation from producing a
// different plan when is was the controller that changed options. A new generation should be forced
// if the plan needs to change.
func (r ReconcileTerraform) createEnvFromSources(ctx context.Context, tf *tfv1beta1.Terraform) error {
resourceName := tf.Name
resourceNamespace := tf.Namespace
name := fmt.Sprintf("%s-%s", resourceName, r.GlobalEnvSuffix)
if len(r.GlobalEnvFromConfigmapData) > 0 {
configMap := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: resourceNamespace,
},
Data: r.GlobalEnvFromConfigmapData,
}
controllerutil.SetControllerReference(tf, &configMap, r.Scheme)
errOnCreate := r.Client.Create(ctx, &configMap)
if errOnCreate != nil {
if errors.IsAlreadyExists(errOnCreate) {
errOnUpdate := r.Client.Update(ctx, &configMap)
if errOnUpdate != nil {
return errOnUpdate
}
} else {
return errOnCreate
}
}
}
if len(r.GlobalEnvFromSecretData) > 0 {
secret := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: resourceNamespace,
},
Data: r.GlobalEnvFromSecretData,
}
controllerutil.SetControllerReference(tf, &secret, r.Scheme)
errOnCreate := r.Client.Create(ctx, &secret)
if errOnCreate != nil {
if errors.IsAlreadyExists(errOnCreate) {
errOnUpdate := r.Client.Update(ctx, &secret)
if errOnUpdate != nil {
return errOnUpdate
}
} else {
return errOnCreate
}
}
}
return nil
}
// listEnvFromSources makes an assumption that if global envs are defined in the controller, the
// configmap and secrets for the envs have been created or updated when initializing the workflow.
//
// This function will return the envFrom of the resources that should exist but does not validate that
// they do exist. If the configmap or secret is missing, force the generation of the tfo resource to update
// and the controller will recreate the missing resources.
func (r ReconcileTerraform) listEnvFromSources(tf *tfv1beta1.Terraform) []corev1.EnvFromSource {
envFrom := []corev1.EnvFromSource{}
resourceName := tf.Name
name := fmt.Sprintf("%s-%s", resourceName, r.GlobalEnvSuffix)
if len(r.GlobalEnvFromConfigmapData) > 0 {
// ConfigMap that should exist
envFrom = append(envFrom, corev1.EnvFromSource{
ConfigMapRef: &corev1.ConfigMapEnvSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: name,
},
},
})
}
if len(r.GlobalEnvFromSecretData) > 0 {
// Secret that should exist
envFrom = append(envFrom, corev1.EnvFromSource{
SecretRef: &corev1.SecretEnvSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: name,
},
},
})
}
return envFrom
}
// SetupWithManager sets up the controller with the Manager.
func (r *ReconcileTerraform) SetupWithManager(mgr ctrl.Manager) error {
controllerOptions := runtimecontroller.Options{
MaxConcurrentReconciles: r.MaxConcurrentReconciles,
}
err := ctrl.NewControllerManagedBy(mgr).
For(&tfv1beta1.Terraform{}).
Owns(&corev1.Pod{}).
WithOptions(controllerOptions).
Complete(r)
if err != nil {
return err
}
return nil
}
func terraformTaskList() []tfv1beta1.TaskName {
return []tfv1beta1.TaskName{
tfv1beta1.RunInit,
tfv1beta1.RunInitDelete,
tfv1beta1.RunPlan,
tfv1beta1.RunPlanDelete,
tfv1beta1.RunApply,
tfv1beta1.RunApplyDelete,
}
}
func scriptTaskList() []tfv1beta1.TaskName {
return []tfv1beta1.TaskName{
tfv1beta1.RunPreInit,
tfv1beta1.RunPreInitDelete,
tfv1beta1.RunPostInit,
tfv1beta1.RunPostInitDelete,
tfv1beta1.RunPrePlan,
tfv1beta1.RunPrePlanDelete,
tfv1beta1.RunPostPlan,
tfv1beta1.RunPostPlanDelete,
tfv1beta1.RunPreApply,
tfv1beta1.RunPreApplyDelete,
tfv1beta1.RunPostApply,
tfv1beta1.RunPostApplyDelete,
}
}
func setupTaskList() []tfv1beta1.TaskName {
return []tfv1beta1.TaskName{
tfv1beta1.RunSetup,
tfv1beta1.RunSetupDelete,
}
}
// ParsedAddress uses go-getter's detect mechanism to get the parsed url
// TODO ParsedAddress can be moved into it's own package
type ParsedAddress struct {
// DetectedScheme is the name of the bin or protocol to use to fetch. For
// example, git will be used to fetch git repos (over https or ssh
// "protocol").
DetectedScheme string `json:"detect"`
// Path the target path for the downloaded file or directory
Path string `json:"path"`
// The files downloaded get called out in the terraform plan as -var-file
UseAsVar bool `json:"useAsVar"`
// Url is the raw address + query
Url string `json:"url"`
// Files are the files to find with a repo.
Files []string `json:"files"`
// Hash is also known as the `ref` query argument. For git this is the
// commit-sha or branch-name to checkout.
Hash string `json:"hash"`
// UrlScheme is the protocol of the URL
UrlScheme string `json:"protocol"`
// Uri is the path of the URL after the proto://host.
Uri string `json:"uri"`
// Host is the host of the URL.
Host string `json:"host"`
// Port is the port to use when fetching the URL.
Port string `json:"port"`
// User is the user to use when fetching the URL.
User string `json:"user"`
// Repo when using a SCM is the URL of the repo which is the same as the
// URL and omitting the query args.
Repo string `json:"repo"`
}
type TaskOptions struct {
annotations map[string]string
// configMapSourceName (and configMapSourceKey) is used to populate an environment variable of the task pod.
// When not empty should be understood by the task to use the configmap as the execution script
configMapSourceName string
// configMapSourceKey (and configMapSourceName) is used to populate an environment variable of the task pod.
// When not empty should be understood by the task to use the configmap as the execution script
configMapSourceKey string
credentials []tfv1beta1.Credentials
env []corev1.EnvVar
envFrom []corev1.EnvFromSource
generation int64
image string
imagePullPolicy corev1.PullPolicy
inheritedAffinity *corev1.Affinity
inheritedNodeSelector map[string]string
inheritedTolerations []corev1.Toleration
// inlineTaskExecutionFile is used to populate an environment variable of the task pod. When not empty the
// task should use this filename which should exist from a configmap mount in the pod.
inlineTaskExecutionFile string
labels map[string]string
mainModulePluginData map[string]string
namespace string
outputsSecretName string
outputsToInclude []string
outputsToOmit []string
policyRules []rbacv1.PolicyRule
prefixedName string
resourceLabels map[string]string
resourceName string
resourceUUID string
task tfv1beta1.TaskName
saveOutputs bool
secretData map[string][]byte
serviceAccount string
cleanupDisk bool
stripGenerationLabelOnOutputsSecret bool
terraformModuleParsed ParsedAddress
terraformVersion string
// urlSource is used to populate an environment variable of the task pod. When not empty is used by the task
// as the download location for the script to execute in the task.
urlSource string
versionedName string
requireApproval bool
restartPolicy corev1.RestartPolicy
volumes []corev1.Volume
volumeMounts []corev1.VolumeMount
// When a plugin is defined to run as a sidecar, this field will be filled in and attached to current task
sidecarPlugins []corev1.Pod
}
func newTaskOptions(tf *tfv1beta1.Terraform, task tfv1beta1.TaskName, generation int64, globalEnvFrom []corev1.EnvFromSource, affinity *corev1.Affinity, nodeSelector map[string]string, tolerations []corev1.Toleration) TaskOptions {
// TODO Read the tfstate and decide IF_NEW_RESOURCE based on that
// applyAction := false
resourceName := tf.Name
resourceUUID := string(tf.UID)
prefixedName := tf.Status.PodNamePrefix
versionedName := prefixedName + "-v" + fmt.Sprint(tf.Generation)
terraformVersion := tf.Spec.TerraformVersion
if terraformVersion == "" {
terraformVersion = "latest"
}
image := ""
imagePullPolicy := corev1.PullAlways
policyRules := []rbacv1.PolicyRule{}
labels := make(map[string]string)
annotations := make(map[string]string)
env := []corev1.EnvVar{}
envFrom := globalEnvFrom
cleanupDisk := false
urlSource := ""
configMapSourceName := ""
configMapSourceKey := ""
restartPolicy := corev1.RestartPolicyNever
inlineTaskExecutionFile := ""
useDefaultInlineTaskExecutionFile := false
volumes := []corev1.Volume{}
volumeMounts := []corev1.VolumeMount{}
// TaskOptions have data for all the tasks but since we're only interested
// in the ones for this taskType, extract and add them to RunOptions
for _, taskOption := range tf.Spec.TaskOptions {
if tfv1beta1.ListContainsTask(taskOption.For, task) ||
tfv1beta1.ListContainsTask(taskOption.For, "*") {
// This statement finds taskOptions that match this current task OR *
policyRules = append(policyRules, taskOption.PolicyRules...)
for key, value := range taskOption.Annotations {
annotations[key] = value
}
for key, value := range taskOption.Labels {
labels[key] = value
}
env = append(env, taskOption.Env...)
envFrom = append(envFrom, taskOption.EnvFrom...)
if taskOption.RestartPolicy != "" {
restartPolicy = taskOption.RestartPolicy
}
volumes = append(volumes, taskOption.Volumes...)
volumeMounts = append(volumeMounts, taskOption.VolumeMounts...)
}
if tfv1beta1.ListContainsTask(taskOption.For, task) {
// This statement only matches taskOptions that match this current task only
urlSource = taskOption.Script.Source
if configMapSelector := taskOption.Script.ConfigMapSelector; configMapSelector != nil {
configMapSourceName = configMapSelector.Name
configMapSourceKey = configMapSelector.Key
}
if inlineScript := taskOption.Script.Inline; inlineScript != "" {
inlineTaskExecutionFile = fmt.Sprintf("inline-%s.sh", task)
}
}
}
images := tf.Spec.Images
if images == nil {
// setup default images
images = &tfv1beta1.Images{}
}
if images.Terraform == nil {
images.Terraform = &tfv1beta1.ImageConfig{
ImagePullPolicy: corev1.PullIfNotPresent,
}
}
if images.Terraform.Image == "" {
images.Terraform.Image = fmt.Sprintf("%s:%s", tfv1beta1.TerraformTaskImageRepoDefault, terraformVersion)
} else {
terraformImage := images.Terraform.Image
splitImage := strings.Split(images.Terraform.Image, ":")
if length := len(splitImage); length > 1 {
terraformImage = strings.Join(splitImage[:length-1], ":")
}
images.Terraform.Image = fmt.Sprintf("%s:%s", terraformImage, terraformVersion)
}
if images.Setup == nil {
images.Setup = &tfv1beta1.ImageConfig{
ImagePullPolicy: corev1.PullIfNotPresent,
}
}
if images.Setup.Image == "" {
images.Setup.Image = fmt.Sprintf("%s:%s", tfv1beta1.SetupTaskImageRepoDefault, tfv1beta1.SetupTaskImageTagDefault)
}
if images.Script == nil {
images.Script = &tfv1beta1.ImageConfig{
ImagePullPolicy: corev1.PullIfNotPresent,
}
}
if images.Script.Image == "" {
images.Script.Image = fmt.Sprintf("%s:%s", tfv1beta1.ScriptTaskImageRepoDefault, tfv1beta1.ScriptTaskImageTagDefault)
}
if inlineTaskExecutionFile == "" && urlSource == "" && (configMapSourceKey == "" || configMapSourceName == "") {
useDefaultInlineTaskExecutionFile = true
}
if tfv1beta1.ListContainsTask(terraformTaskList(), task) {
image = images.Terraform.Image
imagePullPolicy = images.Terraform.ImagePullPolicy
if useDefaultInlineTaskExecutionFile {
inlineTaskExecutionFile = "default-terraform.sh"
}
} else if tfv1beta1.ListContainsTask(scriptTaskList(), task) {
image = images.Script.Image
imagePullPolicy = images.Script.ImagePullPolicy
if useDefaultInlineTaskExecutionFile {
inlineTaskExecutionFile = "default-noop.sh"
}
} else if tfv1beta1.ListContainsTask(setupTaskList(), task) {
image = images.Setup.Image
imagePullPolicy = images.Setup.ImagePullPolicy
if useDefaultInlineTaskExecutionFile {
inlineTaskExecutionFile = "default-setup.sh"
}
}
// sshConfig := utils.TruncateResourceName(tf.Name, 242) + "-ssh-config"
serviceAccount := tf.Spec.ServiceAccount
if serviceAccount == "" {
// By prefixing the service account with "tf-", IRSA roles can use wildcard
// "tf-*" service account for AWS credentials.
serviceAccount = "tf-" + versionedName
}
credentials := tf.Spec.Credentials
// Outputs will be saved as a secret that will have the same lifecycle
// as the Terraform CustomResource by adding the ownership metadata
outputsSecretName := versionedName + "-outputs"
saveOutputs := false
stripGenerationLabelOnOutputsSecret := false
if tf.Spec.OutputsSecret != "" {
outputsSecretName = tf.Spec.OutputsSecret
saveOutputs = true
stripGenerationLabelOnOutputsSecret = true
} else if tf.Spec.WriteOutputsToStatus {
saveOutputs = true
}
outputsToInclude := tf.Spec.OutputsToInclude
outputsToOmit := tf.Spec.OutputsToOmit
if tf.Spec.Setup != nil {
cleanupDisk = tf.Spec.Setup.CleanupDisk
}
resourceLabels := map[string]string{
"terraforms.tf.galleybytes.com/generation": fmt.Sprintf("%d", generation),
"terraforms.tf.galleybytes.com/resourceName": resourceName,
"terraforms.tf.galleybytes.com/podPrefix": prefixedName,
"terraforms.tf.galleybytes.com/terraformVersion": terraformVersion,
"app.kubernetes.io/name": "terraform-operator",
"app.kubernetes.io/component": "terraform-operator-runner",
"app.kubernetes.io/created-by": "controller",
}
requireApproval := tf.Spec.RequireApproval
if task.ID() == -2 {
// This is not one of the main tasks so it's probably an plugin
resourceLabels["terraforms.tf.galleybytes.com/isPlugin"] = "true"
}
return TaskOptions{
env: env,
generation: generation,
configMapSourceName: configMapSourceName,
configMapSourceKey: configMapSourceKey,
envFrom: envFrom,
policyRules: policyRules,
annotations: annotations,
labels: labels,
imagePullPolicy: imagePullPolicy,
inheritedAffinity: affinity,
inheritedNodeSelector: nodeSelector,
inheritedTolerations: tolerations,
inlineTaskExecutionFile: inlineTaskExecutionFile,
namespace: tf.Namespace,
resourceName: resourceName,
prefixedName: prefixedName,
versionedName: versionedName,
credentials: credentials,
terraformVersion: terraformVersion,
image: image,
task: task,
resourceLabels: resourceLabels,
resourceUUID: resourceUUID,
serviceAccount: serviceAccount,
mainModulePluginData: make(map[string]string),
secretData: make(map[string][]byte),
cleanupDisk: cleanupDisk,
outputsSecretName: outputsSecretName,
saveOutputs: saveOutputs,
stripGenerationLabelOnOutputsSecret: stripGenerationLabelOnOutputsSecret,
outputsToInclude: outputsToInclude,
outputsToOmit: outputsToOmit,
urlSource: urlSource,
requireApproval: requireApproval,
restartPolicy: restartPolicy,
volumes: volumes,
volumeMounts: volumeMounts,
sidecarPlugins: nil,
}
}
const terraformFinalizer = "finalizer.tf.galleybytes.com"
// Reconcile reads that state of the cluster for a Terraform object and makes changes based on the state read
// and what is in the Terraform.Spec
// Note:
// The Controller will requeue the Request to be processed again if the returned error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (r *ReconcileTerraform) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
reconcilerID := string(uuid.NewUUID())
reqLogger := r.Log.WithValues("Terraform", request.NamespacedName, "id", reconcilerID)
err := r.cacheNodeSelectors(ctx, reqLogger)
if err != nil {
panic(err)
}
lockKey := request.String() + "-reconcile-lock"
lockOwner, lockFound := r.Cache.Get(lockKey)
if lockFound {
reqLogger.Info(fmt.Sprintf("Request is locked by '%s'", lockOwner.(string)))
return reconcile.Result{RequeueAfter: 30 * time.Second}, nil
}
r.Cache.Set(lockKey, reconcilerID, -1)
defer r.Cache.Delete(lockKey)
defer reqLogger.V(6).Info("Request has released reconcile lock")
reqLogger.V(6).Info("Request has acquired reconcile lock")
tf, err := r.getTerraformResource(ctx, request.NamespacedName, 3, reqLogger)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
// reqLogger.Info(fmt.Sprintf("Not found, instance is defined as: %+v", instance))
reqLogger.V(1).Info("Terraform resource not found. Ignoring since object must be deleted")
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
reqLogger.Error(err, "Failed to get Terraform")
return reconcile.Result{}, err
}
// Final delete by removing finalizers
if tf.Status.Phase == tfv1beta1.PhaseDeleted {
reqLogger.Info("Remove finalizers")
if err := r.updateSecretFinalizer(ctx, tf); err != nil {
r.Recorder.Event(tf, "Warning", "ProcessingError", err.Error())
return reconcile.Result{}, err
}
_ = updateFinalizer(tf)
err := r.update(ctx, tf)
if err != nil {
r.Recorder.Event(tf, "Warning", "ProcessingError", err.Error())
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
// Finalizers
if updateFinalizer(tf) {
err := r.update(ctx, tf)
if err != nil {
return reconcile.Result{}, err
}
reqLogger.V(1).Info("Updated finalizer")
return reconcile.Result{}, nil
}
// Initialize resource
if tf.Status.PodNamePrefix == "" {
// Generate a unique name for everything related to this tf resource
// Must trucate at 220 chars of original name to ensure room for the
// suffixes that will be added (and possible future suffix expansion)
tf.Status.PodNamePrefix = fmt.Sprintf("%s-%s",
utils.TruncateResourceName(tf.Name, 54),
utils.StringWithCharset(8, utils.AlphaNum),
)
tf.Status.LastCompletedGeneration = 0
tf.Status.Phase = tfv1beta1.PhaseInitializing
err := r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
}
return reconcile.Result{}, nil
}
// Add the first stage
if tf.Status.Stage.Generation == 0 {
task := tfv1beta1.RunSetup
stageState := tfv1beta1.StateInitializing
interruptible := tfv1beta1.CanNotBeInterrupt
stage := newStage(tf, task, "TF_RESOURCE_CREATED", interruptible, stageState)
if stage == nil {
return reconcile.Result{}, fmt.Errorf("failed to create a new stage")
}
tf.Status.Stage = *stage
tf.Status.PluginsStarted = []tfv1beta1.TaskName{}
err := r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
deletePhases := []string{
string(tfv1beta1.PhaseDeleting),
string(tfv1beta1.PhaseInitDelete),
string(tfv1beta1.PhaseDeleted),
}
// Check if the resource is marked to be deleted which is
// indicated by the deletion timestamp being set.
if tf.GetDeletionTimestamp() != nil && !utils.ListContainsStr(deletePhases, string(tf.Status.Phase)) {
tf.Status.Phase = tfv1beta1.PhaseInitDelete
}
// // TODO Check the status on stages that have not completed
// for _, stage := range tf.Status.Stages {
// if stage.State == tfv1alpha1.StateInProgress {
//
// }
// }
stage := r.checkSetNewStage(ctx, tf)
if stage != nil {
tf.Status.Stage = *stage
if stage.Reason == "RESTARTED_WORKFLOW" || stage.Reason == "RESTARTED_DELETE_WORKFLOW" {
_ = r.removeOldPlan(tf)
// TODO what to do if the remove old plan function fails
}
reqLogger.V(2).Info(fmt.Sprintf("Stage moving from '%s' -> '%s'", tf.Status.Stage.TaskType, stage.TaskType))
desiredStatus := tf.Status
err := r.updateStatusWithRetry(ctx, tf, &desiredStatus, reqLogger)
if err != nil {
reqLogger.V(1).Info(fmt.Sprintf("Error adding stage '%s': %s", stage.TaskType, err.Error()))
}
if tf.Spec.KeepLatestPodsOnly {
go r.backgroundReapOldGenerationPods(tf, 0)
}
return reconcile.Result{}, nil
}
globalEnvFrom := r.listEnvFromSources(tf)
if err != nil {
return reconcile.Result{}, err
}
currentStage := tf.Status.Stage
podType := currentStage.TaskType
generation := currentStage.Generation
affinity, nodeSelector, tolerations := r.getNodeSelectorsFromCache()
runOpts := newTaskOptions(tf, currentStage.TaskType, generation, globalEnvFrom, affinity, nodeSelector, tolerations)
if podType == tfv1beta1.RunNil {
// podType is blank when the terraform workflow has completed for
// either create or delete.
if tf.Status.Phase == tfv1beta1.PhaseRunning {
// Updates the status as "completed" on the resource
tf.Status.Phase = tfv1beta1.PhaseCompleted
if tf.Spec.WriteOutputsToStatus {
// runOpts.outputsSecetName
secret, err := r.loadSecret(ctx, runOpts.outputsSecretName, runOpts.namespace)
if err != nil {
reqLogger.Error(err, fmt.Sprintf("failed to load secret '%s'", runOpts.outputsSecretName))
}
// Get a list of outputs to clean up any removed outputs
keysInOutputs := []string{}
for key := range secret.Data {
keysInOutputs = append(keysInOutputs, key)
}
for key := range tf.Status.Outputs {
if !utils.ListContainsStr(keysInOutputs, key) {
// remove the key if its not in the new list of outputs
delete(tf.Status.Outputs, key)
}
}
for key, value := range secret.Data {
if tf.Status.Outputs == nil {
tf.Status.Outputs = make(map[string]string)
}
tf.Status.Outputs[key] = string(value)
}
}
err := r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{}, err
}
} else if tf.Status.Phase == tfv1beta1.PhaseDeleting {
// Updates the status as "deleted" which will be used to tell the
// controller to remove any finalizers).
tf.Status.Phase = tfv1beta1.PhaseDeleted
err := r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{}, err
}
}
return reconcile.Result{Requeue: false}, nil
}
// Check for the current stage pod
inNamespace := client.InNamespace(tf.Namespace)
f := fields.Set{
"metadata.generateName": fmt.Sprintf("%s-%s-", tf.Status.PodNamePrefix+"-v"+fmt.Sprint(generation), podType),
}
labelSelector := map[string]string{
"terraforms.tf.galleybytes.com/generation": fmt.Sprintf("%d", generation),
}
matchingFields := client.MatchingFields(f)
matchingLabels := client.MatchingLabels(labelSelector)
pods := &corev1.PodList{}
err = r.Client.List(ctx, pods, inNamespace, matchingFields, matchingLabels)
if err != nil {
reqLogger.Error(err, "")
return reconcile.Result{}, nil
}
if len(pods.Items) == 0 && tf.Status.Stage.State == tfv1beta1.StateInProgress {
// This condition is generally met when the user deletes the pod.
// Force the state to transition away from in-progress and then
// requeue.
tf.Status.Stage.State = tfv1beta1.StateInitializing
err = r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{Requeue: true}, nil
}
return reconcile.Result{}, nil
}
if len(pods.Items) == 0 {
// Trigger a new pod when no pods are found for current stage
sidecarNames := []string{}
for pluginTaskName, pluginConfig := range tf.Spec.Plugins {
if tfv1beta1.ListContainsTask(tf.Status.PluginsStarted, pluginTaskName) {
continue
}
when := pluginConfig.When
whenTask := pluginConfig.Task
switch when {
case "After":
if whenTask.ID() < podType.ID() {
defer r.createPluginJob(ctx, reqLogger, tf, pluginTaskName, pluginConfig, globalEnvFrom)
}
case "At":
if whenTask.ID() == podType.ID() {
defer r.createPluginJob(ctx, reqLogger, tf, pluginTaskName, pluginConfig, globalEnvFrom)
}
case "Sidecar":
if whenTask.ID() == podType.ID() {
pluginSidecarPod, err := r.getPluginSidecarPod(ctx, reqLogger, tf, pluginTaskName, pluginConfig, globalEnvFrom)
if err != nil {
if pluginConfig.Must {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{Requeue: true}, nil
}
reqLogger.V(1).Info("Error adding sidecar plugin: %s", err.Error())
continue
}
exists := false
for _, c := range pluginSidecarPod.Spec.Containers {
if utils.ListContainsStr(sidecarNames, c.Name) {
exists = true
}
}
if !exists {
sidecarNames = append(sidecarNames, getContainerNames(pluginSidecarPod)...)
runOpts.sidecarPlugins = append(runOpts.sidecarPlugins, *pluginSidecarPod)
}
}
}
}
if (podType == tfv1beta1.RunPlan || podType == tfv1beta1.RunPlanDelete) && runOpts.requireApproval {
requireApprovalSidecarPlugin := tfv1beta1.Plugin{
ImageConfig: tfv1beta1.ImageConfig{
Image: "ghcr.io/galleybytes/require-approval:0.1.1",
ImagePullPolicy: corev1.PullIfNotPresent,
},
Must: true,
}
pluginSidecarPod, err := r.getPluginSidecarPod(ctx, reqLogger, tf, tfv1beta1.TaskName("require-approval"), requireApprovalSidecarPlugin, globalEnvFrom)
if err != nil {
reqLogger.V(1).Info("Error adding require-approval plugin: %s", err.Error())
return reconcile.Result{Requeue: true}, nil
}
exists := false
for _, c := range pluginSidecarPod.Spec.Containers {
if utils.ListContainsStr(sidecarNames, c.Name) {
exists = true
}
}
if !exists {
runOpts.sidecarPlugins = append(runOpts.sidecarPlugins, *pluginSidecarPod)
}
}
reqLogger.V(1).Info(fmt.Sprintf("Setting up the '%s' pod", podType))
err := r.setupAndRun(ctx, tf, runOpts)
if err != nil {
reqLogger.Error(err, "")
return reconcile.Result{}, err
}
if tf.Status.Phase == tfv1beta1.PhaseInitializing {
tf.Status.Phase = tfv1beta1.PhaseRunning
} else if tf.Status.Phase == tfv1beta1.PhaseInitDelete {
tf.Status.Phase = tfv1beta1.PhaseDeleting
}
tf.Status.Stage.State = tfv1beta1.StateInProgress
// TODO because the pod is already running, is it critical that the
// phase and state be updated. The updateStatus function needs to retry
// if it fails to update.
err = r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{Requeue: true}, nil
}
// When the pod is created, don't requeue. The pod's status changes
// will trigger tfo to reconcile.
return reconcile.Result{}, nil
}
// At this point, a pod is found for the current stage. We can check the
// pod status to find out more info about the pod.
realPod := pods.Items[0]
podName := realPod.ObjectMeta.Name
podPhase := realPod.Status.Phase
msg := fmt.Sprintf("Pod '%s' %s", podName, podPhase)
// if tf.Status.Stage.PodName != podName {
// if tf.Status.Stage.PodName == "" {
// // This is the first time this pod is found. Set the rerun attempt to 0
// tf.Status.Stage.RerunAttempt = 0
// } else {
// tf.Status.Stage.RerunAttempt++
// }
// }
tf.Status.Stage.PodUID = string(realPod.UID)
tf.Status.Stage.PodName = podName
if tf.Status.Stage.Message != msg {
tf.Status.Stage.Message = msg
reqLogger.Info(msg)
}
// TODO Does the user need reason and message?
// reason := realPod.Status.Reason
// message := realPod.Status.Message
// if reason != "" {
// msg = fmt.Sprintf("%s %s", msg, reason)
// }
// if message != "" {
// msg = fmt.Sprintf("%s %s", msg, message)
// }
if realPod.Status.Phase == corev1.PodFailed {
tf.Status.Stage.State = tfv1beta1.StateFailed
tf.Status.Stage.StopTime = metav1.NewTime(time.Now())
err = r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
if realPod.Status.Phase == corev1.PodSucceeded {
tf.Status.Stage.State = tfv1beta1.StateComplete
tf.Status.Stage.StopTime = metav1.NewTime(time.Now())
err = r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{}, err
}
if !tf.Spec.KeepCompletedPods && !tf.Spec.KeepLatestPodsOnly {
err := r.Client.Delete(ctx, &realPod)
if err != nil {
reqLogger.V(1).Info(err.Error())
}
}
return reconcile.Result{}, nil
}
tf.Status.Stage.State = tfv1beta1.StageState(realPod.Status.Phase)
// Finally, update any statuses that have been changed if not already saved. This is probablye
// for pending condition that does not require anything to be done.
err = r.updateStatusWithRetry(ctx, tf, &tf.Status, reqLogger)
if err != nil {
reqLogger.V(1).Info(err.Error())
return reconcile.Result{}, err
}
// TODO should tf operator "auto" reconciliate (eg plan+apply)?
// TODO how should we handle manually triggering apply
return reconcile.Result{}, nil
}
// getTerraformResource fetches the terraform resource with a retry
func (r ReconcileTerraform) getTerraformResource(ctx context.Context, namespacedName types.NamespacedName, maxRetry int, reqLogger logr.Logger) (*tfv1beta1.Terraform, error) {
tf := &tfv1beta1.Terraform{}
for retryCount := 1; retryCount <= maxRetry; retryCount++ {
err := r.Client.Get(ctx, namespacedName, tf)
if err != nil {
if errors.IsNotFound(err) {
return tf, err
} else if retryCount < maxRetry {
time.Sleep(100 * time.Millisecond)
continue
}
return tf, err
} else {
break
}
}
return tf, nil
}
func newStage(tf *tfv1beta1.Terraform, taskType tfv1beta1.TaskName, reason string, interruptible tfv1beta1.Interruptible, stageState tfv1beta1.StageState) *tfv1beta1.Stage {
if reason == "GENERATION_CHANGE" {
tf.Status.PluginsStarted = []tfv1beta1.TaskName{}
tf.Status.Phase = tfv1beta1.PhaseInitializing
}
startTime := metav1.NewTime(time.Now())
stopTime := metav1.NewTime(time.Unix(0, 0))
if stageState == tfv1beta1.StateComplete {
stopTime = startTime
}
return &tfv1beta1.Stage{
Generation: tf.Generation,
Interruptible: interruptible,
Reason: reason,
State: stageState,
TaskType: taskType,
StartTime: startTime,
StopTime: stopTime,
}
}
func getConfiguredTasks(taskOptions *[]tfv1beta1.TaskOption) []tfv1beta1.TaskName {
tasks := []tfv1beta1.TaskName{
tfv1beta1.RunSetup,
tfv1beta1.RunInit,
tfv1beta1.RunPlan,
tfv1beta1.RunApply,
tfv1beta1.RunSetupDelete,
tfv1beta1.RunInitDelete,
tfv1beta1.RunPlanDelete,