-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathworkflow_utils.go
More file actions
1331 lines (1198 loc) · 48.5 KB
/
Copy pathworkflow_utils.go
File metadata and controls
1331 lines (1198 loc) · 48.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package exec
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/huh"
"github.com/google/uuid"
"github.com/samber/lo"
"mvdan.cc/sh/v3/shell"
errUtils "github.com/cloudposse/atmos/errors"
"github.com/cloudposse/atmos/internal/tui/templates/term"
uiutils "github.com/cloudposse/atmos/internal/tui/utils"
w "github.com/cloudposse/atmos/internal/tui/workflow"
"github.com/cloudposse/atmos/pkg/auth"
"github.com/cloudposse/atmos/pkg/auth/credentials"
"github.com/cloudposse/atmos/pkg/auth/validation"
"github.com/cloudposse/atmos/pkg/background"
"github.com/cloudposse/atmos/pkg/ci"
"github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/data"
"github.com/cloudposse/atmos/pkg/dependencies"
envpkg "github.com/cloudposse/atmos/pkg/env"
ioLayer "github.com/cloudposse/atmos/pkg/io"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/process"
"github.com/cloudposse/atmos/pkg/retry"
stepPkg "github.com/cloudposse/atmos/pkg/runner/step"
"github.com/cloudposse/atmos/pkg/schema"
"github.com/cloudposse/atmos/pkg/telemetry"
"github.com/cloudposse/atmos/pkg/ui"
u "github.com/cloudposse/atmos/pkg/utils"
workflowPkg "github.com/cloudposse/atmos/pkg/workflow"
)
// Workflow error title for formatted output.
const WorkflowErrTitle = "Workflow Error"
// workflowTemplatePasses is the number of template render passes the workflow
// step executor uses, matching the custom command step path (cmd_utils.go) so
// multi-level templates resolve identically in both.
const workflowTemplatePasses = 3
// bgRunIDLen is the length of the short per-run id used to scope background container
// instance names when no explicit `--stack` is given.
const bgRunIDLen = 8
// Local errors not in shared package (workflow-specific internal errors).
var (
ErrNoWorkflowFilesToSelect = errors.New("no workflow files to select from")
ErrNonTTYWorkflowSelection = errors.New("interactive workflow selection not available in non-TTY or CI environments")
)
// KnownWorkflowErrors contains all known workflow sentinel errors for error handling.
var KnownWorkflowErrors = []error{
errUtils.ErrWorkflowNoSteps,
errUtils.ErrInvalidWorkflowStepType,
errUtils.ErrInvalidFromStep,
errUtils.ErrWorkflowStepFailed,
errUtils.ErrWorkflowNoWorkflow,
errUtils.ErrWorkflowFileNotFound,
errUtils.ErrInvalidWorkflowManifest,
}
// workflowStepErrorContext contains context needed to build workflow step errors.
type workflowStepErrorContext struct {
WorkflowPath string
WorkflowBasePath string
Workflow string
StepName string
Command string
CommandType string
FinalStack string
}
// buildWorkflowStepError builds an error with resume hints when a workflow step fails.
func buildWorkflowStepError(err error, ctx *workflowStepErrorContext) error {
log.Debug("Workflow failed", "error", err)
// Remove the workflow base path, stacks/workflows.
workflowFileName := strings.TrimPrefix(filepath.ToSlash(ctx.WorkflowPath), filepath.ToSlash(ctx.WorkflowBasePath))
// Remove the leading slash.
workflowFileName = strings.TrimPrefix(workflowFileName, "/")
// Remove the file extension.
workflowFileName = strings.TrimSuffix(workflowFileName, filepath.Ext(workflowFileName))
resumeCommand := fmt.Sprintf(
"%s workflow %s -f %s --from-step '%s'",
config.AtmosCommand,
ctx.Workflow,
workflowFileName,
ctx.StepName,
)
// Add stack parameter to resume command if a stack was used.
if ctx.FinalStack != "" {
resumeCommand = fmt.Sprintf("%s -s '%s'", resumeCommand, ctx.FinalStack)
}
failedCmd := ctx.Command
if ctx.CommandType == config.AtmosCommand {
failedCmd = config.AtmosCommand + " " + ctx.Command
// Add stack parameter to failed command if a stack was used.
if ctx.FinalStack != "" {
failedCmd = fmt.Sprintf("%s -s '%s'", failedCmd, ctx.FinalStack)
}
}
// Build error with context about the failed command.
// Use fmt.Errorf with %w to wrap the underlying error while adding ErrWorkflowStepFailed to the chain.
// This preserves both the error sentinel for errors.Is() checks and the underlying error's exit code.
wrappedErr := fmt.Errorf("%w: %w", errUtils.ErrWorkflowStepFailed, err)
// Now build the error with explanation and hints using the wrapped error.
// This preserves the error chain while adding formatted context.
// Commands are wrapped in code fences for proper formatting and copy-paste.
// Single quotes are used for shell safety (step names and stacks can contain spaces).
builder := errUtils.Build(wrappedErr).
WithTitle("Workflow Error").
WithExplanationf("The following command failed to execute:\n\n```shell\n%s\n```", failedCmd).
WithHintf("To resume the workflow from this step, run:\n\n```shell\n%s\n```", resumeCommand)
// Extract exit code from the underlying error if available.
if exitCode := errUtils.GetExitCode(err); exitCode != 0 {
builder = builder.WithExitCode(exitCode)
}
return builder.Err()
}
// prepareStepEnvironment prepares environment variables for a workflow step.
// baseEnv should already contain system env + global env + toolchain PATH.
// This function merges workflow env, persistent env-step values, and step env on
// top, then handles auth if needed.
// Returns the environment variables to use for the step.
func prepareStepEnvironment(
baseEnv []string,
stepIdentity string,
stepName string,
authManager auth.AuthManager,
workflowEnvMap map[string]string,
persistentEnvMap map[string]string,
stepEnvMap map[string]string,
) ([]string, error) {
// Make a copy of baseEnv to avoid modifying the caller's slice.
stepEnv := make([]string, len(baseEnv))
copy(stepEnv, baseEnv)
// Merge workflow, persistent env-step, and step env vars into a single map.
// Later layers take precedence, so a current step's env can override a value
// established by an earlier env step.
// This ensures duplicate keys are resolved before adding to the environment.
mergedEnv := make(map[string]string, len(workflowEnvMap)+len(persistentEnvMap)+len(stepEnvMap))
for k, v := range workflowEnvMap {
mergedEnv[k] = v
}
for k, v := range persistentEnvMap {
mergedEnv[k] = v
}
for k, v := range stepEnvMap {
mergedEnv[k] = v
}
if pathOverride, ok := mergedEnv["PATH"]; ok {
// Workflow templates commonly extend PATH with the process PATH, for example
// `PATH: /workspace/.context/bin:{{ env "PATH" }}`. At this point baseEnv
// has already added the workflow toolchain directories, so replacing PATH
// would otherwise make declared tools unavailable to the step.
mergedEnv["PATH"] = mergeWorkflowPath(pathOverride, lastEnvironmentValue(baseEnv, "PATH"))
}
if len(mergedEnv) > 0 {
stepEnv = append(stepEnv, envpkg.ConvertMapToSlice(mergedEnv)...)
}
// No identity specified, use base environment (system + global + toolchain + workflow + persistent + step env).
if stepIdentity == "" {
return stepEnv, nil
}
if authManager == nil {
return nil, errUtils.Build(errUtils.ErrAuthManager).
WithExplanation("auth manager is not initialized").
WithContext("identity", stepIdentity).
WithContext("step", stepName).
Err()
}
ctx := context.Background()
// Try to use cached credentials first (passive check, no prompts).
// Only authenticate if cached credentials are not available or expired.
if _, err := authManager.GetCachedCredentials(ctx, stepIdentity); err != nil {
log.Debug("No valid cached credentials found, authenticating", "identity", stepIdentity, "error", err)
// No valid cached credentials - perform full authentication.
if _, err = authManager.Authenticate(ctx, stepIdentity); err != nil {
// Check for user cancellation - return clean error without wrapping.
if errors.Is(err, errUtils.ErrUserAborted) {
return nil, errUtils.ErrUserAborted
}
return nil, fmt.Errorf("%w for identity %q in step %q: %w", errUtils.ErrAuthenticationFailed, stepIdentity, stepName, err)
}
}
// Prepare shell environment with authentication credentials.
// Pass stepEnv (system + global + toolchain + workflow + step) to let auth configure credentials.
authEnv, authErr := authManager.PrepareShellEnvironment(ctx, stepIdentity, stepEnv)
if authErr != nil {
return nil, fmt.Errorf("%w: failed to prepare shell environment for identity %q in step %q: %w", errUtils.ErrAuthenticationFailed, stepIdentity, stepName, authErr)
}
stepEnv = authEnv
log.Debug("Prepared environment with identity", "identity", stepIdentity, "step", stepName)
return stepEnv, nil
}
// lastEnvironmentValue returns the effective value for key in env, where later
// entries take precedence. This matches the environment semantics used for
// subprocesses and lets a toolchain PATH override the inherited system PATH.
func lastEnvironmentValue(env []string, key string) string {
var value string
for _, entry := range env {
entryKey, entryValue, ok := strings.Cut(entry, "=")
if ok && strings.EqualFold(entryKey, key) {
value = entryValue
}
}
return value
}
// mergeWorkflowPath combines a workflow PATH override with the already
// toolchain-augmented PATH. When both values share a suffix, that suffix is
// retained once and toolchain directories are placed after the custom prefix.
func mergeWorkflowPath(overridePath string, toolchainPath string) string {
if overridePath == "" || toolchainPath == "" {
return overridePath
}
separator := string(os.PathListSeparator)
overrideEntries := strings.Split(overridePath, separator)
toolchainEntries := strings.Split(toolchainPath, separator)
commonSuffix := 0
for commonSuffix < len(overrideEntries) && commonSuffix < len(toolchainEntries) {
overrideEntry := overrideEntries[len(overrideEntries)-1-commonSuffix]
toolchainEntry := toolchainEntries[len(toolchainEntries)-1-commonSuffix]
if overrideEntry != toolchainEntry {
break
}
commonSuffix++
}
merged := make([]string, 0, len(overrideEntries)+len(toolchainEntries)-commonSuffix)
merged = append(merged, overrideEntries[:len(overrideEntries)-commonSuffix]...)
merged = append(merged, toolchainEntries[:len(toolchainEntries)-commonSuffix]...)
merged = append(merged, overrideEntries[len(overrideEntries)-commonSuffix:]...)
return strings.Join(merged, separator)
}
// IsKnownWorkflowError returns true if the error matches any known workflow error.
// This includes ExitCodeError which indicates a subcommand failure that's already been reported.
func IsKnownWorkflowError(err error) bool {
// Check if it's an ExitCodeError - these are already reported by the subcommand
var exitCodeErr errUtils.ExitCodeError
if errors.As(err, &exitCodeErr) {
return true
}
// Check known workflow errors
for _, knownErr := range KnownWorkflowErrors {
if errors.Is(err, knownErr) {
return true
}
}
return false
}
// checkAndMergeDefaultIdentity checks if there's a default identity configured in atmos.yaml or stack configs.
// If a default identity is found in stack configs, it merges it into atmosConfig.Auth.
// Stack defaults take precedence over atmos.yaml defaults (following Atmos inheritance model).
// Returns true if a default identity exists after merging.
func checkAndMergeDefaultIdentity(atmosConfig *schema.AtmosConfiguration) bool {
if len(atmosConfig.Auth.Identities) == 0 {
return false
}
// Always load stack configs - stack defaults take precedence over atmos.yaml.
stackDefaults, err := config.LoadStackAuthDefaults(atmosConfig)
if err != nil {
// On error, fall back to checking atmos.yaml defaults.
for _, identity := range atmosConfig.Auth.Identities {
if identity.Default {
return true
}
}
return false
}
// Merge stack defaults into auth config (stack takes precedence).
if len(stackDefaults) > 0 {
config.MergeStackAuthDefaults(&atmosConfig.Auth, stackDefaults)
}
// Check if we have a default after merging.
for _, identity := range atmosConfig.Auth.Identities {
if identity.Default {
return true
}
}
return false
}
type workflowCommandFilters struct {
tags []string
labels string
}
// ExecuteWorkflow executes an Atmos workflow.
func ExecuteWorkflow(
atmosConfig schema.AtmosConfiguration,
workflow string,
workflowPath string,
workflowDefinition *schema.WorkflowDefinition,
dryRun bool,
commandLineStack string,
fromStep string,
commandLineIdentity string,
commandLineFilters ...workflowCommandFilters,
) (retErr error) {
defer perf.Track(&atmosConfig, "exec.ExecuteWorkflow")()
commandFilters := workflowCommandFilters{}
if len(commandLineFilters) > 0 {
commandFilters = commandLineFilters[0]
}
var activeContainer *workflowPkg.ContainerSession
defer func() {
if activeContainer == nil {
return
}
if cleanupErr := activeContainer.Cleanup(retErr == nil); cleanupErr != nil && retErr == nil {
retErr = cleanupErr
}
}()
// Reset step executor state at the start of each workflow to ensure clean variable scope.
ResetStepExecutorState()
// Initialize step executor with stage count for stage step type.
initStepExecutorWithStages(workflowDefinition)
// Resolve inline workflow step commands and env through the same template
// engine custom command steps use (full Atmos renderer + multi-pass), so
// {{ .steps.* }} / {{ .env.* }} / {{ .flags.* }} and template functions
// behave identically in both. Flags are protected so a flag value containing
// template markers is not re-evaluated on later passes (mirrors cmd_utils).
workflowVars := stepExecutorState.Variables()
workflowVars.SetTemplateRenderer(func(name, input string, data any) (string, error) {
return ProcessTmpl(&atmosConfig, name, input, data, false)
})
workflowVars.SetTemplatePasses(workflowTemplatePasses)
workflowVars.ProtectTemplateRoots("Flags", "flags")
// Evaluate value-producing YAML functions (!env, !exec) in interactive step
// fields (default/prompt/placeholder/options). Workflow manifests are parsed
// with UnmarshalYAML, which leaves these as literal "!env ..." strings; this
// lets interactive steps source defaults from the environment in CI.
if err := resolveWorkflowStepFunctions(&atmosConfig, workflowDefinition); err != nil {
return err
}
steps := workflowDefinition.Steps
if len(steps) == 0 {
return errUtils.Build(errUtils.ErrWorkflowNoSteps).
WithTitle(WorkflowErrTitle).
WithExplanationf("Workflow `%s` is empty and requires at least one step to execute.", workflow).
WithContext("workflow", workflow).
WithExitCode(1).
Err()
}
// Check if the workflow steps have the `name` attribute
checkAndGenerateWorkflowStepNames(workflowDefinition)
// Background container services started by `background: true` steps are tracked in
// a run-scoped registry. runCtx propagates cancellation (Ctrl-C / step failure) to
// readiness waits and teardown. Any service still running when the workflow ends —
// or when it exits early on error — is auto-torn-down here (implicit, since a service
// never exits on its own); an explicit `cancel` step removes it from the registry first.
runCtx, cancelRun := context.WithCancel(context.Background())
defer cancelRun()
bgRegistry := background.NewRegistry()
// bgGated records background steps that have already passed their readiness gate,
// so the implicit gate before each foreground step does not re-probe them.
bgGated := map[string]bool{}
// Scope background container instance names per run. An explicit `--stack` is honored
// verbatim (override path); otherwise use a run-specific id rather than the shared
// workflow/stack name, so concurrent executions of the same workflow do not collide
// on the same container.
bgStack := commandLineStack
if bgStack == "" {
bgStack = "run-" + uuid.NewString()[:bgRunIDLen]
}
bgRunner := &workflowPkg.ContainerRunner{Stack: bgStack, DryRun: dryRun}
defer func() {
if stopErr := bgRegistry.StopAll(runCtx); stopErr != nil {
retErr = errors.Join(retErr, stopErr)
}
}()
// Validate exec steps before executing anything: an exec step replaces
// the Atmos process, so it must be the final step and must not set
// supervisor-only fields (tty, interactive, retry, timeout, output).
if err := schema.ValidateWorkflowSteps(workflowDefinition.Steps); err != nil {
return errUtils.Build(err).
WithTitle(WorkflowErrTitle).
WithHint("Check workflow step type, nested steps, needs dependencies, and control-step output/fail configuration").
WithContext("workflow", workflow).
WithExitCode(1).
Err()
}
log.Debug("Executing workflow", "workflow", workflow, "path", workflowPath)
if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug {
err := u.PrintAsYAMLToFileDescriptor(&atmosConfig, workflowDefinition)
if err != nil {
return err
}
}
// If `--from-step` is specified, skip all the previous steps
if fromStep != "" {
steps = lo.DropWhile[schema.WorkflowStep](steps, func(step schema.WorkflowStep) bool {
return step.Name != fromStep
})
if len(steps) == 0 {
stepNames := lo.Map(workflowDefinition.Steps, func(step schema.WorkflowStep, _ int) string { return step.Name })
return errUtils.Build(errUtils.ErrInvalidFromStep).
WithTitle(WorkflowErrTitle).
WithExplanationf("The `--from-step` flag was set to `%s`, but this step does not exist in workflow `%s`.\n\n### Available steps:\n\n%s", fromStep, workflow, u.FormatList(stepNames)).
WithContext("from_step", fromStep).
WithContext("workflow", workflow).
WithExitCode(1).
Err()
}
}
// Ensure toolchain dependencies are installed and build PATH for workflow steps.
tenv, err := dependencies.ForWorkflow(&atmosConfig, workflowDefinition)
if err != nil {
return err
}
// Create auth manager if any runnable step has an identity or if command-line identity is specified.
// We check once upfront to avoid repeated initialization.
var authManager auth.AuthManager
var authStackInfo *schema.ConfigAndStacksInfo
needsAuth := false
for i := range steps {
step := &steps[i]
if err := schema.ValidateStepCondition(step.When); err != nil {
return err
}
runs, err := step.When.EvaluateWithImplicitSuccessE(workflowPkg.BuildConditionContext(workflow, workflowDefinition, step, commandLineStack, workflowDefinition.Env))
if err != nil {
return err
}
if !runs {
continue
}
if commandLineIdentity != "" || strings.TrimSpace(step.Identity) != "" {
needsAuth = true
break
}
}
if needsAuth {
// Create a ConfigAndStacksInfo for the auth manager to populate with AuthContext.
// This enables YAML template functions to access authenticated credentials.
authStackInfo = &schema.ConfigAndStacksInfo{
AuthContext: &schema.AuthContext{},
}
credStore := credentials.NewCredentialStoreWithConfig(&atmosConfig.Auth)
validator := validation.NewValidator()
var err error
authManager, err = auth.NewAuthManager(&atmosConfig.Auth, credStore, validator, authStackInfo, atmosConfig.CliConfigPath)
if err != nil {
return fmt.Errorf("%w: %w", errUtils.ErrFailedToInitializeAuthManager, err)
}
}
// Construct base environment once: system env + global env + toolchain PATH.
// This is reused for all steps, with workflow/step env vars merged on top per step.
baseEnv := envpkg.MergeGlobalEnv(os.Environ(), atmosConfig.Env)
baseEnv = append(baseEnv, tenv.EnvVars()...)
persistentEnv := make(map[string]string)
// Initialize show renderer for header/flags display.
showRenderer := workflowPkg.NewShowRenderer()
// Build flags map for header display.
flags := buildWorkflowFlagsMap(commandLineStack, commandLineIdentity, dryRun, fromStep)
// Initialize progress renderer if enabled.
totalSteps := len(steps)
progressRenderer := workflowPkg.NewProgressRenderer(workflowDefinition, totalSteps)
// Render header before first step (if enabled).
showRenderer.RenderHeaderIfNeeded(workflowDefinition, workflow, flags)
var workflowErr error
conditionStatus := schema.ConditionPredicateSuccess
for stepIdx, step := range steps {
conditionContext := workflowPkg.BuildConditionContext(workflow, workflowDefinition, &step, commandLineStack, workflowDefinition.Env)
conditionContext.Status = conditionStatus
runs, err := step.When.EvaluateWithImplicitSuccessE(conditionContext)
if err != nil {
return err
}
if !runs {
log.Debug("Skipping workflow step, `when` condition did not match", "step", step.Name)
continue
}
// Render step label with optional count prefix and progress bar.
// When progress is enabled, combine label + progress on a single line (no newline).
// When progress is disabled, only show the label if show.count is enabled; otherwise
// emit nothing so default output stays backward compatible (show features are opt-in).
showCfg := stepPkg.GetShowConfig(&step, workflowDefinition)
label := stepPkg.FormatStepLabel(&step, workflowDefinition, stepIdx, totalSteps)
if progressRenderer.IsEnabled() {
progressRenderer.Update(stepIdx+1, step.Name)
progressRenderer.RenderWithLabel(label) // No newline - will be cleared.
} else if stepPkg.ShowCount(showCfg) {
ui.Writeln(label)
}
command := strings.TrimSpace(step.Command)
commandType := strings.TrimSpace(step.Type)
stepIdentity := strings.TrimSpace(step.Identity)
workflowStack := strings.TrimSpace(workflowDefinition.Stack)
stepStack := strings.TrimSpace(step.Stack)
finalStack := ""
// The workflow `stack` attribute overrides the stack in the `command` (if specified).
// The step `stack` attribute overrides the stack in the `command` and the workflow `stack` attribute.
// The stack defined on the command line has the highest priority.
if workflowStack != "" {
finalStack = workflowStack
}
if stepStack != "" {
finalStack = stepStack
}
if commandLineStack != "" {
finalStack = commandLineStack
}
// If step doesn't specify identity, use command-line identity (if provided).
if stepIdentity == "" && commandLineIdentity != "" {
stepIdentity = commandLineIdentity
}
log.Debug("Executing workflow step", "step", stepIdx, "name", step.Name, "command", command)
if commandType == "" {
commandType = "atmos"
}
// Resolve step-variable templates in workflow/step env values (parity with
// custom command steps) so a value like `X: "{{ .steps.select.value }}"`
// is populated before it reaches the subprocess.
resolvedWorkflowEnv, resolvedStepEnv, err := resolveWorkflowStepEnvs(workflowDefinition.Env, step.Env, baseEnv)
if err != nil {
if workflowErr == nil {
workflowErr = err
} else {
workflowErr = errors.Join(workflowErr, err)
}
conditionStatus = schema.ConditionPredicateFailure
continue
}
// Prepare environment variables: start with baseEnv (system + global + toolchain).
// Then merge workflow-level, persistent env-step, and step-level env vars.
// If identity is specified, also authenticate and add credentials.
stepEnv, err := prepareStepEnvironment(baseEnv, stepIdentity, step.Name, authManager, resolvedWorkflowEnv, persistentEnv, resolvedStepEnv)
if err != nil {
if workflowErr == nil {
workflowErr = err
} else {
workflowErr = errors.Join(workflowErr, err)
}
conditionStatus = schema.ConditionPredicateFailure
continue
}
workDir := workflowPkg.CalculateWorkingDirectory(workflowDefinition, &step, atmosConfig.BasePath)
if workDir == "" {
workDir = "."
}
// Clear progress line and re-render as permanent record before step execution.
// This ensures progress line appears as header, then step output below it.
if progressRenderer.IsEnabled() {
ui.ClearLine()
progressRenderer.RenderPermanent(label)
}
// Reject unknown step types before opening a log group so the precise
// validation error is returned directly (not wrapped as a step failure).
if commandType != "shell" &&
commandType != schema.TaskTypeExec &&
commandType != "atmos" &&
commandType != schema.TaskTypeWait &&
commandType != schema.TaskTypeWaitAll &&
commandType != schema.TaskTypeCancel &&
commandType != schema.TaskTypeParallel &&
commandType != schema.TaskTypeMatrix &&
!stepPkg.IsExtendedStepType(commandType) {
return errUtils.Build(errUtils.ErrInvalidWorkflowStepType).
WithTitle(WorkflowErrTitle).
WithExplanationf("Workflow `%s` step `%s` uses unsupported type `%s`.", workflow, step.Name, commandType).
WithContext("workflow", workflow).
WithContext("step", step.Name).
WithHintf("Step type '%s' is not supported", commandType).
WithHint("Each step must specify a valid type: 'atmos', 'shell', 'script', 'exec', or an interactive type like 'input', 'confirm', 'choose'").
WithExitCode(1).
Err()
}
// Resolve step-variable templates ({{ .steps.* }} / {{ .env.* }} /
// {{ .flags.* }}) in inline command-bearing steps (shell/atmos/exec) so a
// value captured by an earlier step reaches the command — parity with
// custom command steps.
if workflowCommandSupportsTemplating(commandType) {
resolvedCommand, resolveErr := resolveWorkflowStepCommand(command, stepEnv)
if resolveErr != nil {
// errors.Join ignores a nil left operand, so this both starts and
// accumulates the workflow error without an extra nil check.
workflowErr = errors.Join(workflowErr, resolveErr)
conditionStatus = schema.ConditionPredicateFailure
continue
}
command = resolvedCommand
}
// If this step will be enclosed in a CI log group, mark the subprocess
// environment so a nested `atmos` invocation skips unsupported nested
// grouping.
if commandType != schema.TaskTypeExec && ci.ShouldPropagateLogGroupSentinel(&atmosConfig, ci.DimensionStep) {
stepEnv = append(stepEnv, ci.LogGroupSentinelEnv())
}
var commandResult *stepPkg.StepResult
runCommandStep := func(run func(stdout, stderr io.Writer) error) error {
var runErr error
commandResult, runErr = stepPkg.ExecuteCommandResult(step.Name, run)
return runErr
}
executeStep := func() error {
// Background steps (start/wait/wait-all/cancel) are coordinated by the
// run-scoped registry; everything else falls through to the normal switch.
handled := true
switch {
case step.BackgroundAsync:
// Start the container service detached (non-blocking): consecutive background
// steps come up concurrently. Readiness is enforced by the implicit gate before
// the next foreground step (and by `wait`/`wait-all`).
err = workflowPkg.StartBackground(runCtx, bgRegistry, bgRunner, &steps[stepIdx], stepEnv)
case commandType == schema.TaskTypeWait:
err = workflowPkg.WaitBackground(runCtx, bgRegistry, step.For)
if err == nil {
for _, name := range step.For {
bgGated[name] = true
}
}
case commandType == schema.TaskTypeWaitAll:
err = workflowPkg.WaitAllBackground(runCtx, bgRegistry)
if err == nil {
for _, name := range bgRegistry.Names() {
bgGated[name] = true
}
}
case commandType == schema.TaskTypeCancel:
err = workflowPkg.CancelBackground(runCtx, bgRegistry, step.For)
for _, name := range step.For {
delete(bgGated, name)
}
default:
handled = false
}
// Implicit readiness gate: before running a foreground step, block until every
// background service started so far is healthy. Already-gated services are skipped.
if !handled && err == nil {
err = workflowPkg.GatePendingBackground(runCtx, bgRegistry, bgGated)
}
switch {
case handled:
// already executed above
case err != nil:
// A failed readiness gate skips this step's foreground work; the error
// handler below reports it.
case commandType == schema.TaskTypeParallel, commandType == schema.TaskTypeMatrix:
err = executeWorkflowControlStep(context.Background(), &workflowControlContext{
atmosConfig: atmosConfig,
workflowDefinition: workflowDefinition,
dryRun: dryRun,
commandLineStack: commandLineStack,
commandLineTags: commandFilters.tags,
commandLineLabels: commandFilters.labels,
commandLineIdentity: stepIdentity,
baseEnv: baseEnv,
persistentEnv: persistentEnv,
authManager: authManager,
}, &steps[stepIdx])
case commandType == "shell":
// Render command before execution if show.command is enabled.
// Steps with tty/interactive attach the user's terminal; plain
// steps keep the existing masked shell-interpreter behavior.
stepPkg.RenderCommand(&step, workflowDefinition, command)
commandName := fmt.Sprintf("%s-step-%d", workflow, stepIdx)
switch {
case workflowPkg.StepContainerOverride(&step):
err = retry.Do(context.Background(), step.Retry, func() error {
return runCommandStep(func(stdout, stderr io.Writer) error {
return workflowPkg.RunStepContainerOverride(context.Background(), &workflowPkg.ContainerStepParams{
Workflow: workflow,
WorkflowPath: workflowPath,
BasePath: atmosConfig.BasePath,
WorkflowDef: workflowDefinition,
Step: &step,
HostWorkDir: workDir,
Command: command,
StepEnv: stepEnv,
RuntimeEnv: stepEnv,
DryRun: dryRun,
StdoutCapture: stdout,
StderrCapture: stderr,
})
})
})
case workflowDefinition.Container != nil && workflowDefinition.Container.IsEnabled() && !workflowPkg.StepContainerDisabled(&step):
if activeContainer == nil {
activeContainer, err = workflowPkg.StartWorkflowContainer(context.Background(), &workflowPkg.ContainerStepParams{
Workflow: workflow,
WorkflowPath: workflowPath,
BasePath: atmosConfig.BasePath,
WorkflowDef: workflowDefinition,
RuntimeEnv: stepEnv,
DryRun: dryRun,
})
if err != nil {
break
}
}
err = retry.Do(context.Background(), step.Retry, func() error {
return runCommandStep(func(stdout, stderr io.Writer) error {
return activeContainer.ExecShell(context.Background(), &workflowPkg.ContainerStepParams{
Step: &step,
WorkflowDef: workflowDefinition,
HostWorkDir: workDir,
Command: command,
StepEnv: stepEnv,
StdoutCapture: stdout,
StderrCapture: stderr,
})
})
})
default:
err = retry.Do(context.Background(), step.Retry, func() error {
return runCommandStep(func(stdoutCapture, stderrCapture io.Writer) error {
return process.RunShellStep(context.Background(), &process.ShellSessionSpec{
Command: command,
Name: commandName,
Dir: workDir,
Env: stepEnv,
TTY: step.Tty,
Interactive: step.Interactive,
DryRun: dryRun,
}, func() error {
return ExecuteShellWithWriters(&ExecuteShellSpec{
Command: command,
Name: commandName,
Dir: workDir,
EnvVars: stepEnv,
DryRun: dryRun,
Stdout: io.MultiWriter(ioLayer.MaskWriter(os.Stdout), stdoutCapture),
Stderr: io.MultiWriter(ioLayer.MaskWriter(os.Stderr), stderrCapture),
})
})
})
})
}
case commandType == schema.TaskTypeExec:
// Replace the Atmos process with the command (shell exec semantics).
// Validated earlier to be the final step; no retry wrapper (the
// process is replaced, so a retry could never run).
stepPkg.RenderCommand(&step, workflowDefinition, command)
err = process.ReplaceShellSession(&process.ExecSpec{
Command: command,
Name: fmt.Sprintf("%s-step-%d", workflow, stepIdx),
Dir: ".",
Env: stepEnv,
DryRun: dryRun,
})
case commandType == "atmos":
// Parse command using shell.Fields for proper quote handling.
// This correctly handles arguments like -var="foo=bar" by stripping quotes.
args, parseErr := shell.Fields(command, nil)
if parseErr != nil {
log.Debug("Shell parsing failed, falling back to strings.Fields", "error", parseErr, "command", command)
args = strings.Fields(command)
}
args = workflowPkg.AppendAtmosStepFlags(args, workflowPkg.AtmosStepFlags{
Stack: finalStack,
Tags: commandFilters.tags,
Labels: commandFilters.labels,
})
if finalStack != "" {
log.Debug("Using stack", "stack", finalStack)
}
// Build display command from the final arguments so it matches execution.
displayCmd := "atmos " + strings.Join(args, " ")
// Render command before execution if show.command is enabled.
stepPkg.RenderCommand(&step, workflowDefinition, displayCmd)
ui.Infof("Executing command: `atmos %s`", command)
err = retry.Do(context.Background(), step.Retry, func() error {
return runCommandStep(func(stdout, stderr io.Writer) error {
return ExecuteShellCommand(
atmosConfig,
"atmos",
args,
".",
stepEnv,
dryRun,
"",
WithStdoutCapture(stdout),
WithStderrCapture(stderr),
)
})
})
default:
// Check if this is an extended step type (input, confirm, choose, etc.).
if !stepPkg.IsExtendedStepType(commandType) {
return errUtils.Build(errUtils.ErrInvalidWorkflowStepType).
WithTitle(WorkflowErrTitle).
WithExplanationf("Workflow `%s` step `%s` uses unsupported type `%s`.", workflow, step.Name, commandType).
WithContext("workflow", workflow).
WithContext("step", step.Name).
WithHintf("Step type '%s' is not supported", commandType).
WithHint("Each step must specify a valid type: 'atmos', 'shell', 'script', 'exec', or an interactive type like 'input', 'confirm', 'choose'").
WithExitCode(1).
Err()
}
if commandType == schema.TaskTypeScript {
stepPkg.RenderCommand(&step, workflowDefinition, process.FormatScriptDisplay(step.Interpreter, step.Script))
switch {
case workflowPkg.StepContainerOverride(&step):
err = retry.Do(context.Background(), step.Retry, func() error {
return workflowPkg.RunStepContainerOverride(context.Background(), &workflowPkg.ContainerStepParams{
Workflow: workflow,
WorkflowPath: workflowPath,
BasePath: atmosConfig.BasePath,
WorkflowDef: workflowDefinition,
Step: &step,
HostWorkDir: workDir,
Command: process.FormatScriptDisplay(step.Interpreter, step.Script),
StepEnv: stepEnv,
RuntimeEnv: stepEnv,
DryRun: dryRun,
})
})
case workflowDefinition.Container != nil && workflowDefinition.Container.IsEnabled() && !workflowPkg.StepContainerDisabled(&step):
if activeContainer == nil {
activeContainer, err = workflowPkg.StartWorkflowContainer(context.Background(), &workflowPkg.ContainerStepParams{
Workflow: workflow,
WorkflowPath: workflowPath,
BasePath: atmosConfig.BasePath,
WorkflowDef: workflowDefinition,
RuntimeEnv: stepEnv,
DryRun: dryRun,
})
if err != nil {
break
}
}
err = retry.Do(context.Background(), step.Retry, func() error {
return activeContainer.ExecShell(context.Background(), &workflowPkg.ContainerStepParams{
Step: &step,
WorkflowDef: workflowDefinition,
HostWorkDir: workDir,
Command: process.FormatScriptDisplay(step.Interpreter, step.Script),
StepEnv: stepEnv,
})
})
default:
err = executeExtendedStep(context.Background(), &steps[stepIdx], workflowDefinition, stepEnv, extendedStepOptions{
DryRun: dryRun,
FinalStack: finalStack,
AtmosConfig: &atmosConfig,
})
}
break
}
err = executeExtendedStep(context.Background(), &steps[stepIdx], workflowDefinition, stepEnv, extendedStepOptions{
DryRun: dryRun,
FinalStack: finalStack,
AtmosConfig: &atmosConfig,
ToolchainPATH: tenv.PATH(),
AuthManager: authManager,
})
}
if err != nil {
return err
}
return stepPkg.StoreCommandResult(workflowVars, step.Name, step.Outputs, commandResult)
}
// Wrap each step's output in a collapsible CI log group when grouping is
// active. Exec steps run bare because a successful Unix exec never returns
// to close a deferred group.
err = stepPkg.RunGroupedForType(&atmosConfig, step.Name, command, commandType, executeStep)
if err != nil {
// Terminal-handoff steps (tty/interactive/exec) that exit non-zero
// propagate the code silently, like a shell - don't wrap them in a
// themed workflow error (which would query the terminal post-session).
var silentExit errUtils.ExitCodeError
if errors.As(err, &silentExit) && silentExit.Silent {
return err
}
stepErr := err
if !errors.Is(err, errUtils.ErrInvalidWorkflowStepType) {
stepErr = buildWorkflowStepError(err, &workflowStepErrorContext{
WorkflowPath: workflowPath,
// Must be the SAME anchor workflowPath was actually joined against
// (workflow.go), not the raw, always-relative atmosConfig.Workflows.BasePath
// -- otherwise the TrimPrefix below in buildWorkflowStepError silently fails
// to strip it whenever workflowPath ends up absolute (e.g. via the
// precomputed WorkflowsDirAbsolutePath), leaving the resume-command hint
// showing a garbled path instead of the plain workflow file name.
WorkflowBasePath: getWorkflowsDirToUse(&atmosConfig),
Workflow: workflow,
StepName: step.Name,
Command: command,
CommandType: commandType,
FinalStack: finalStack,
})
}
if workflowErr == nil {
workflowErr = stepErr
} else {
workflowErr = errors.Join(workflowErr, stepErr)
}
conditionStatus = schema.ConditionPredicateFailure
continue
}
if commandType == "env" && (step.Export == nil || *step.Export) {
for key := range step.Vars {
if value, ok := workflowVars.Env[key]; ok {
persistentEnv[key] = value
}
}
}
}
// Mark progress as done.
if progressRenderer.IsEnabled() {
progressRenderer.Done()
}
return workflowErr
}
// stepExecutorState holds persistent state for extended step execution within a workflow.
// This allows step results to be passed between steps for variable templating.
var stepExecutorState *stepPkg.StepExecutor
type extendedStepOptions struct {
DryRun bool
FinalStack string
AtmosConfig *schema.AtmosConfiguration
ToolchainPATH string
AuthManager auth.AuthManager
}
// executeExtendedStep runs an extended step type (input, confirm, choose, etc.).