Skip to content

[FEAT] Add support for Enterprise Cost Centers#3000

Open
vmvarela wants to merge 38 commits intointegrations:mainfrom
vmvarela:cost-centers
Open

[FEAT] Add support for Enterprise Cost Centers#3000
vmvarela wants to merge 38 commits intointegrations:mainfrom
vmvarela:cost-centers

Conversation

@vmvarela
Copy link

@vmvarela vmvarela commented Dec 15, 2025

Resolves #2739


Before the change?

  • No support for enterprise cost centers resources or data

After the change?

  • Two new resources and data sources (github_enterprise_cost_center and github_enterprise_cost_centers)

NOTE: This API (billing) has no support for APP or fine-grained tokens.

Pull request checklist

  • Schema migrations have been created if needed (example)
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been reviewed and added / updated if needed (for bug fixes / features)

Does this introduce a breaking change?

Please see our docs on breaking changes to help!

  • Yes
  • No

@github-actions
Copy link

👋 Hi! Thank you for this contribution! Just to let you know, our GitHub SDK team does a round of issue and PR reviews twice a week, every Monday and Friday! We have a process in place for prioritizing and responding to your input. Because you are a part of this community please feel free to comment, add to, or pick up any issues/PRs that are labeled with Status: Up for grabs. You & others like you are the reason all of this works! So thank you & happy coding! 🚀

@deiga
Copy link
Collaborator

deiga commented Dec 19, 2025

We're trying to move towards using Context-aware provider functions, could you update all schemas to use those? So ReadContext etc

@vmvarela vmvarela force-pushed the cost-centers branch 2 times, most recently from 13dcd40 to 1ab2c0f Compare December 22, 2025 06:32
Copilot AI review requested due to automatic review settings December 26, 2025 09:00
Copy link

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

This PR adds comprehensive support for GitHub Enterprise Cost Centers, enabling Terraform management of cost center resources and their assignments. The implementation addresses issue #2739 by leveraging the newly public GitHub Enterprise billing API.

Key changes:

  • Introduces github_enterprise_cost_center resource for creating, updating, and archiving cost centers with authoritative management of user, organization, and repository assignments
  • Adds github_enterprise_cost_center and github_enterprise_cost_centers data sources for querying cost center information
  • Implements robust resource assignment synchronization with batching (50 resources per request) and retry logic for transient failures

Reviewed changes

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

Show a summary per file
File Description
website/github.erb Adds navigation links for the new data sources and resource
website/docs/r/enterprise_cost_center.html.markdown Documents the cost center resource with examples, arguments, attributes, and import instructions
website/docs/d/enterprise_cost_center.html.markdown Documents the single cost center data source for retrieving by ID
website/docs/d/enterprise_cost_centers.html.markdown Documents the data source for listing cost centers with optional state filtering
github/util_cost_centers.go Provides utility functions for API interactions including CRUD operations and resource assignment management
github/resource_github_enterprise_cost_center.go Implements the cost center resource with full lifecycle management and authoritative assignment synchronization
github/provider.go Registers the new resource and data sources with the provider
github/resource_github_enterprise_cost_center_test.go Provides acceptance tests covering create, update, assignment changes, and import scenarios
github/data_source_github_enterprise_cost_centers_test.go Tests the list data source with state filtering
github/data_source_github_enterprise_cost_centers.go Implements the data source for listing cost centers
github/data_source_github_enterprise_cost_center_test.go Tests the single cost center data source retrieval
github/data_source_github_enterprise_cost_center.go Implements the data source for retrieving a specific cost center by ID
examples/cost_centers/main.tf Provides a comprehensive example demonstrating resource and data source usage

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

@joraff
Copy link

joraff commented Jan 6, 2026

I built and tested your branch @vmvarela and it works great! I was able to read, import, and create cost centers and resources using your examples and a few of my own. Thank you for the work.

