Repository navigation
fix(ansible): forward -- <args> passthrough to ansible-playbook - #2594
Andriy Knysh (aknysh) merged 5 commits into
Conversation
`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]>
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughThe ChangesAnsible playbook argument validation
🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
cmd/ansible/ansible_test.gocmd/ansible/playbook.go
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]>
|
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. |
|
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 -20Length 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 -10Length 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 -5Length 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 -80Length 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 -10Length 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 -80Length 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 -10Length 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 -100Length of output: 74570
Here's what I found in the codebase: The established pattern is in // ParseSeparatedArgs extracts arguments after the -- separator using Cobra's built-in ArgsLenAtDash().
func ParseSeparatedArgs(cmd *cobra.Command, args []string) *SeparatedArgsThis utility is already used by Where the real gap is — 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 What the PR does vs. what it should do: The PR fixes only the validator ( The correct fix belongs in 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- Would you like me to open a follow-up issue to track this, or would you prefer it addressed in this PR? |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…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]>
|
Erik Osterman (Cloud Posse) (@osterman) you're right — thanks for catching it. The first patch only fixed the What was wrong: Fix: ingestion now derives the split from Cobra's On reusing The separator-aware Added |
|
Erik Osterman (Cloud Posse) (@osterman) I started moving this to the flag handler (using #2595's The handler only captures flag-like passthrough with
|
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 ( |
|
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 -80Length of output: 41999 ✏️ Learnings added
|
|
Thanks for the fix and the regression tests — the bug is real and your root-cause analysis (Cobra's Two facts from the existing infrastructure:
Here's the shape of the fix we'd like:
// 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
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
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 Tests: keep your regression tests (adapted), and add unit tests in Out of scope for this PR (we'll consolidate separately): migrating the existing duplicates ( |
…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]>
|
Erik Osterman (Cloud Posse) (@osterman) Implemented exactly per your spec in 09a3d51 — thanks for the precise direction, and you're right that my
Tests: Verified end-to-end on the built binary: Left out per your scope note: consolidating |
|
Heads-up on the red
So every fork PR will show this check red once workflows are approved. Possibly worth guarding the commit step on Acceptance tests are still queued — happy to address anything they surface. |
Andriy Knysh (aknysh)
left a comment
There was a problem hiding this comment.
thanks Marat Bakeev (@mtb-xt)
8e0e49e
into
cloudposse:main
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
…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)
|
These changes were released in v1.221.1. |
what
atmos ansible playbook <component> -s <stack> -- <ansible-args>failing with a misleadingUnknown command \`` error.playbookCmdnow uses a separator-aware argument validator instead ofcobra.ExactArgs(1): it requires exactly one positional component, counting only the arguments before a--separator.--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 rootUsageFuncrendered that failure as anUnknown commanderror naming the component.ansible-playbookflags, even though the command help documents[options]and points at the ansible-playbook CLI docs, and the executor (buildCommandArgs) already appendsinfo.AdditionalArgsAndFlagsto the command.cobra.ArgsLenAtDash()returns-1when no--is present, so the validator still checks the full slice for the common case and keeps the original "exactly one component" contract.Before
After
references
atmos ansible playbook(verified on v1.220.0).Summary by CodeRabbit
New Features
--verbatim to the underlying playbook command; positional validation ignores these passthrough args.Bug Fixes
--and return clear validation errors when missing or duplicated.Tests