Skip to content

fix(ansible): forward -- <args> passthrough to ansible-playbook - #2594

Merged
Andriy Knysh (aknysh) merged 5 commits into
cloudposse:mainfrom
mtb-xt:fix/ansible-double-dash-passthrough
Jun 11, 2026
Merged

Andriy Knysh (aknysh) merged 5 commits into
cloudposse:mainfrom
mtb-xt:fix/ansible-double-dash-passthrough

Conversation

@mtb-xt

@mtb-xt Marat Bakeev (mtb-xt) commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

what

  • Fix atmos ansible playbook <component> -s <stack> -- <ansible-args> failing with a misleading Unknown command \`` error.
  • playbookCmd now uses a separator-aware argument validator instead of cobra.ExactArgs(1): it requires exactly one positional component, counting only the arguments before a -- separator.
  • Adds regression tests for the -- passthrough path.

why

  • cobra.ExactArgs(1) counts every positional argument, including the ansible-playbook passthrough tokens captured after --. Any invocation using -- (e.g. -- --check, -- --tags web, -- --limit host) therefore tripped argument validation with 2+ "positional" args, and the root UsageFunc rendered that failure as an Unknown command error naming the component.
  • This made it impossible to forward native ansible-playbook flags, even though the command help documents [options] and points at the ansible-playbook CLI docs, and the executor (buildCommandArgs) already appends info.AdditionalArgsAndFlags to the command.
  • cobra.ArgsLenAtDash() returns -1 when no -- is present, so the validator still checks the full slice for the common case and keeps the original "exactly one component" contract.

Before

$ atmos ansible playbook myapp -s prod -- --check
Error: Unknown command `myapp` for `atmos ansible playbook`

After

$ atmos ansible playbook myapp -s prod --dry-run -- --check
ansible-playbook --extra-vars @/.../prod-myapp.ansible.vars.yaml -i inventory/hosts.yml --check playbook.yml

references

Summary by CodeRabbit

  • New Features

    • Forward additional args after -- verbatim to the underlying playbook command; positional validation ignores these passthrough args.
  • Bug Fixes

    • Require exactly one component before -- and return clear validation errors when missing or duplicated.
  • Tests

    • Added comprehensive tests for separator-aware parsing, validation, and passthrough behavior, including prompt-aware validation scenarios.

`atmos ansible playbook <component> -s <stack> -- --check` failed with a
misleading "Unknown command `<component>`" error instead of running the
playbook in check mode.

`playbookCmd` used `cobra.ExactArgs(1)`, which counts every positional
argument — including the ansible-playbook passthrough tokens captured after
`--`. So any invocation using `--` (e.g. `-- --check`) tripped argument
validation with 2+ "positional" args, and the root UsageFunc rendered that
failure as an "Unknown command" error naming the component.

Replace `ExactArgs(1)` with a separator-aware validator that counts only the
positional arguments before `--` (via `cobra.ArgsLenAtDash()`, which returns
-1 when no `--` is present). Arguments after `--` are already forwarded to
ansible-playbook by the executor (`buildCommandArgs`), so `-- --check`,
`-- --tags ...`, `-- --limit ...` now work as the command help documents.

Add regression tests covering the separator path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@atmos-pro

atmos-pro Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@github-actions github-actions Bot added the size/s Small size PR label Jun 10, 2026
@mtb-xt
Marat Bakeev (mtb-xt) marked this pull request as ready for review June 10, 2026 08:42
@mtb-xt
Marat Bakeev (mtb-xt) requested a review from a team as a code owner June 10, 2026 08:42
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9ce4c54a-c0dd-4a6b-8abc-fd92e7e0afea

📥 Commits

Reviewing files that changed from the base of the PR and between 81ae128 and 09a3d51.

📒 Files selected for processing (6)
  • cmd/ansible/ansible.go
  • cmd/ansible/ansible_test.go
  • cmd/ansible/playbook.go
  • pkg/flags/positional_args_builder.go
  • pkg/flags/separator.go
  • pkg/flags/separator_test.go

📝 Walkthrough

Walkthrough

The atmos ansible playbook command now validates exactly one component argument while allowing arbitrary arguments after -- to pass through to ansible-playbook. A custom validator replaces cobra.ExactArgs(1), counts only pre-separator arguments, and returns a wrapped error when component count deviates from one.

Changes

Ansible playbook argument validation

Layer / File(s) Summary
Separator utilities
pkg/flags/separator.go
Adds SplitArgsAtDash(cmd,args) and SeparatorAwareValidator to slice args at Cobra's -- index and validate only pre--- positional tokens.
PositionalArgsBuilder integration
pkg/flags/positional_args_builder.go
Wraps generated Cobra validators with SeparatorAwareValidator and updates prompt-aware validators to consider only pre--- args.
Playbook command usage and validator wiring
cmd/ansible/playbook.go
Replace cobra.ExactArgs(1) with a separator-aware positional-args builder, declare component positional, and update playbookCmd.Use.
Init parsing wiring
cmd/ansible/ansible.go
initConfigAndStacksInfo now uses flags.SplitArgsAtDash to set ComponentFromArg from pre--- and AdditionalArgsAndFlags including passthrough post--- tokens.
Flags unit tests
pkg/flags/separator_test.go
Tests for SplitArgsAtDash, SeparatorAwareValidator, and PositionalArgsBuilder behaviors across nil-cmd, no---, -- present, and prompt-aware cases.
Ansible command tests
cmd/ansible/ansible_test.go
Updates playbook Use expectation, removes old helper test, adds TestInitConfigAndStacksInfoDoubleDash and TestPlaybookCmdArgsValidationWithDoubleDash covering pre-/post--- semantics and validation failures.

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • cloudposse/atmos#1990: Also adjusts CLI handling of the -- end-of-options separator and adds related tests.