@vmvarela vmvarela force-pushed the cost-centers branch 3 times, most recently from a3e128c to 0bdad0f Compare January 8, 2026 16:35
@vmvarela vmvarela changed the title feat: Add support for Enterprise Cost Centers [FEAT] Add support for Enterprise Cost Centers Jan 8, 2026
@vmvarela vmvarela force-pushed the cost-centers branch 2 times, most recently from 3314826 to 1d13386 Compare January 10, 2026 11:11
Copy link
Collaborator

@deiga deiga left a comment

Choose a reason for hiding this comment

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

Half-way through. Please consider if my comments could apply to other places in your changes as well, I wasn't able to comment on every duplicate thing

Copy link
Author

@vmvarela vmvarela left a comment

Choose a reason for hiding this comment

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

Thank you for the thorough review @deiga! I've addressed all the feedback. Here's a summary of the changes:

Implemented:

  • ✅ Added top-level Description attribute to all resources and data sources
  • ✅ Removed ctx = context.WithValue(ctx, ctxId, ...) pattern from all files
  • ✅ Replaced log.Printf with tflog.Info and added tflog.Warn for 404 removals
  • ✅ Used diag.Errorf instead of diag.FromErr(fmt.Errorf(...))
  • ✅ Create and Update no longer call Read - computed fields are set directly
  • ✅ Extracted anonymous retry functions to named functions (retryCostCenterAddResources, retryCostCenterRemoveResources)
  • ✅ Changed import ID separator from / to : and using parseTwoPartID
  • ✅ Replaced stringSliceToAnySlice with existing flattenStringList
  • ✅ Used http.StatusNotFound and other constants instead of magic numbers
  • ✅ Moved is404 to util.go
  • ✅ Updated tests to use providerFactories and skipUnlessEnterprise(t)
  • ✅ Added owner = var.enterprise_slug to example provider config
  • ✅ Used buildTwoPartID in data source
  • ✅ Inlined check variables in tests

Regarding questions:

  • The resources attribute provides the raw API view while users, organizations, repositories are filtered convenience attributes. I kept both for flexibility and debugging purposes.
  • diffStringSlices differs from setChanges - it compares string slices directly while setChanges works with Terraform state changes. They serve different purposes.
  • In Create, we only fetch from API after assignments are configured to populate computed fields, since we're not calling Read anymore.

All tests pass and the code compiles without errors.

@vmvarela vmvarela force-pushed the cost-centers branch 5 times, most recently from b66a9c0 to 2763ff4 Compare January 20, 2026 18:58
@vmvarela vmvarela requested a review from deiga January 20, 2026 19:15
Copy link
Collaborator

@deiga deiga left a comment

Choose a reason for hiding this comment

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

Please pay attention to what I'm asking form you and make sure to make similar changes in other places where they might apply.

Consider these also for your other PRs

@vmvarela vmvarela force-pushed the cost-centers branch 3 times, most recently from 52a3d8a to 5e58a8c Compare January 21, 2026 09:28
@vmvarela vmvarela requested a review from deiga January 21, 2026 10:08
vmvarela added 20 commits March 20, 2026 13:46
Split resourceGithubEnterpriseCostCenterOrganizationsCreateOrUpdate into
separate Create and Update functions. Create only adds organizations,
Update handles the full diff. Both return nil instead of calling Read.

Resolves PR comments #6-7.
Split resourceGithubEnterpriseCostCenterRepositoriesCreateOrUpdate into
separate Create and Update functions. Create only adds repositories,
Update handles the full diff. Both return nil instead of calling Read.

Resolves PR comments #8-9.
…tions

The API returns type strings as 'User', 'Org', and 'Repo' but the tests
were checking for lowercase 'user', 'organization', and 'repository'.
This fix ensures CheckDestroy properly detects remaining assignments.
Add CostCenterResourceType constants (User, Org, Repo) to avoid
magic strings throughout the codebase. This prevents typos and
makes the code more maintainable.

Addresses review feedback from @deiga.
Replace terraform-plugin-sdk/v2 test imports with terraform-plugin-testing
to fix flag redefinition conflict ('sweep' flag registered twice).
This aligns cost center tests with the rest of the codebase.
Keep chunkStringSlice(items, maxSize) generic in util.go to avoid coupling with cost-center-specific constants.

