OpenTelemetry Container Resource Detector

raw JSON →
0.62b1 verified Mon Apr 27 auth: no python

Detects container ID from cgroup or container runtime to enrich OpenTelemetry resource attributes. Current version 0.62b1, beta release. Part of opentelemetry-python-contrib releases, cadence aligned with OpenTelemetry Python releases.

pip install opentelemetry-resource-detector-containerid
error ModuleNotFoundError: No module named 'opentelemetry_resource_detector_container'
cause Incorrect import path: using hyphens instead of underscores.
fix
Use: from opentelemetry.resource.detector.container import ContainerIDResourceDetector
error AttributeError: 'ContainerIDResourceDetector' object has no attribute 'detect'
cause In older versions of opentelemetry-sdk, detect() exists but is deprecated; in newer versions the method may have been removed or renamed.
fix
Update to use get_aggregated_resources from opentelemetry.sdk.resources, or install compatible older SDK. Example: resource = get_aggregated_resources([detector])
error TypeError: 'NoneType' object is not subscriptable
cause The detector may return None if container ID is not found, and code tries to access attributes.
fix
Check that resource is not None before accessing attributes, or use get_aggregated_resources which always returns a Resource.
deprecated The method `detect()` on ContainerIDResourceDetector is deprecated in favor of `get_aggregated_resources` from opentelemetry.sdk.resources.
fix Use `get_aggregated_resources([detector])` instead of `detector.detect()`.
gotcha Container ID detection requires access to /proc/self/cgroup or /proc/1/cgroup and may fail in environments without cgroup v1 or v2. On some container runtimes (e.g., Podman), the ID format differs.
fix Ensure the container runtime exposes cgroup files. Use `container.id` attribute only when the detector succeeds; fall back to a default value if needed.
gotcha The detector is part of `opentelemetry-python-contrib` and does not include OpenTelemetry SDK itself. Users must install `opentelemetry-sdk` separately.
fix Install opentelemetry-sdk: `pip install opentelemetry-sdk`.

Detect container ID and merge into a resource. Newer SDKs require get_aggregated_resources; detect() is deprecated.

from opentelemetry import trace
from opentelemetry.resource.detector.container import ContainerIDResourceDetector
from opentelemetry.sdk.resources import get_aggregated_resources

# Create a resource detector instance
detector = ContainerIDResourceDetector()
# For the latest SDK, use get_aggregated_resources to merge multiple detectors
resource = get_aggregated_resources([detector])
# Or if using older SDK (pre-1.25):
# resource = detector.detect()
print(resource.attributes.get('container.id', 'no container ID found'))