Creating Discovery Packages for Netherframe
This guide provides a systematic workflow for creating new discovery packages, based on lessons learned from implementing the GitLab discovery package.
Overview
Discovery packages enable Netherframe to import existing cloud infrastructure resources. Each package implements provider-specific logic to discover resources and generate appropriate import IDs and configurations.
Workflow Steps
1. Research Phase
Objective: Understand the provider's resources and import patterns.
# Check if provider bindings already exist
ls providers/{provider_org}/{provider_name}/
# Examine the generated provider stubs
cat providers/{provider_org}/{provider_name}/nf/providers/{provider_org}/{provider_name}/__init__.pyi
Key Actions:
- List all resources from the provider's generated bindings (found in __init__.pyi)
- Research the Terraform provider documentation for import ID formats
- Identify the provider's API client library (e.g., boto3 for AWS, python-gitlab for GitLab)
- Understand resource relationships and dependencies
Lessons Learned: - The generated provider bindings are the authoritative source for resource types - Import ID formats vary significantly between resources (numeric IDs, paths, composite keys) - Some resources may not support import or discovery
2. Package Structure Setup
Standard directory structure:
discovery/netherframe.discovery.{provider_org}.{provider_name}/
├── netherframe/ # NO __init__.py here!
│ └── discovery/ # NO __init__.py here!
│ └── {provider_org}/ # NO __init__.py here!
│ └── {provider_name}/
│ ├── __init__.py
│ └── discoverer.py
├── tests/
│ ├── __init__.py
│ └── test_{provider_name}_discoverer.py
├── pyproject.toml
└── README.md
IMPORTANT: Do NOT create __init__.py files in the namespace directories (netherframe/, netherframe/discovery/, netherframe/discovery/{provider_org}/). These are shared namespace packages used by multiple packages, and adding __init__.py files will cause import conflicts. Only add __init__.py to the final package directory (netherframe/discovery/{provider_org}/{provider_name}/). The nf/ shim modules (the nf.* alias) are generated: see the existing packages, and run python tools/scripts/generate_nf_alias_shims.py after adding modules.
pyproject.toml template:
[project]
name = "netherframe.discovery.{provider_org}.{provider_name}"
version = "0.1.0"
description = "{Provider} resource discovery for Netherframe"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"netherframe.core",
"{provider-api-library}>=X.Y.Z", # e.g., python-gitlab>=4.0.0
]
[project.entry-points."nf.discoverers"]
{provider_name} = "netherframe.discovery.{provider_org}.{provider_name}:{Provider}Discoverer"
[build-system]
requires = ["uv_build>=0.13.9,<0.14.0"]
build-backend = "uv_build"
[tool.uv]
package = true
[tool.uv.build-backend]
module-name = ["netherframe.discovery.{provider_org}.{provider_name}", "nf.discovery.{provider_org}.{provider_name}"]
module-root = ""
3. Core Implementation Pattern
Base discoverer structure:
from typing import Any
from nf.core.infrastructure.discovery import DiscoveredResource, ResourceDiscoverer
try:
import example_cloud # the provider's API client library
HAS_PROVIDER = True
except ImportError:
HAS_PROVIDER = False
example_cloud = None
class ExampleDiscoverer(ResourceDiscoverer):
def __init__(self) -> None:
if not HAS_PROVIDER:
raise ImportError("example-cloud is required to use the Example discoverer. Install it with: pip install example-cloud")
def get_provider_source(self) -> str:
return "example/cloud"
def get_supported_resource_types(self) -> list[str]:
# List ALL resources from the provider
return [
# Group resources logically
# Core resources
"cloud_resource1",
"cloud_resource2",
# Child resources
"cloud_resource1_child",
# etc...
]
def validate_config(self, config: dict[str, Any]) -> bool:
return "token" in config
def discover_resources(self, config: dict[str, Any], filters: dict[str, Any] | None = None) -> list[DiscoveredResource]:
# Call the provider's API and return one DiscoveredResource per object
return []
ResourceDiscoverer has four abstract methods: get_provider_source,
get_supported_resource_types, validate_config and discover_resources.
4. Efficient Discovery Implementation
Key Patterns:
-
Hierarchical Discovery: Start with parent resources, then discover children
def discover_resources(self, config, filters): # Discover parents first projects = self._discover_projects(client, filters) # Then discover children for each parent for project in projects: self._discover_project_children(project, filters) -
Batch Operations: Minimize API calls by fetching lists vs individual items
# Good: One API call resources = client.resources.list(all=True) # Bad: N API calls for id in resource_ids: resource = client.resources.get(id) -
Filter Early: Apply filters at the API level when possible
# Good: Filter at API projects = client.projects.list(owned=True, membership=True) # Bad: Filter after fetching all projects = [p for p in client.projects.list(all=True) if p.owned] -
Error Resilience: Continue discovery even if some resources fail
for resource_type in resource_types: try: resources = self._discover_resource_type(client, resource_type, filters) discovered.extend(resources) except Exception as e: logging.warning(f"Failed to discover {resource_type}: {e}") # Continue with next type instead of failing entirely
5. Import ID Patterns
Common patterns encountered:
- Simple ID:
resource_id(e.g., runners, users) - Path-based:
namespace/path(e.g., projects) - Composite:
parent_id:child_id(e.g., memberships) - Triple composite:
parent:key:scope(e.g., variables with environment scope) - Special formats: Some resources have unique requirements
Implementation approach:
from types import SimpleNamespace
def variable_import_id(project, var) -> str:
# Document import format clearly
# Import ID format: project_id:variable_key:environment_scope
import_id = f"{project.path_with_namespace}:{var.key}"
if hasattr(var, "environment_scope") and var.environment_scope != "*":
import_id += f":{var.environment_scope}"
return import_id
project = SimpleNamespace(path_with_namespace="team/app")
assert variable_import_id(project, SimpleNamespace(key="TOKEN", environment_scope="prod")) == "team/app:TOKEN:prod"
assert variable_import_id(project, SimpleNamespace(key="TOKEN", environment_scope="*")) == "team/app:TOKEN"
6. Attribute Mapping Strategy
Best practices:
-
Required vs Optional: Always include required attributes, check for optional
attrs = { # Required attributes "name": resource.name, "path": resource.path, } # Optional attributes with hasattr checks if hasattr(resource, "description"): attrs["description"] = resource.description -
Type Conversions: Ensure correct types for Terraform
# Convert lists/arrays if hasattr(resource, "topics") and resource.topics: attrs["topics"] = list(resource.topics) # Convert booleans attrs["enabled"] = bool(getattr(resource, "enabled", True)) -
Nested Objects: Handle complex structures appropriately
# For nested access levels if hasattr(resource, "push_access_levels"): attrs["push_access_level"] = [ { "access_level": level.access_level, "user_id": getattr(level, "user_id", None), } for level in resource.push_access_levels ]
7. Testing Strategy
Comprehensive test coverage:
- Configuration tests: Token handling, environment variables, validation
- Discovery tests: Mock API responses for each resource type
- Filter tests: Ensure filters work correctly
- Error handling tests: API failures, missing permissions
- Import ID tests: Verify correct format for each resource type
Mock pattern:
from typing import Any
from unittest.mock import Mock, patch
from nf.core.infrastructure.discovery import DiscoveredResource, ResourceDiscoverer
class ExampleDiscoverer(ResourceDiscoverer):
def get_provider_source(self) -> str:
return "example/cloud"
def get_supported_resource_types(self) -> list[str]:
return ["cloud_resource"]
def validate_config(self, config: dict[str, Any]) -> bool:
return "token" in config
def _create_client(self, config: dict[str, Any]) -> Any:
raise NotImplementedError("a real discoverer builds the provider's API client here")
def discover_resources(self, config: dict[str, Any], filters: dict[str, Any] | None = None) -> list[DiscoveredResource]:
client = self._create_client(config)
return [
DiscoveredResource(
resource_type="cloud_resource",
import_id=str(resource.id),
attributes={"name": resource.name},
provider_source=self.get_provider_source(),
)
for resource in client.resources.list()
]
discoverer = ExampleDiscoverer()
config = {"token": "unused"}
def test_discover_resources():
mock_resource = Mock()
mock_resource.id = 123
mock_resource.name = "test"
# Set all required attributes
mock_client = Mock()
mock_client.resources.list.return_value = [mock_resource]
with patch.object(discoverer, "_create_client", return_value=mock_client):
resources = discoverer.discover_resources(config)
assert len(resources) == 1
assert resources[0].import_id == "123"
test_discover_resources()
8. Documentation Requirements
README.md must include: - Installation instructions - Authentication setup - Basic usage example - List of supported resources - Configuration options - Filter examples - Known limitations
Example script (examples/{provider}_discovery_example.py):
- Show multiple discovery scenarios
- Demonstrate filtering
- Include error handling
- Show both auto-import and manual import options
9. Performance Considerations
-
Pagination: Handle large result sets efficiently
def _create_client(self, config): client = Provider(...) if "per_page" in config: client.per_page = config["per_page"] return client -
Selective Discovery: Allow discovering specific resource types
resource_types = config.get("resource_types", self.get_supported_resource_types()) -
Caching: Consider caching parent resources to avoid repeated lookups
self._project_cache = {} def _get_project(self, project_id): if project_id not in self._project_cache: self._project_cache[project_id] = self.client.projects.get(project_id) return self._project_cache[project_id]
10. Integration Checklist
- [ ] Add package to workspace members in root
pyproject.toml - [ ] Add tests directory to pytest testpaths
- [ ] Create entry point in package's
pyproject.toml - [ ] Implement all methods from
ResourceDiscovererinterface - [ ] Handle authentication via config and environment variables
- [ ] Support common filter patterns (IDs, ownership, access levels)
- [ ] Document all import ID formats
- [ ] Create comprehensive test suite
- [ ] Write clear README with examples
- [ ] Add example script to
examples/directory
Common Pitfalls to Avoid
- Don't fetch unnecessary data: Only get full resource details when needed
- Don't assume attributes exist: Always use
hasattr()orgetattr() - Don't fail on first error: Log and continue with other resources
- Don't hardcode values: Make timeouts, page sizes configurable
- Don't forget metadata: Include helpful context for debugging
- Don't fabricate unreadable values: When the API never returns an argument the provider needs (passwords, API key values, client secrets), leave it out of
attributesand list it under theARGUMENTS_TO_SUPPLYmetadata key (from netherframe.core.infrastructure.discovery import ARGUMENTS_TO_SUPPLY) as{argument path: reason}, e.g.{"auth_parameters.api_key.value": "not returned by the AWS API"}.nf discover resourcesandResourceDiscoveryManager.discover_and_fold()then tell users which arguments they must supply. - Don't invent native import support: For a configuration resource whose provider has no importer, set metadata
NATIVE_IMPORT_SUPPORTED: False(the constant is in the same discovery module). Itsimport_idis then only a logical inventory identity. JSON includesnative_import_supported: false, the table shows import as unsupported, and folding emits the configuration without an import block orimport_from(), with a notice to review creation behavior before applying. Document that behavior explicitly; some account settings apply or reverse policy when created or deleted.
Resource Organization
Group resources logically in get_supported_resource_types():
def get_supported_resource_types() -> list[str]:
return [
# Core resources
"provider_project",
"provider_group",
"provider_user",
# Project-scoped resources
"provider_project_variable",
"provider_project_hook",
# Group-scoped resources
"provider_group_variable",
"provider_group_membership",
# Global/instance resources
"provider_instance_variable",
"provider_system_hook",
]
Quick Start Template
# 1. Create package structure
provider_org="example"
provider_name="cloud"
package_name="netherframe.discovery.${provider_org}.${provider_name}"
mkdir -p discovery/${package_name}/{netherframe/discovery/${provider_org}/${provider_name},tests}
# 2. Copy and adapt from existing discoverer
cp discovery/netherframe.discovery.gitlabhq.gitlab/pyproject.toml discovery/${package_name}/
cp discovery/netherframe.discovery.gitlabhq.gitlab/netherframe/discovery/gitlabhq/gitlab/discoverer.py \
discovery/${package_name}/netherframe/discovery/${provider_org}/${provider_name}/
# 3. Update with provider-specific logic
# 4. Add to workspace
# 5. Write tests
# 6. Document
This workflow ensures consistent, high-quality discovery packages that provide maximum value to users wanting to import existing infrastructure into Netherframe.