Sunday, February 4, 2024

 

How to Get OCI Region and Instance Metadata from a Linux Server

When working with Oracle Cloud Infrastructure (OCI), there are times when you need to quickly fetch instance-level metadata — like the region, availability domain, shape, and other details — directly from the server. Fortunately, OCI exposes a handy metadata service that makes this easy to access from the command line.

In this post, I’ll show you how to pull just the region using curl, and also explain what other information is available if you query the full metadata endpoint.


Fetching the Region of an OCI Instance

To retrieve the region (like me-dubai-1) of an instance running on OCI, you can use:

curl -s http://169.254.169.254/opc/v1/instance/ | grep '"region":' | awk -F '"' '{print $4}'


[root@<Servername> <foldername>]# curl -s http://169.254.169.254/opc/v1/instance/ |grep region


  "region": "me-dubai-1",

  "regionInfo": {

    "regionIdentifier": "me-dubai-1",

    "regionKey": "DXB"

}

Another method to use is JQ

curl -s http://169.254.169.254/opc/v1/instance/ | jq -r '.region'

To get the complete instance metadata  

You’ll get the entire instance metadata in JSON format. Here’s a trimmed sample of what that might look like:

{
  "availabilityDomain": "",
  "compartmentId": "OCID",
  "displayName": "instance Name",
  "faultDomain": "FAULT-DOMAIN-1",
  "hostname": "Hostname of the Instance ",
  "id": "ocid ..",
  "image": "which version of O/S image had been used,
  "region": "me-dubai-1",
  "regionInfo": {
    "regionIdentifier": "me-dubai-1",
    "regionKey": "DXB"
  },
  "shape": "Type of VM",  like VM standard flexe4
  "state": "Running",
  "timeCreated": ",
  "metadata": {
    "ssh_authorized_keys": "SSH keys associated with the instance "
  }
}

Some key fields 

Field
Description
region
 The region where the instance is running
availability Domain
 Availability Domain (e.g., ME-DUBAI-1-AD-1)
compartment Id      
OCID of the compartment
shape
Instance shape (e.g., VM.Standard.E4.Flex)
display Name
Name of the instance
hostname
Hostname of  the instance
id
OCID of the instance
state
Instance lifecycle state (e.g., Running) 

Formatting JSON Output (Without jq)

If jq isn’t installed, you can still format the JSON nicely using Python:

curl -s http://169.254.169.254/opc/v1/instance/ | python3 -m json.tool

Notes:

The instance metadata service is local and does not require any credentials or internet access. It’s a super handy tool for automation scripts, configuration checks, or logging environment info in multi-region deployments.