OpenTelemetry Python: reading resource attributes before async detection completes in CI
Resource detectors run when the provider is built. A test that reads resource.attributes immediately after start, before the detector has populated service.name/host fields, sees an empty or partial resource and fails an assertion.
What this error means
A test asserts resource.attributes["service.name"] equals a value, but gets unknown_service or a KeyError because the resource was inspected before detection merged its attributes.
KeyError: 'service.name'
# or:
assert resource.attributes.get('service.name') == 'my-service'
AssertionError: assert 'unknown_service' == 'my-service'Common causes
Resource is inspected before detectors merge attributes
Detection populates the resource as the provider initializes. Reading attributes too early, or from a resource built without the detector, yields defaults.
No explicit service.name to fall back on
When detection provides nothing and OTEL_SERVICE_NAME is unset, the SDK uses unknown_service, which the test does not expect.
How to fix it
Build the resource explicitly and pass it in
- Create a
Resourcewith the attributes you assert on. - Pass it to the TracerProvider so it is available immediately.
- Read attributes from that resource, not a lazily detected one.
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
resource = Resource.create({SERVICE_NAME: "my-service"})
provider = TracerProvider(resource=resource)
assert provider.resource.attributes[SERVICE_NAME] == "my-service"Set OTEL_SERVICE_NAME in the environment
Provide the service name via env so it is present regardless of detector timing.
env:
OTEL_SERVICE_NAME: my-serviceHow to prevent it
- Construct the Resource explicitly for tests instead of relying on detection.
- Set OTEL_SERVICE_NAME so identity is deterministic.
- Read attributes from the provider you configured, not the global default.