Add nolint:unparam with explicit rationale because current call sites pass the same value, while preserving future reuse for other resources.
The import function now calls GetCostCenter to populate the 'name'
field from the API response. Without this, the Required 'name' field
would be empty after import, causing recreate churn on the next plan.

Addresses review comment from @stevehipwell.
Sub-resources (_users, _organizations, _repositories) now use a simple
cost_center_id as their Terraform ID, consistent with the main
github_enterprise_cost_center resource.

Also moves d.SetId() to after the API call succeeds, preventing
corrupt state if the add-resources call fails.

Tests updated to use ImportStateIdPrefix and read attributes from
state instead of parsing the now-simple ID.

Addresses review comments from @stevehipwell.
Before adding resources to a cost center, check via API whether
the cost center already has resources of the managed type assigned.
If so, return an error asking the user to import or remove them
manually. This prevents silently clobbering pre-existing assignments.
Replace the two-map diff (currentX + desiredX) with a single map
where false=remove and true=keep. Desired items not in the map are
added. This is shorter and avoids constructing a second map.
Instead of reading resource names from Terraform state (which may be
stale or incomplete), Delete now calls GetCostCenter to fetch the
current list of resources of the managed type from the API and removes
them all. Also handles 404 gracefully (cost center already gone).
The cost center sub-resources (organizations, repositories, users)
were registered in provider.go and had docs, but were accidentally
omitted from the website sidebar navigation.
@deiga
Copy link
Collaborator

deiga commented Mar 23, 2026

@vmvarela thanks for keeping these up-to-date! We haven't had enough capacity to get these fully reviewed and merged yet, but we do still intend to get there! ☺️

Copy link
Collaborator

@deiga deiga left a comment

Choose a reason for hiding this comment

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

We're close! :)

Comment on lines +65 to +67
if cc == nil || cc.ID == "" {
return diag.Errorf("failed to create cost center: missing id in response (unexpected API response; please retry or contact support)")
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is unnecessary defensive programming. There are no real cases where this could be true

Suggested change
if cc == nil || cc.ID == "" {
return diag.Errorf("failed to create cost center: missing id in response (unexpected API response; please retry or contact support)")
}

Copy link
Author

Choose a reason for hiding this comment

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

Done.

Comment on lines +88 to +95
if errIs404(err) {
tflog.Warn(ctx, "Cost center not found, removing from state", map[string]any{
"enterprise_slug": enterpriseSlug,
"cost_center_id": costCenterID,
})
d.SetId("")
return nil
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This could be replaced with a call to deleteResourceOn404AndSwallow304OtherwiseReturnError

Copy link
Author

Choose a reason for hiding this comment

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

Done

Comment on lines +154 to +161
if errIs404(err) {
tflog.Warn(ctx, "Cost center not found, removing from state", map[string]any{
"enterprise_slug": enterpriseSlug,
"cost_center_id": costCenterID,
})
d.SetId("")
return nil
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

suggestion: could be replaced by deleteResourceOn404AndSwallow304OtherwiseReturnError

Copy link
Author

Choose a reason for hiding this comment

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

Done

The modernize/newexpr rule incorrectly suggests replacing github.Ptr(x)
with new(x), but new() takes a type not an expression — the auto-fix
generates invalid Go code. Exclude this specific rule pattern.
…n404AndSwallow304OtherwiseReturnError helper
@vmvarela vmvarela requested a review from deiga March 23, 2026 20:24
.golangci.yml Outdated
Comment on lines +50 to +52
- linters:
- modernize
text: "newexpr: call of Ptr"
Copy link
Collaborator

Choose a reason for hiding this comment

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

issue: This seems wrong. We've already applied modernize all over the codebase and it works

Copy link
Author

Choose a reason for hiding this comment

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

It did not work for me, but I will delete this.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT]: Add support for Enterprise billing resources

5 participants