Get OCI compartment ID by name from bash

If you work with Oracle Cloud, it stands to reason you probably want some tooling around it to simplify your regular tasks. You have the option of using a client library with your programming language of choice, or you can use the command line client and have some bash scripts for your regular tasks.

One common argument you will need in performing some tasks is the compartment ID. For this we can run the command: "oci iam compartment list --all".

This will give us a JSON list of all the compartments:

{
  "data": [
    {
        "compartment-id": "ocid1.tenancy.oc1..xxxxx",
        "defined-tags": {},
        "description": "Compartment for Foo",
        "freeform-tags": {},
        "id": "ocid1.compartment.oc1..xxxxx",
        "inactive-status": null,
        "is-accessible": null,
        "lifecycle-state": "ACTIVE",
        "name": "Foo",
        "time-created": "2019-01-22T13:16:26.592000+00:00"
    }
  ]
}

So - what's a good way we could filter out to get the compartment by name?

There is a handy command line tool called jq, which allows you to query a json document easily. So, if we take the above sample and add it into jqplay.org we can develop the syntax for our selector. We come up with the following rule:

.data[] | select(.name == "Foo") | .id



So we can make this simple bash function:


function getCompartmentId {
   local compartmentName=$1

   oci iam compartment list --all | jq -r ".data[] | select(.name == \"${compartmentName}\") | .id"
}

That way in our script we can reference this function to perform some action on that specific compartment.

compartmentId=$(getCompartmentId Transat)
printf "Compartment ID for Foo is \"%s\"\n" $compartmentId 
 
 

Popular posts from this blog

Report row buttons firing a dynamic action

Accessing the last request value from a page submission

Installing Oracle Instant Client on Ubuntu