Suggested reviewers

  • osterman
  • aknysh
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly matches the main change: enabling -- passthrough to ansible-playbook by updating argument validation and ingestion.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/ansible/ansible_test.go`:
- Around line 500-504: The test should assert the specific error type instead of
only checking for any error: change the t.Run body to capture err := c.Execute()
and verify it matches errUtils.ErrInvalidComponentArgument using either
assert.ErrorIs(t, err, errUtils.ErrInvalidComponentArgument) or assert.True(t,
errors.Is(err, errUtils.ErrInvalidComponentArgument)); update imports to include
"errors" if using errors.Is and ensure the package import for errUtils is added.
Locate the test using newCmd() and the t.Run named "rejects two components
before --" to apply this change.
- Around line 494-498: Update the test "rejects missing component before --" to
not only assert an error but to verify the error is
errUtils.ErrInvalidComponentArgument: run c.Execute(), store the returned error,
assert it's non-nil, and then use errors.Is(err,
errUtils.ErrInvalidComponentArgument) (or equivalent assert) to check the
specific error type; also add the "errors" import and ensure the existing
errUtils import is present in the test file.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d5b29744-6ab8-4349-86c4-dedee302fb79

📥 Commits

Reviewing files that changed from the base of the PR and between 3c1aba3 and f5491ef.

📒 Files selected for processing (2)
  • cmd/ansible/ansible_test.go
  • cmd/ansible/playbook.go

Comment thread cmd/ansible/ansible_test.go Resolved
Comment thread cmd/ansible/ansible_test.go Resolved
Address CodeRabbit review on cloudposse#2594: the negative cases in
TestPlaybookCmdArgsValidationWithDoubleDash asserted only that an error
occurred. Assert the wrapped sentinel errUtils.ErrInvalidComponentArgument
via assert.ErrorIs so a future change returning a different error is caught.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 10, 2026
@osterman

Copy link
Copy Markdown
Member

CodeRabbit (@coderabbitai) are we sure this fix is not curve fitting? The problem I see is that it's in the flag handler itself. And that the args passed in both in the original code (which had exact) and in the patch, do not get their args from the flag handler. I'm pretty sure we have a function for this use case. Can you reference our flag handler agent/skills and compared to other commands using the flag handler. Either way the fix belongs in flag handler if there is not already a fix there.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== Find flag handler / parser files ==="
fd -t f -e go | xargs grep -l "AdditionalArgsAndFlags" | head -30

echo ""
echo "=== How AdditionalArgsAndFlags is populated ==="
rg -n "AdditionalArgsAndFlags" --type go -C 3

echo ""
echo "=== ArgsLenAtDash usage across codebase ==="
rg -n "ArgsLenAtDash" --type go -C 3

echo ""
echo "=== Look for double-dash / passthrough handling in flag handler ==="
rg -n "ArgsLenAtDash\|passthrough\|double.dash\|dash\|-- " --type go -C 3 | head -80

echo ""
echo "=== Find the main flag/args parsing logic ==="
fd -t f -e go -g "*flag*" | head -20
fd -t f -e go -g "*arg*" | head -20
fd -t f -e go -g "*parse*" | head -20

Length of output: 70685


🏁 Script executed:

#!/bin/bash
echo "=== Show playbook.go current state ==="
cat cmd/ansible/playbook.go

echo ""
echo "=== Show the atmos info/exec structures that carry AdditionalArgsAndFlags ==="
rg -n "AdditionalArgsAndFlags" --type go -B 2 -A 2

echo ""
echo "=== Find where args after -- are parsed/captured in cobra commands ==="
rg -rn "Dash\|double.dash\|passthrough\|extraArgs\|extra_args" --type go -C 2 | head -100

echo ""
echo "=== Look at other commands that do passthrough (e.g., terraform, helmfile) ==="
fd -t f -e go -g "*terraform*" | head -10
fd -t f -e go -g "*helmfile*" | head -10

Length of output: 46173


🏁 Script executed:

#!/bin/bash
echo "=== Locate main args/flags parsing (likely in pkg or internal) ==="
rg -rn "func.*ParseArgs\|func.*parseArgs\|func.*BuildArgs\|func.*buildArgs\|func.*processArgs" --type go -C 3 | head -80

echo ""
echo "=== Find 'processConfigAndStacks' or similar entry points that populate info struct ==="
rg -rn "func.*processCmd\|func.*executeCmd\|func.*runCmd\|func.*Execute" --type go -C 2 | grep -v "_test.go" | head -60

echo ""
echo "=== Show how helmfile or terraform commands set up cobra Args validator ==="
fd -t f -e go -g "*helmfile*" | xargs grep -l "cobra\|Args" 2>/dev/null | head -5
fd -t f -e go -g "*terraform*" | xargs grep -l "cobra.ExactArgs\|cobra.ArgsLenAtDash\|validateArgs" 2>/dev/null | head -5

Length of output: 1213


🏁 Script executed:

#!/bin/bash
echo "=== Find the central flag/args handling - look for where passthrough args are gathered ==="
rg -rn "os\.Args\|flag\.Args\|ArgsLenAtDash\|Passthrough\|passThrough" --type go -C 3 | head -100

echo ""
echo "=== Check if there's a common 'execute' or 'run' function for vendor/component commands ==="
rg -rn "AdditionalArgsAndFlags\s*=" --type go -C 5 | head -80

echo ""
echo "=== Look at how info.AdditionalArgsAndFlags is set from cobra args ==="
rg -rn "info\." --type go -l | head -20
rg -rn "\.AdditionalArgsAndFlags\s*=" --type go -B 3 -A 3 | head -80

Length of output: 11392


🏁 Script executed:

#!/bin/bash
echo "=== Find the atmos exec info struct ==="
rg -rn "type.*Info\|AdditionalArgsAndFlags" --type go -C 5 | grep -A 10 "AdditionalArgsAndFlags" | head -80

echo ""
echo "=== Find where cobra args are processed into AdditionalArgsAndFlags ==="
rg -rn "AdditionalArgsAndFlags" --type go | head -30

echo ""
echo "=== Check the ansible execute/run functions for how args are gathered ==="
cat cmd/ansible/ansible.go 2>/dev/null || echo "no ansible.go"
ls cmd/ansible/

Length of output: 11520


🏁 Script executed:

#!/bin/bash
echo "=== List all files in cmd/ansible ==="
ls -la cmd/ansible/

echo ""
echo "=== Show buildCommandArgs function ==="
rg -rn "func buildCommandArgs\|func BuildCommandArgs" --type go -C 10 | head -60

echo ""
echo "=== Show how args are processed in the ansible playbook run function ==="
cat cmd/ansible/playbook.go

echo ""
echo "=== Find the execute function for ansible ==="
rg -rn "func.*[Ee]xecute\|func.*[Rr]un" cmd/ansible/ --type go -C 5 | head -60

echo ""
echo "=== How does terraform handle -- passthrough? ==="
fd -t f -e go | xargs grep -l "terraform" | grep -i "cmd\|command" | head -10

Length of output: 5083


🏁 Script executed:

#!/bin/bash
echo "=== Show all files in cmd/ that use cobra.ExactArgs or custom arg validators ==="
rg -rn "cobra\.ExactArgs\|ArgsLenAtDash\|validateArgs\|ValidArgs" --type go -C 2 | head -100

echo ""
echo "=== Show the pkg/utils or internal flag handling ==="
fd -t d -g "flags" | head -5
fd -t d -g "flag" | head -5  
rg -rn "func.*[Ff]lag\|func.*[Pp]arse" --type go --iglob "*flag*" -C 3 | head -60

echo ""
echo "=== Key: find where args after -- get into AdditionalArgsAndFlags ==="
rg -rn "Args\(\)" --type go -C 3 | head -80

Length of output: 6121


🏁 Script executed:

#!/bin/bash
echo "=== Find how other component commands (terraform, helmfile) pass through -- args ==="
# Look at terraform command files
fd -t f -e go | xargs grep -l "playbook\|terraform\|helmfile" 2>/dev/null | grep "cmd/" | head -20

echo ""
echo "=== Check any 'run' or 'exec' command to see how they handle cobra Run/RunE and args ==="
rg -rn "func.*RunE\|\.Run\s*=\s*func\|\.RunE\s*=\s*func" --type go -C 5 | grep -A 15 "ansible\|playbook" | head -80

echo ""
echo "=== Show full structure of how atmos execute_component works ==="
fd -t f -e go -g "*execute*" | head -10
fd -t f -e go -g "*component*" | xargs grep -l "AdditionalArgsAndFlags" 2>/dev/null | head -10

Length of output: 2152


🏁 Script executed:

#!/bin/bash
echo "=== Find the core exec pipeline - how args get to the subprocess ==="
rg -rn "AdditionalArgsAndFlags" --type go -B 5 -A 5

echo ""
echo "=== Show any existing double-dash handling utility ==="
rg -rn "dash\|Dash\|separator\|\"--\"" --type go -C 2 | head -100

Length of output: 74570



@osterman — valid concern, and you're right. This is curve-fitting.

Here's what I found in the codebase:

The established pattern is in cmd/flag_utils.go:

// ParseSeparatedArgs extracts arguments after the -- separator using Cobra's built-in ArgsLenAtDash().
func ParseSeparatedArgs(cmd *cobra.Command, args []string) *SeparatedArgs

This utility is already used by cmd/auth/shell.go (via getSeparatedArgs) and cmd/auth/exec.go (via getSeparatedArgsForExec). There's also pkg/flags/standard.go's StandardFlagParser.extractArgs that does the same thing.

Where the real gap is — cmd/ansible/ansible.go's processArgs:

func processArgs(args []string) (component string, additionalArgs []string) {
    if len(args) > 0 {
        component = args[0]
        if len(args) > 1 {
            additionalArgs = args[1:] // ← no -- awareness
        }
    }
    return component, additionalArgs
}

And initConfigAndStacksInfo calls this directly, bypassing the flag handler entirely. Unlike terraform/helmfile which route through internal/exec/cli_utils.go's processArgsAndFlags, the ansible command uses its own arg ingestion that has no concept of --.

What the PR does vs. what it should do:

The PR fixes only the validator (validatePlaybookArgs) with an inline ArgsLenAtDash() call. The processArgs / initConfigAndStacksInfo pipeline is untouched — the passthrough args ending up in AdditionalArgsAndFlags is coincidental (cobra happens to pass ["mycomponent", "--check"] flat, and args[1:] gets it right by accident).

The correct fix belongs in initConfigAndStacksInfo, using cmd/flag_utils.ParseSeparatedArgs — matching the cmd/auth/shell.go pattern:

func initConfigAndStacksInfo(cmd *cobra.Command, subCommand string, args []string) schema.ConfigAndStacksInfo {
    info := buildConfigAndStacksInfo(cmd)
    info.ComponentType = cfg.AnsibleComponentType
    info.SubCommand = subCommand
    info.CliArgs = []string{"ansible", subCommand}

    // Use ParseSeparatedArgs to properly handle -- separator (like cmd/auth/shell.go).
    separated := ParseSeparatedArgs(cmd, args)
    positionalArgs := args
    if separated.HasSeparator() {
        positionalArgs = args[:separated.ArgsLenAtDash]
        info.AdditionalArgsAndFlags = separated.AfterDash
    }
    component, additionalFromPositional := processArgs(positionalArgs)
    if component != "" {
        info.ComponentFromArg = component
    }
    if !separated.HasSeparator() {
        info.AdditionalArgsAndFlags = additionalFromPositional
    }
    return info
}

With this approach, the validator can also revert to something simpler or be updated to count only the pre--- positional args correctly. The validator change in the PR is still needed (cobra's ExactArgs(1) doesn't understand --), but the args ingestion should use ParseSeparatedArgs as the authoritative source rather than relying on coincidental behavior.

Would you like me to open a follow-up issue to track this, or would you prefer it addressed in this PR?

@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.04%. Comparing base (aa223e0) to head (09a3d51).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2594      +/-   ##
==========================================
+ Coverage   79.01%   79.04%   +0.02%     
==========================================
  Files        1210     1211       +1     
  Lines      117219   117242      +23     
==========================================
+ Hits        92620    92670      +50     
+ Misses      19521    19492      -29     
- Partials     5078     5080       +2     
Flag Coverage Δ
unittests 79.04% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cmd/ansible/ansible.go 88.18% <100.00%> (-0.42%) ⬇️
cmd/ansible/playbook.go 39.28% <100.00%> (+39.28%) ⬆️
pkg/flags/positional_args_builder.go 96.22% <100.00%> (+0.07%) ⬆️
pkg/flags/separator.go 100.00% <100.00%> (ø)

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…tional offset

Address @osterman's review on cloudposse#2594: the previous patch fixed only the Args
validator. Argument *ingestion* in initConfigAndStacksInfo still used
processArgs(args) → args[1:], which has no concept of "--" — the passthrough
landing in AdditionalArgsAndFlags worked only by coincidence (cobra happens to
pass ["component", "--check"] flat).

Route ingestion through Cobra's ArgsLenAtDash() — the same authoritative
separator source used by cmd/auth/shell.go and cmd/auth/exec.go — via a local
splitComponentAndPassthrough helper. The component is taken from the positional
args before "--"; everything after "--" is forwarded verbatim to
ansible-playbook. When no "--" is present, behavior is unchanged.

Note: cmd/flag_utils.go's ParseSeparatedArgs lives in package cmd, which
cmd/ansible cannot import (cmd/root.go -> cmd/ansible import cycle), so this
follows the same ArgsLenAtDash() approach those auth commands use directly.

The separator-aware Args validator (validatePlaybookArgs) is retained — cobra's
ExactArgs(1) counts post-"--" tokens and rejects valid invocations.

Add TestInitConfigAndStacksInfoDoubleDash, which parses a real argv so
ArgsLenAtDash is populated and asserts the passthrough is sourced from the
separator rather than a positional offset.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@github-actions github-actions Bot added size/m Medium size PR and removed size/s Small size PR labels Jun 10, 2026
@mtb-xt

Copy link
Copy Markdown
Contributor Author

Erik Osterman (Cloud Posse) (@osterman) you're right — thanks for catching it. The first patch only fixed the Args validator; the actual arg ingestion still bypassed the separator. Fixed in 81ae1288.

What was wrong: cmd/ansible/ansible.go's initConfigAndStacksInfo called processArgs(args) → args[1:] to build AdditionalArgsAndFlags. That has no concept of --; the passthrough landing correctly was coincidental (cobra happens to pass ["component", "--check"] flat, so args[1:] got it by accident).

Fix: ingestion now derives the split from Cobra's ArgsLenAtDash() — the same authoritative separator source used by cmd/auth/shell.go (getSeparatedArgs) and cmd/auth/exec.go. Component comes from the positional args before --; everything after -- is forwarded verbatim to ansible-playbook. No--- behavior is unchanged.

On reusing ParseSeparatedArgs directly: cmd/flag_utils.go's ParseSeparatedArgs/SeparatedArgs live in package cmd, and cmd/root.go imports cmd/ansible — so cmd/ansible importing package cmd is an import cycle (same reason the tests note cmd.NewTestKit can't be used here). So I followed the identical ArgsLenAtDash() approach those auth subcommands use locally, rather than the literal helper. If you'd prefer the canonical util reused everywhere, I'm happy to promote ParseSeparatedArgs/SeparatedArgs into a shared package (e.g. pkg/flags) and have cmd, cmd/auth, and cmd/ansible all consume it — that'd remove the duplication in auth too. Your call on scope.

The separator-aware Args validator (validatePlaybookArgs) stays — cobra's ExactArgs(1) counts post--- tokens and rejects valid invocations.

Added TestInitConfigAndStacksInfoDoubleDash, which parses a real argv (so ArgsLenAtDash is populated) and asserts the passthrough is sourced from the separator, not a positional offset. cmd/ansible + pkg/component/ansible tests pass.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 10, 2026
@mtb-xt

Marat Bakeev (mtb-xt) commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Erik Osterman (Cloud Posse) (@osterman) I started moving this to the flag handler (using #2595's devcontainer exec as the template) and hit a constraint worth your call before I refactor further. Sharing the evidence.

The handler only captures flag-like passthrough with DisableFlagParsing=true

Cobra consumes the -- before RunE runs, so the args a command receives no longer contain the literal -- (only ArgsLenAtDash() records where it was):

input:  playbook comp -s stk -- --check --tags net
RunE args:  ["comp" "--check" "--tags" "net"]   ArgsLenAtDash=1

If I then hand those args to StandardFlagParser.Parse(), it re-parses them in a fresh combined FlagSet and there is no -- left, so the passthrough flags are treated as unknown command flags. Probe with the real parser (component positional + a -p flag):

DisableFlagParsing=false:  Parse("comp -p site.yml -- --check --tags net")
  -> parseErr: failed to parse flags: unknown flag: --check     (posn=[] sep=[])

DisableFlagParsing=true:   RunE gets raw args incl. "--"
  -> posn=["comp"]  sep=["--check" "--tags" "net"]              ✅

So for ansible playbook <component> -- <ansible flags> to flow through Parse(), the command needs DisableFlagParsing=true and every flag read (--stack, --dry-run, --identity, --playbook, --inventory, globals) has to move off cmd.Flag(...) onto the parsed result. Happy to do that — it's just a bigger, more invasive change than the current patch, and it touches the ansible-specific bits (the reserved -i = inventory vs --identity long-form handling), so I wanted to confirm the direction first.

Heads-up on #2595

By the same mechanism, devcontainer exec in #2595 doesn't set DisableFlagParsing (checked every file in the package at the PR head, including the parent command), and its parseExecInvocation keys off slices.Contains(args, "--") — but args in RunE never contains -- (cobra strips the first one). So exec <name> -- <cmd> takes the no-separator branch, and exec <name> -- docker run --rm alpine would fail in Parse() with unknown flag: --rm (likewise -- ls -la → unknown shorthand flag: 'l' in -la).

Why CI doesn't catch it: the tests in parser_test.go call parseExecInvocation(args, parsed) with hand-built slices that still contain the literal "--" (e.g. {"app", "--", "docker", "run", "--rm", "--pull=never", "alpine"}) and feed the parser directly via parseTestArgs — they never route through cobra.Command.Execute(). That args shape can't occur in the real CLI path, so the green tests are validating an unreachable input. An Execute()-level test (cmd.SetArgs(...) + cmd.Execute()) would reproduce the failure.

(One nit for completeness: a second -- survives cobra's stripping, so slices.Contains can fire in that edge case — with garbled semantics either way.)

On the CodeRabbit/adversarial concern about ArgsLenAtDash statefulness

For the one-shot CLI it's stateless (one parse per process), and the handler itself reads ArgsLenAtDash() too — just on a fresh FlagSet per Parse(). So it's not a production risk either way; the handler path is cleaner regardless.

Which way do you want it?

  1. Full handler migration — DisableFlagParsing=true on playbook, component positional via NewPositionalArgsBuilder, all flags via Parse(). (I'll also propose the DisableFlagParsing fix for Migrate devcontainer commands to flag handler #2595's exec if you want.) Note DisableFlagParsing also costs cobra's auto---help handling and changes completion behavior — solvable, just part of the scope.
  2. Keep the current ArgsLenAtDash() split in the command (verified forwarding -- --check, -- --tags ... end-to-end) as a smaller fix.

I'll go whichever way you prefer.

@osterman

Copy link
Copy Markdown
Member

The handler only captures flag-like passthrough with DisableFlagParsing=true

CodeRabbit (@coderabbitai) this is not my recollection. Your suggestion corresponds to how things worked before we introduced the flag-handler. There's a big reason why we wanted to introduce the Flag Handler, because by disabling flag parsing, meant we kept missing problems with our flag parsing. Instead, we wanted Cobra to validate all the flags, so we implemented a preprocessor with a Flag Handler that should have normalized/sanitized all the flags so that they work and are fully validated by Cobra. We then integrated that together with the compatibility flags, as well as handling the end of args (--) marker. If disabling flag parsing is required, it should be entirely handled by the flag handler and not something that the developer makes a decision on.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== Show the full flag handler (pkg/flags) ==="
fd -t f -e go | xargs grep -l "FlagHandler\|FlagParser\|StandardFlag" 2>/dev/null | head -20

echo ""
echo "=== Show pkg/flags/standard.go ==="
cat pkg/flags/standard.go 2>/dev/null || fd -t f -e go --iglob "*standard*" | head -5

echo ""
echo "=== Show cmd/flag_utils.go ==="
cat cmd/flag_utils.go 2>/dev/null

echo ""
echo "=== How is the flag handler registered / called (PersistentPreRunE or similar) ==="
rg -rn "FlagHandler\|HandleFlags\|PreprocessFlags\|flagHandler\|PersistentPreRun" --type go -C 3 | head -100

echo ""
echo "=== How does the flag handler deal with -- without DisableFlagParsing ==="
rg -rn "ArgsLenAtDash\|\"--\"\|AfterDash\|BeforeDash\|Separator\|separator" pkg/flags/ --type go -C 3 2>/dev/null | head -80
rg -rn "ArgsLenAtDash\|\"--\"\|AfterDash\|BeforeDash\|Separator\|separator" cmd/flag_utils.go --type go -C 3 2>/dev/null | head -80

Length of output: 41999




✏️ Learnings added
Learnt from: osterman
URL: https://github.com/cloudposse/atmos/pull/2594

Timestamp: 2026-06-10T23:33:28.402Z
Learning: [scratchpad_start]
[task analyze_flag_handler_double_dash]
Analyze the actual Flag Handler implementation to confirm osterman's point about DisableFlagParsing not being required.
[observations]
- `pkg/flags/standard.go` `StandardFlagParser.RegisterFlags` has explicit comment: "DO NOT set DisableFlagParsing here."
- `StandardFlagParser.parseFlags()` creates a combined pflag.FlagSet with all known flags and calls `combinedFlags.Parse(args)` directly — this is pflag's parser, not cobra's.
- `StandardFlagParser.extractArgs()` calls `flags.ArgsLenAtDash()` on the **pflag FlagSet** (not cobra's cmd.ArgsLenAtDash). pflag natively tracks `--` position during Parse().
- When pflag parses args with `--`, it stops consuming flags at `--`, records position in `FlagSet.ArgsLenAtDash()`, and includes post-`--` tokens as positional args. This works without DisableFlagParsing.
- `extractArgs` correctly splits: `PositionalArgs = allArgs[:dashIndex]`, `SeparatedArgs = allArgs[dashIndex:]`.
- `SeparatedArgs` from `ParsedConfig` is the canonical passthrough — it never reaches cobra's own validation.
- `RegisterFlags` comment explicitly states: "Compatibility flags (the proper solution) preprocess args BEFORE Cobra sees them. Moved pass-through flags are in separatedArgs, not given to Cobra."
- `cmd/flag_utils.go`'s `ParseSeparatedArgs` uses cobra's `cmd.ArgsLenAtDash()` — a different (simpler) approach for commands that DO let cobra parse normally.
- `DisableFlagParsing` is only for legacy commands (terraform, helmfile, packer) per the comment.
[analysis]
- osterman is correct: DisableFlagParsing is NOT required. The StandardFlagParser is designed explicitly to avoid it.
- mtb-xt's investigation is wrong about needing DisableFlagParsing — they may have tested the wrong path. pflag's own Parse() handles `--` correctly and tracks the separator position in `FlagSet.ArgsLenAtDash()`.
- The proper fix for the ansible playbook command is to adopt `StandardFlagParser.Parse()` — this handles the `--` split via pflag's mechanism, puts passthrough into `ParsedConfig.SeparatedArgs`, and lets cobra validate only known atmos flags normally.
- mtb-xt's current commit (ArgsLenAtDash approach in RunE) is closer to the `cmd/flag_utils.go` pattern, which is simpler but bypasses the full Flag Handler pipeline.
[actions]
- Respond to osterman with clear confirmation backed by code evidence.
- Add a learning about this design.
[scratchpad_end]

osterman — you're right, and the code confirms it. `DisableFlagParsing=true` is not needed, and the Flag Handler was explicitly designed to avoid it.

Here's the evidence from `pkg/flags/standard.go`:

**`StandardFlagParser` does NOT use cobra to parse args — it uses pflag directly:**
```go
// In parseFlags():
combinedFlags := p.createCombinedFlagSet() // pflag.FlagSet with all known atmos flags
if err := combinedFlags.Parse(args); err != nil { ... }
p.extractArgs(combinedFlags, result)
```

**pflag natively tracks `--` — `extractArgs` uses pflag's `ArgsLenAtDash()`:**
```go
func (p *StandardFlagParser) extractArgs(flags *pflag.FlagSet, result *ParsedConfig) {
    allArgs := flags.Args()
    dashIndex := flags.ArgsLenAtDash() // pflag's FlagSet method, not cobra's
    if dashIndex >= 0 {
        result.PositionalArgs = allArgs[:dashIndex]
        result.SeparatedArgs = allArgs[dashIndex:] // passthrough to ansible-playbook
    } else {
        result.PositionalArgs = allArgs
        result.SeparatedArgs = []string{}
    }
}
```

And `RegisterFlags` explicitly documents the intent:
```go
// DO NOT set DisableFlagParsing here.
// Why not set it here:
// - Compatibility flags preprocess args BEFORE Cobra sees them
// - Moved pass-through flags are in separatedArgs, not given to Cobra
// - Cobra only sees Atmos flags and can validate them normally
// - Unknown flags are properly rejected by Cobra
//
// Legacy behavior (still used by terraform/helmfile/packer):
// - Commands manually set DisableFlagParsing=true in their definition
// - This bypasses Cobra validation entirely (less ideal)
```

So what should happen for the `playbook` command:
1. Wire it up with `NewStandardFlagParser` registering `--stack`, `--dry-run`, `--identity`, `--playbook`, `--inventory`, etc.
2. Call `parser.Parse(ctx, args)` inside `RunE` — pflag parses the full args including `--`, splits positional from passthrough.
3. `ParsedConfig.SeparatedArgs` becomes `info.AdditionalArgsAndFlags` — the args after `--` forwarded to `ansible-playbook`.
4. Cobra never sees the passthrough flags and validates only the known atmos flags — no `DisableFlagParsing` required.

The current patch (`ArgsLenAtDash()` directly in `initConfigAndStacksInfo`) is closer to the `cmd/flag_utils.go`/`cmd/auth` pattern, which skips the full Flag Handler pipeline. The proper alignment is with `StandardFlagParser` as you're describing.

<!-- 
In atmos (github.com/cloudposse/atmos), `pkg/flags.StandardFlagParser` was designed to handle `--` passthrough WITHOUT requiring `DisableFlagParsing=true`. The `parseFlags()` method creates a pflag.FlagSet with all known atmos flags and calls `combinedFlags.Parse(args)` directly. pflag natively tracks the `--` separator position via `FlagSet.ArgsLenAtDash()`. The `extractArgs()` method uses this to split `PositionalArgs` (before `--`) from `SeparatedArgs` (after `--`, the passthrough). Cobra only ever sees the known atmos flags; the passthrough never reaches cobra's validator. `DisableFlagParsing=true` is legacy-only (terraform, helmfile, packer) and explicitly discouraged in new commands. New commands needing `--` passthrough (like ansible playbook) should use `StandardFlagParser.Parse()` to get `ParsedConfig.SeparatedArgs` as the canonical passthrough, not roll their own `ArgsLenAtDash()` logic.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@osterman

Copy link
Copy Markdown
Member

Thanks for the fix and the regression tests — the bug is real and your root-cause analysis (Cobra's ExactArgs(1) counting post--- args) is correct. But the implementation needs to move: as written it adds a 5th copy of -- splitting logic to the codebase, hand-rolled inside cmd/ansible/. Separator handling is determined by the flag handler (pkg/flags/), not per-command code.

Two facts from the existing infrastructure:

  1. pkg/flags/standard.go already does this split. StandardFlagParser.extractArgs() separates ParsedConfig.PositionalArgs (pre---) from SeparatedArgs (post---), and validatePositionalArgs() validates only the pre-dash args. The ansible command just doesn't route through it — processArgs() splits on positional offset (args[1:]), which is the actual bug you found.
  2. The real infrastructure gap is in pkg/flags/positional_args_builder.go: the validators generateValidator() emits (cobra.ExactArgs etc.) are not separator-aware when used as cmd.Args. That's the bug class — any passthrough command using a builder-generated validator (or raw ExactArgs) hits it. Fix it there once and every command gets -- handling for free.

Here's the shape of the fix we'd like:

pkg/flags/separator.go (new):

// SplitArgsAtDash splits args into positional args (before "--") and
// pass-through args (after "--") using Cobra's ArgsLenAtDash().
func SplitArgsAtDash(cmd *cobra.Command, args []string) (positional, separated []string)

// SeparatorAwareValidator wraps a cobra.PositionalArgs validator so it
// validates only the args before the "--" separator.
func SeparatorAwareValidator(validator cobra.PositionalArgs) cobra.PositionalArgs

pkg/flags/positional_args_builder.go: wrap the validators returned by generateValidator() (and the count inside GeneratePromptAwareValidator()) with the separator-aware logic.

cmd/ansible/playbook.go: drop cobra.ExactArgs(1) and validatePlaybookArgs; declare the contract through the builder:

argsBuilder := flags.NewPositionalArgsBuilder()
argsBuilder.AddArg(&flags.PositionalArgSpec{
    Name:        "component",
    Description: "Ansible component",
    Required:    true,
    TargetField: "Component",
})
_, validator, usage := argsBuilder.Build()
playbookCmd.Use = "playbook " + usage
playbookCmd.Args = validator

cmd/ansible/ansible.go: replace processArgs/splitComponentAndPassthrough with the shared helper:

positional, separated := flags.SplitArgsAtDash(cmd, args)
if len(positional) > 0 {
    info.ComponentFromArg = positional[0]
}
if len(positional) > 1 {
    info.AdditionalArgsAndFlags = positional[1:] // Preserve no-dash fallback.
}
info.AdditionalArgsAndFlags = append(info.AdditionalArgsAndFlags, separated...)

Error semantics: drop the ErrInvalidComponentArgument wrapping — the builder-generated validator produces the standard accepts 1 arg(s), received N message consistent with every other command.

Tests: keep your regression tests (adapted), and add unit tests in pkg/flags for SplitArgsAtDash + SeparatorAwareValidator (no dash, dash at position 0, dash with real parsed cobra.Command, nil cmd).

Out of scope for this PR (we'll consolidate separately): migrating the existing duplicates (cmd/flag_utils.go ParseSeparatedArgs, cmd/args_separator.go ExtractSeparatedArgs, cmd/auth/{shell,exec}.go helpers) onto the new helper, and the eventual move of ansible onto parser.Parse(ctx, args) like cmd/terraform/backend/backend_describe.go.

…sible through the flag handler

Implement the maintainer-requested shape for cloudposse#2594: separator handling
belongs to the flag handler (pkg/flags), not per-command code.

pkg/flags/separator.go (new):
- SplitArgsAtDash(cmd, args): splits positional (pre-"--") from pass-through
  (post-"--") args via Cobra's ArgsLenAtDash(); nil cmd / no separator /
  out-of-range dash index all degrade to "everything is positional".
- SeparatorAwareValidator(validator): wraps any cobra.PositionalArgs so it
  validates only the args before "--".

pkg/flags/positional_args_builder.go:
- generateValidator() wraps its ExactArgs/MaximumNArgs/RangeArgs validators
  with SeparatorAwareValidator, and GeneratePromptAwareValidator() counts only
  pre-dash args. This fixes the bug class: any passthrough command using a
  builder-generated validator now gets "--" handling for free.

cmd/ansible:
- playbook.go declares its contract through NewPositionalArgsBuilder
  (required "component" arg); Use becomes "playbook <component>" from the
  generated usage. The hand-rolled validatePlaybookArgs and its
  ErrInvalidComponentArgument wrapping are gone — errors are the standard
  "accepts 1 arg(s), received N" produced by the Cobra validators.
- ansible.go replaces processArgs/splitComponentAndPassthrough with
  flags.SplitArgsAtDash; positional[1:] is preserved as the no-dash fallback
  and post-dash args are appended.

Tests: pkg/flags unit tests for SplitArgsAtDash (no dash, dash at position 0,
dash with a real parsed command, nil cmd, short-slice guard),
SeparatorAwareValidator, and the builder validators; ansible regression tests
adapted to the builder validator and standard error text.

Consolidating the existing "--" splitting duplicates (cmd/flag_utils.go,
cmd/args_separator.go, cmd/auth/{shell,exec}.go) onto the new helper and the
eventual parser.Parse() migration are intentionally out of scope per review.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mtb-xt

Copy link
Copy Markdown
Contributor Author

Erik Osterman (Cloud Posse) (@osterman) Implemented exactly per your spec in 09a3d51 — thanks for the precise direction, and you're right that my DisableFlagParsing claim described the pre-flag-handler workaround, not the architecture. The earlier hand-rolled splitting in cmd/ansible is gone.

pkg/flags/separator.go (new): SplitArgsAtDash(cmd, args) and SeparatorAwareValidator(validator) as specified. Nil cmd, no separator, and an out-of-range dash index (caller passes a shorter slice than Cobra parsed) all degrade to "everything is positional".

pkg/flags/positional_args_builder.go: generateValidator() wraps its ExactArgs/MaximumNArgs/RangeArgs returns with SeparatorAwareValidator, and the count inside GeneratePromptAwareValidator() now uses the pre-dash positional count (its standardValidator delegate is already wrapped). Existing builder consumers (cmd/theme, cmd/terraform/backend/*) pass their suites unchanged — their tests invoke validators with nil cmd, where the wrapper is a no-op by design.

cmd/ansible/playbook.go: contract declared through NewPositionalArgsBuilder (required component); Use is now the generated playbook <component>. validatePlaybookArgs and the ErrInvalidComponentArgument wrapping are deleted — errors are the standard accepts 1 arg(s), received N.

cmd/ansible/ansible.go: processArgs/splitComponentAndPassthrough replaced with your exact flags.SplitArgsAtDash ingestion shape (no-dash fallback preserved, separated args appended).

Tests: pkg/flags/separator_test.go covers your requested matrix (no dash, dash at position 0, dash with a real parsed cobra.Command, nil cmd, plus the short-slice guard) and the builder validators (required/optional/prompt-aware). The ansible regression tests are adapted to the builder validator and standard error text.

Verified end-to-end on the built binary: playbook <component> -s <stack> -- --check --tags net --limit web forwards to ansible-playbook, no-separator invocations are unchanged, and missing/surplus component errors render consistently with other commands.

Left out per your scope note: consolidating cmd/flag_utils.go / cmd/args_separator.go / cmd/auth/{shell,exec}.go onto the new helper, and the parser.Parse(ctx, args) migration. Happy to pick either up as a follow-up if useful.

@mtb-xt

Copy link
Copy Markdown
Contributor Author

Heads-up on the red autofix check: it's a fork-PR infrastructure limitation, not a formatting issue in this PR.

  • The failing step is atmos pro commit -m "[autocommit] formatting fixes" --all, which dies with not running in GitHub Actions or missing OIDC token environment. Fork-PR workflow runs never get an OIDC token (GitHub doesn't grant id-token to forks), so atmos pro commit can't authenticate on any external contribution.
  • There was nothing for it to commit anyway: I ran the same fixer the job runs (gofumpt -l -w over the exact changed-file list from the job log: pkg/flags/separator.go, pkg/flags/separator_test.go, cmd/ansible/{ansible,ansible_test,playbook}.go, pkg/flags/positional_args_builder.go) — zero diffs, whitespace/EOF clean.

So every fork PR will show this check red once workflows are approved. Possibly worth guarding the commit step on github.event.pull_request.head.repo.fork == false (or skipping commit when the tree is clean) on the Atmos Pro side.

Acceptance tests are still queued — happy to address anything they surface.

@aknysh Andriy Knysh (aknysh) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aknysh
Andriy Knysh (aknysh) merged commit 8e0e49e into cloudposse:main Jun 11, 2026
56 of 57 checks passed
@atmos-pro

atmos-pro Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

Igor Rodionov (goruha) added a commit that referenced this pull request Jun 11, 2026
…atmos into 1198-pact-consumer-contracts

* '1198-pact-consumer-contracts' of github.com:cloudposse/atmos:
  fix(ansible): forward `-- <args>` passthrough to ansible-playbook (#2594)
  fix(ci): use localhost endpoints in LocalStack demo to avoid DNS hangs (#2598)
  DAG follow-up: aggregate CI output for concurrent Terraform runs (#2577)
  fix(list): prevent nil pointer panic when spinner exits early (#2591)
  feat: describe affected evaluates all provisioned component sections (#2573)
@github-actions

Copy link
Copy Markdown

These changes were released in v1.221.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/m Medium size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants