Module: OpenTelemetry::Resource::Detector::AWS::EC2

Extended by:
EC2
Included in:
EC2
Defined in:
lib/opentelemetry/resource/detector/aws/ec2.rb

Overview

EC2 contains detect class method for determining EC2 resource attributes

Constant Summary collapse

EC2_METADATA_HOST =

EC2 metadata service endpoints and constants

'169.254.169.254'
TOKEN_ENDPOINT =
'/latest/api/token'
IDENTITY_DOCUMENT_ENDPOINT =
'/latest/dynamic/instance-identity/document'
HOSTNAME_ENDPOINT =
'/latest/meta-data/hostname'
TOKEN_HEADER =
'X-aws-ec2-metadata-token'
TOKEN_TTL_HEADER =
'X-aws-ec2-metadata-token-ttl-seconds'
TOKEN_TTL_VALUE =
'60'
HTTP_TIMEOUT =

Timeout in seconds for HTTP requests

1
RESOURCE =

Create a constant for resource semantic conventions

OpenTelemetry::SemanticConventions::Resource

Instance Method Summary collapse

Instance Method Details

#detectObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/opentelemetry/resource/detector/aws/ec2.rb', line 36

def detect
  # Implementation for EC2 detection supporting both IMDSv1 and IMDSv2
  resource_attributes = {}

  begin
    # Attempt to get IMDSv2 token - this will fail if IMDSv2 is not supported
    # but we'll still try IMDSv1 in that case
    token = fetch_token

    # Get instance identity document which contains most metadata
    # Will try with token (IMDSv2) or without token (IMDSv1)
    identity = fetch_identity_document(token) || {}
    return OpenTelemetry::SDK::Resources::Resource.create({}) if identity.empty?

    hostname = fetch_hostname(token)

    # Set resource attributes from the identity document
    resource_attributes[RESOURCE::CLOUD_PROVIDER] = 'aws'
    resource_attributes[RESOURCE::CLOUD_PLATFORM] = 'aws_ec2'
    resource_attributes[RESOURCE::CLOUD_ACCOUNT_ID] = identity['accountId']
    resource_attributes[RESOURCE::CLOUD_REGION] = identity['region']
    resource_attributes[RESOURCE::CLOUD_AVAILABILITY_ZONE] = identity['availabilityZone']

    resource_attributes[RESOURCE::HOST_ID] = identity['instanceId']
    resource_attributes[RESOURCE::HOST_TYPE] = identity['instanceType']
    resource_attributes[RESOURCE::HOST_NAME] = hostname
  rescue StandardError => e
    OpenTelemetry.handle_error(exception: e, message: 'EC2 resource detection failed')
    return OpenTelemetry::SDK::Resources::Resource.create({})
  end

  # Filter out nil or empty values
  resource_attributes.delete_if { |_key, value| value.nil? || value.empty? }
  OpenTelemetry::SDK::Resources::Resource.create(resource_attributes)
end