Using Cloud Instance Metadata

When Micronaut detects it is running on any of the cloud platforms listed above, such as Google Compute or AWS EC2, upon startup Micronaut will populate 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 of this data is merged together into the metadata property for the running ServiceInstance.

If you need to access the metadata for your application instance you can use the interface EmbeddedServerInstance, and call getMetadata() which will get a map of all of the metadata.

If you are connecting remotely via 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. Flowable.fromPublisher(
  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 inside one of your existing 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.metadata
  5. }