Using Cloud Instance Metadata

When Micronaut detects it is running on a supported cloud platform, on startup it populates the interface ComputeInstanceMetadata.

As of Micronaut 2.1.x this logic depends on the presence of the appropriate core Cloud module for Oracle Cloud, AWS, or GCP.

All this data is merged together into the metadata property for the running ServiceInstance.

To access the metadata for your application instance you can use the interface EmbeddedServerInstance, and call getMetadata() which returns a Map of the metadata.

If you connect remotely via a client, the instance metadata can be referenced once you have retrieved a ServiceInstance from either the LoadBalancer or DiscoveryClient APIs.

The Netflix Ribbon client-side load balancer can be configured to use the metadata to do zone-aware client-side load balancing. See Client-Side Load Balancing

To obtain metadata for a service via Service Discovery use the LoadBalancerResolver interface to resolve a LoadBalancer and obtain a reference to a service by identifier:

Obtaining Metadata for a Service instance

  1. LoadBalancer loadBalancer = loadBalancerResolver.resolve("some-service");
  2. Flux.from(
  3. loadBalancer.select()
  4. ).subscribe((instance) ->
  5. ConvertibleValues<String> metaData = instance.getMetadata();
  6. ...
  7. );

The EmbeddedServerInstance is available through event listeners that listen for the ServiceReadyEvent. The @EventListener annotation makes it easy to listen for the event in your beans.

To obtain metadata for the locally running server, use an EventListener for the ServiceReadyEvent:

Obtaining Metadata for a Local Server

  1. @EventListener
  2. void onServiceStarted(ServiceReadyEvent event) {
  3. ServiceInstance serviceInstance = event.getSource();
  4. ConvertibleValues<String> metadata = serviceInstance.getMetadata();
  5. }