Skip to content

Fix fleetctl generate-gitops failing to include VPP fleet assignments#42429

Open
lukeheath wants to merge 3 commits intomainfrom
lukeheath/fix-generate-gitops
Open

Fix fleetctl generate-gitops failing to include VPP fleet assignments#42429
lukeheath wants to merge 3 commits intomainfrom
lukeheath/fix-generate-gitops

Conversation

@lukeheath
Copy link
Member

@lukeheath lukeheath commented Mar 25, 2026

For #33106

Reproduced bug and validated fix locally. After fix:

volume_purchasing_program:
    - fleets:
      - "💻 Workstations"
      location: VPP Location 1
    - fleets:
      - "📱🔐 Personal mobile devices"
      location: VPP Location 2

Passed fleetctl gitops validation.

Summary by CodeRabbit

Bug Fixes

  • Fixed fleetctl generate-gitops command that previously failed to include VPP (Volume Purchasing Program) fleet assignments. The tool now properly retrieves VPP tokens and includes them with their associated team assignments in the generated configuration files.

Tests

  • Added comprehensive test coverage for VPP token retrieval and validation of correct inclusion in GitOps configuration generation.

@lukeheath lukeheath requested a review from a team as a code owner March 25, 2026 22:24
Copilot AI review requested due to automatic review settings March 25, 2026 22:24
Copy link

@claude claude bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review.

Tip: disable this comment in your organization's Code Review settings.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Updates fleetctl generate-gitops to correctly include VPP (Volume Purchasing Program) token-to-fleet/team assignments by fetching and translating VPP token state from the server API.

Changes:

  • Added a Fleet client method to fetch VPP tokens (GET /api/latest/fleet/vpp_tokens).
  • Updated generateMDM to derive volume_purchasing_program GitOps output from VPP tokens instead of app config.
  • Expanded generate-gitops unit tests to cover VPP token-to-config translation and updated an existing MDM-disabled test to avoid VPP calls.

Reviewed changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 4 comments.

File Description
server/service/client_mdm.go Adds Client.GetVPPTokens() for retrieving VPP token state from the Fleet API.
cmd/fleetctl/fleetctl/generate_gitops.go Uses GetVPPTokens() to generate mdm.volume_purchasing_program from token assignments.
cmd/fleetctl/fleetctl/generate_gitops_test.go Adds VPP translation tests and adjusts existing tests to account for the new VPP fetch.
changes/33106-fix-generate-gitops-vpp Changelog entry for the fix.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov
Copy link

codecov bot commented Mar 25, 2026

Codecov Report

❌ Patch coverage is 73.68421% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.51%. Comparing base (3135a5d) to head (8990217).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
server/service/client_mdm.go 0.00% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #42429      +/-   ##
==========================================
- Coverage   66.52%   66.51%   -0.01%     
==========================================
  Files        2530     2530              
  Lines      203059   203083      +24     
  Branches     9141     9141              
==========================================
+ Hits       135077   135086       +9     
- Misses      55775    55786      +11     
- Partials    12207    12211       +4     
Flag Coverage Δ
backend 68.31% <73.68%> (-0.01%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@lukeheath
Copy link
Member Author

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 25, 2026

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 25, 2026

Walkthrough

This change adds VPP token fetching functionality to the fleetctl generate-gitops command. The generateMDM function now retrieves VPP tokens via a new GetVPPTokens() interface method instead of using direct assignment. The returned tokens are transformed into MDM Apple Volume Purchasing Program info containing locations and associated team names. A corresponding client method implements the API call to fetch VPP tokens from the server. Tests validate VPP token handling across multiple scenarios.

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is minimal and lacks key information from the template such as testing details, validation steps, and a changes file reference. Add details about automated tests added/updated, manual QA performed, confirmation that changes file was added, and any other relevant checklist items from the template.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing fleetctl generate-gitops to include VPP fleet assignments, which is the primary focus of all code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch lukeheath/fix-generate-gitops

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
cmd/fleetctl/fleetctl/generate_gitops_test.go (1)

1979-2090: Add one failure-path case for GetVPPTokens errors.

Current table cases validate shape/mapping well, but don’t assert generateMDM behavior when the client returns an error.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleetctl/fleetctl/generate_gitops_test.go` around lines 1979 - 2090, Add
a failure-path test to TestGenerateMDMVPPTokens that asserts generateMDM returns
the error when GetVPPTokens fails: extend the table with a case like
"GetVPPTokens error", modify vppMockClientWrapper to include an err field (e.g.
vppErr error) and update its GetVPPTokens to return (w.vppTokens, w.vppErr), and
in the test set wrapper.vppErr = errors.New("some error") then call
cmd.generateMDM(&appConfig.MDM) and require.Error(t, err) and assert the
returned mdmRaw is nil or empty as appropriate; reference
TestGenerateMDMVPPTokens, generateMDM, and vppMockClientWrapper.GetVPPTokens to
locate where to add the case and change the wrapper.
cmd/fleetctl/fleetctl/generate_gitops.go (1)

1121-1130: Make VPP output ordering deterministic for stable GitOps diffs.

Line 1122+ preserves incoming token/team order. If backend order changes, generated YAML can churn without real config changes.

♻️ Suggested deterministic ordering
+	"sort"
+	"strings"
@@
-		var vppConfig []fleet.MDMAppleVolumePurchasingProgramInfo
+		vppConfig := make([]fleet.MDMAppleVolumePurchasingProgramInfo, 0, len(vppTokens))
 		for _, token := range vppTokens {
+			if token == nil {
+				continue
+			}
 			teamNames := make([]string, 0, len(token.Teams))
 			for _, team := range token.Teams {
 				teamNames = append(teamNames, team.Name)
 			}
+			sort.Strings(teamNames)
 			vppConfig = append(vppConfig, fleet.MDMAppleVolumePurchasingProgramInfo{
 				Location: token.Location,
 				Teams:    teamNames,
 			})
 		}
+		sort.Slice(vppConfig, func(i, j int) bool {
+			return strings.ToLower(vppConfig[i].Location) < strings.ToLower(vppConfig[j].Location)
+		})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleetctl/fleetctl/generate_gitops.go` around lines 1121 - 1130, The
current loop building vppConfig from vppTokens preserves upstream ordering which
causes non-deterministic YAML diffs; to fix, iterate over a deterministically
sorted copy of vppTokens (e.g., sort by token.Location or another stable key)
and for each token build teamNames and sort them (use sort.Strings on the slice
of Team.Name) before creating fleet.MDMAppleVolumePurchasingProgramInfo, and
(optionally) sort the final vppConfig slice by Location as a final pass so the
resulting output is stable regardless of backend ordering.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@cmd/fleetctl/fleetctl/generate_gitops_test.go`:
- Around line 1979-2090: Add a failure-path test to TestGenerateMDMVPPTokens
that asserts generateMDM returns the error when GetVPPTokens fails: extend the
table with a case like "GetVPPTokens error", modify vppMockClientWrapper to
include an err field (e.g. vppErr error) and update its GetVPPTokens to return
(w.vppTokens, w.vppErr), and in the test set wrapper.vppErr = errors.New("some
error") then call cmd.generateMDM(&appConfig.MDM) and require.Error(t, err) and
assert the returned mdmRaw is nil or empty as appropriate; reference
TestGenerateMDMVPPTokens, generateMDM, and vppMockClientWrapper.GetVPPTokens to
locate where to add the case and change the wrapper.

In `@cmd/fleetctl/fleetctl/generate_gitops.go`:
- Around line 1121-1130: The current loop building vppConfig from vppTokens
preserves upstream ordering which causes non-deterministic YAML diffs; to fix,
iterate over a deterministically sorted copy of vppTokens (e.g., sort by
token.Location or another stable key) and for each token build teamNames and
sort them (use sort.Strings on the slice of Team.Name) before creating
fleet.MDMAppleVolumePurchasingProgramInfo, and (optionally) sort the final
vppConfig slice by Location as a final pass so the resulting output is stable
regardless of backend ordering.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4bec6317-8723-431c-87f3-4ba834eb7536

📥 Commits

Reviewing files that changed from the base of the PR and between 24601a0 and 1e4df78.

📒 Files selected for processing (4)
  • changes/33106-fix-generate-gitops-vpp
  • cmd/fleetctl/fleetctl/generate_gitops.go
  • cmd/fleetctl/fleetctl/generate_gitops_test.go
  • server/service/client_mdm.go

@lukeheath
Copy link
Member Author

Re: CodeRabbit:

  1. ListVPPTokens sorts by OrgName before returning, and that's what our new GetVPPTokens client method calls under the hood. So the output is already deterministic without any changes on our side.

  2. Added error test case.

@lukeheath
Copy link
Member Author

@sgress454 I noticed this was the oldest bug not in a sprint so figured I'd take crack at it based on your comment.

@lukeheath lukeheath marked this pull request as ready for review March 25, 2026 23:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants