OCI Cloud Shellを使ってリソースの情報を効率よく取得する方法

# 概要

この記事はOracle Cloud Infrastructure（OCI）のCloud Shellを使って、任意のリソース情報を取得する方法を記載します。

## 対象読者

OCIのリソース情報をコンソール画面で取得するのが大変だと感じている人
Cloud Shellで情報を取得する方法を知りたい人

## 環境

OCIのCloud Shell

# コマンドの調べ方

CLIで使えるコマンドは下記のリファレンスに記載されています。

[Oracle Cloud Infrastructure CLI Command Reference](https://docs.oracle.com/en-us/iaas/tools/oci-cli/3.47.0/oci_cli_docs/index.html)

たとえば、Computeの情報を調べる際は、Compute Serviceのリンクを押します。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/302006/b79a8c12-5b89-ebb8-026f-7350a74da98a.png)

Computeの中に様々なコマンドがあるため、自分の必要なコマンドを見つけます。
ここではinstanceを使います。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/302006/75a402d5-827d-f954-4cc3-06a4a5458acc.png)

# 基本

基本的な操作を記載します。例としてComputeのinstanceを用います。

## リソース情報を取得する

情報を取得する場合は`get`または`list`を使います。
`list`はコンパートメント内にあるすべてのComputeリソースを取得し、`get`は指定したComputeリソースの情報を取得します。

そのため基本の流れは

1. コンパートメントIDを調べる
1. `oci hogehoge list`コマンドで一覧情報を取得する
1. 対象のOCIDを取得する
1. `oci hogehoge get`コマンドで特定のリソースの情報を取得する

となります。

### コマンド

```bash:list
oci compute instance list --compartment-id "ocid"
```

<details><summary>list 出力結果</summary>


```json
{
  "data": [
    {
      "agent-config": {
        "are-all-plugins-disabled": false,
        "is-management-disabled": false,
        "is-monitoring-disabled": false,
        "plugins-config": [
          {
            "desired-state": "DISABLED",
            "name": "Vulnerability Scanning"
          },
          {
            "desired-state": "DISABLED",
            "name": "Oracle Java Management Service"
          },
          {
            "desired-state": "ENABLED",
            "name": "OS Management Service Agent"
          },
          {
            "desired-state": "DISABLED",
            "name": "Management Agent"
          },
          {
            "desired-state": "ENABLED",
            "name": "Custom Logs Monitoring"
          },
          {
            "desired-state": "DISABLED",
            "name": "Compute RDMA GPU Monitoring"
          },
          {
            "desired-state": "ENABLED",
            "name": "Compute Instance Run Command"
          },
          {
            "desired-state": "ENABLED",
            "name": "Compute Instance Monitoring"
          },
          {
            "desired-state": "DISABLED",
            "name": "Compute HPC RDMA Auto-Configuration"
          },
          {
            "desired-state": "DISABLED",
            "name": "Compute HPC RDMA Authentication"
          },
          {
            "desired-state": "DISABLED",
            "name": "Block Volume Management"
          },
          {
            "desired-state": "DISABLED",
            "name": "Bastion"
          }
        ]
      },
      "availability-config": {
        "is-live-migration-preferred": null,
        "recovery-action": "RESTORE_INSTANCE"
      },
      "availability-domain": "*****:*****-*****-1-***-1",
      "capacity-reservation-id": null,
      "cluster-placement-group-id": null,
      "compartment-id": "ocid1.****.****.********",
      "dedicated-vm-host-id": null,
      "defined-tags": {
        "Oracle-Tags": {
          "CreatedBy": "********",
          "CreatedOn": "****-**-**T**:**:**.***Z"
        }
      },
      "display-name": "*****",
      "extended-metadata": {},
      "fault-domain": "FAULT-DOMAIN-2",
      "freeform-tags": {},
      "id": "ocid1.instance.****.********",
      "image-id": "ocid1.image.****.********",
      "instance-configuration-id": null,
      "instance-options": {
        "are-legacy-imds-endpoints-disabled": false
      },
      "ipxe-script": null,
      "is-cross-numa-node": false,
      "launch-mode": "PARAVIRTUALIZED",
      "launch-options": {
        "boot-volume-type": "PARAVIRTUALIZED",
        "firmware": "UEFI_64",
        "is-consistent-volume-naming-enabled": true,
        "is-pv-encryption-in-transit-enabled": true,
        "network-type": "PARAVIRTUALIZED",
        "remote-data-volume-type": "PARAVIRTUALIZED"
      },
      "lifecycle-state": "RUNNING",
      "metadata": {
        "ssh_authorized_keys": "ssh-rsa ***** ssh-key-****-**-**"
      },
      "platform-config": null,
      "preemptible-instance-config": null,
      "region": "*****-*****-1",
      "shape": "VM.Standard.E2.1.Micro",
      "shape-config": {
        "baseline-ocpu-utilization": null,
        "gpu-description": null,
        "gpus": 0,
        "local-disk-description": null,
        "local-disks": 0,
        "local-disks-total-size-in-gbs": null,
        "max-vnic-attachments": 1,
        "memory-in-gbs": 1.0,
        "networking-bandwidth-in-gbps": 0.48,
        "ocpus": 1.0,
        "processor-description": "*****"
      },
      "source-details": {
        "boot-volume-size-in-gbs": null,
        "boot-volume-vpus-per-gb": null,
        "image-id": "ocid1.image.****.********",
        "instance-source-image-filter-details": null,
        "kms-key-id": null,
        "source-type": "image"
      },
      "system-tags": {
        "orcl-cloud": {
          "free-tier-retained": "true"
        }
      },
      "time-created": "****-**-**T**:**:**.*********+**:**",
      "time-maintenance-reboot-due": null
    },
    {
      "agent-config": {
        "are-all-plugins-disabled": false,
        "is-management-disabled": false,
        "is-monitoring-disabled": false,
        "plugins-config": [
          {
            "desired-state": "DISABLED",
            "name": "Vulnerability Scanning"
          },
          {
            "desired-state": "DISABLED",
            "name": "Oracle Java Management Service"
          },
          {
            "desired-state": "DISABLED",
            "name": "OS Management Service Agent"
          },
          {
            "desired-state": "DISABLED",
            "name": "OS Management Hub Agent"
          },
          {
            "desired-state": "DISABLED",
            "name": "Management Agent"
          },
          {
            "desired-state": "ENABLED",
            "name": "Custom Logs Monitoring"
          },
          {
            "desired-state": "DISABLED",
            "name": "Compute RDMA GPU Monitoring"
          },
          {
            "desired-state": "ENABLED",
            "name": "Compute Instance Run Command"
          },
          {
            "desired-state": "ENABLED",
            "name": "Compute Instance Monitoring"
          },
          {
            "desired-state": "DISABLED",
            "name": "Compute HPC RDMA Auto-Configuration"
          },
          {
            "desired-state": "DISABLED",
            "name": "Compute HPC RDMA Authentication"
          },
          {
            "desired-state": "ENABLED",
            "name": "Cloud Guard Workload Protection"
          },
          {
            "desired-state": "DISABLED",
            "name": "Block Volume Management"
          },
          {
            "desired-state": "DISABLED",
            "name": "Bastion"
          }
        ]
      },
      "availability-config": {
        "is-live-migration-preferred": null,
        "recovery-action": "RESTORE_INSTANCE"
      },
      "availability-domain": "*****:*****-*****-1-***-1",
      "capacity-reservation-id": null,
      "cluster-placement-group-id": null,
      "compartment-id": "ocid1.****.****.********",
      "dedicated-vm-host-id": null,
      "defined-tags": {
        "Oracle-Tags": {
          "CreatedBy": "********",
          "CreatedOn": "****-**-**T**:**:**.***Z"
        }
      },
      "display-name": "*****",
      "extended-metadata": {},
      "fault-domain": "FAULT-DOMAIN-2",
      "freeform-tags": {},
      "id": "ocid1.instance.****.********",
      "image-id": "ocid1.image.****.********",
      "instance-configuration-id": null,
      "instance-options": {
        "are-legacy-imds-endpoints-disabled": false
      },
      "ipxe-script": null,
      "is-cross-numa-node": false,
      "launch-mode": "PARAVIRTUALIZED",
      "launch-options": {
        "boot-volume-type": "PARAVIRTUALIZED",
        "firmware": "UEFI_64",
        "is-consistent-volume-naming-enabled": true,
        "is-pv-encryption-in-transit-enabled": true,
        "network-type": "PARAVIRTUALIZED",
        "remote-data-volume-type": "PARAVIRTUALIZED"
      },
      "lifecycle-state": "STOPPED",
      "metadata": {
        "ssh_authorized_keys": "ssh-rsa ***** ssh-key-****-**-**"
      },
      "platform-config": null,
      "preemptible-instance-config": null,
      "region": "*****-*****-1",
      "shape": "VM.Standard.E2.1.Micro",
      "shape-config": {
        "baseline-ocpu-utilization": null,
        "gpu-description": null,
        "gpus": 0,
        "local-disk-description": null,
        "local-disks": 0,
        "local-disks-total-size-in-gbs": null,
        "max-vnic-attachments": 1,
        "memory-in-gbs": 1.0,
        "networking-bandwidth-in-gbps": 0.48,
        "ocpus": 1.0,
        "processor-description": "*****"
      },
      "source-details": {
        "boot-volume-size-in-gbs": null,
        "boot-volume-vpus-per-gb": null,
        "image-id": "ocid1.image.****.********",
        "instance-source-image-filter-details": null,
        "kms-key-id": null,
        "source-type": "image"
      },
      "system-tags": {
        "orcl-cloud": {
          "free-tier-retained": "true"
        }
      },
      "time-created": "****-**-**T**:**:**.*********+**:**",
      "time-maintenance-reboot-due": null
    }
  ]
}

```


</details>


```bash:get
oci compute instance get --instance-id "ocid"
```

<details><summary>get 出力結果</summary>


```json
{
  "data": {
    "agent-config": {
      "are-all-plugins-disabled": false,
      "is-management-disabled": false,
      "is-monitoring-disabled": false,
      "plugins-config": [
        {
          "desired-state": "DISABLED",
          "name": "Vulnerability Scanning"
        },
        {
          "desired-state": "DISABLED",
          "name": "Oracle Java Management Service"
        },
        {
          "desired-state": "ENABLED",
          "name": "OS Management Service Agent"
        },
        {
          "desired-state": "DISABLED",
          "name": "Management Agent"
        },
        {
          "desired-state": "ENABLED",
          "name": "Custom Logs Monitoring"
        },
        {
          "desired-state": "DISABLED",
          "name": "Compute RDMA GPU Monitoring"
        },
        {
          "desired-state": "ENABLED",
          "name": "Compute Instance Run Command"
        },
        {
          "desired-state": "ENABLED",
          "name": "Compute Instance Monitoring"
        },
        {
          "desired-state": "DISABLED",
          "name": "Compute HPC RDMA Auto-Configuration"
        },
        {
          "desired-state": "DISABLED",
          "name": "Compute HPC RDMA Authentication"
        },
        {
          "desired-state": "DISABLED",
          "name": "Block Volume Management"
        },
        {
          "desired-state": "DISABLED",
          "name": "Bastion"
        }
      ]
    },
    "availability-config": {
      "is-live-migration-preferred": null,
      "recovery-action": "RESTORE_INSTANCE"
    },
    "availability-domain": "GoDi:AP-OSAKA-1-AD-1",
    "capacity-reservation-id": null,
    "cluster-placement-group-id": null,
    "compartment-id": "[MASKED]",
    "dedicated-vm-host-id": null,
    "defined-tags": {
      "Oracle-Tags": {
        "CreatedBy": "[MASKED]",
        "CreatedOn": "2024-02-13T06:20:06.998Z"
      }
    },
    "display-name": "[MASKED]",
    "extended-metadata": {},
    "fault-domain": "FAULT-DOMAIN-2",
    "freeform-tags": {},
    "id": "[MASKED]",
    "image-id": "[MASKED]",
    "instance-configuration-id": null,
    "instance-options": {
      "are-legacy-imds-endpoints-disabled": false
    },
    "ipxe-script": null,
    "is-cross-numa-node": false,
    "launch-mode": "PARAVIRTUALIZED",
    "launch-options": {
      "boot-volume-type": "PARAVIRTUALIZED",
      "firmware": "UEFI_64",
      "is-consistent-volume-naming-enabled": true,
      "is-pv-encryption-in-transit-enabled": true,
      "network-type": "PARAVIRTUALIZED",
      "remote-data-volume-type": "PARAVIRTUALIZED"
    },
    "lifecycle-state": "RUNNING",
    "metadata": {
      "ssh_authorized_keys": "[MASKED]"
    },
    "platform-config": null,
    "preemptible-instance-config": null,
    "region": "ap-osaka-1",
    "shape": "VM.Standard.E2.1.Micro",
    "shape-config": {
      "baseline-ocpu-utilization": null,
      "gpu-description": null,
      "gpus": 0,
      "local-disk-description": null,
      "local-disks": 0,
      "local-disks-total-size-in-gbs": null,
      "max-vnic-attachments": 1,
      "memory-in-gbs": 1.0,
      "networking-bandwidth-in-gbps": 0.48,
      "ocpus": 1.0,
      "processor-description": "2.0 GHz AMD EPYC\u2122 7551 (Naples)",
      "vcpus": 2
    },
    "source-details": {
      "boot-volume-size-in-gbs": null,
      "boot-volume-vpus-per-gb": null,
      "image-id": "[MASKED]",
      "instance-source-image-filter-details": null,
      "kms-key-id": null,
      "source-type": "image"
    },
    "system-tags": {
      "orcl-cloud": {
        "free-tier-retained": "true"
      }
    },
    "time-created": "2024-02-13T06:20:07.478000+00:00",
    "time-maintenance-reboot-due": null
  },
  "etag": "[MASKED]"
}

```
</details>


## リソース情報をフィルタリングして取得する

上記の出力を見て分かる通り、100行単位の情報がJsonとして出力されます。
ここからほしい情報だけをフィルタリングします。

### --queryオプションを使用する

`oci hogehoge` コマンドで使える`--query`オプションによってフィルタリングします。

たとえば、`oci compute list`の出力結果からOCIDだけを取得する場合は以下のようにします。

```bash
 oci compute instance list --compartment-id "ocid" --query "data[].id"
```

```bash:出力結果
[
  "ocid1.instance.oc1.ap-osaka-1.****gcb7fb6srlov6pbsbqr43py6p7y43ju6zurmybgho6a",
  "ocid1.instance.oc1.ap-osaka-1.****2tgp3vqkv6qkexqkelniph372t2lo25ubngd5wyxb3a"
]
```

`oci compute list`コマンドで出力されるJsonは次のようになっています。
`--query "data[]"`とすると`data`配下の配列内を対象にクエリします。

```json
{
  "data": [
    {},  # ここが対象
    {},  # ここが対象
    ...  # ここが対象
    {}   # ここが対象
  ]
}
```

`--query "data[].id"`とすれば、`data`配下の配列内の要素`id`を取り出します。

```json
{
  "data": [
    {
      "display-name": "hogehoge",
      "id": "ocid"  # ここが対象
      ...
    },  
    {},  
    ...  
    {}   
  ]
}
```

複数の情報をフィルタリングしたい場合は`--query "data[].[id, \"display-name\"]"`とします。

```bash
oci compute instance list --compartment-id "ocid" --query "data[].[id, \"display-name\"]"
```

```出力結果

[
  [
    "ocid1.instance.oc1.ap-osaka-1.anvwsljr4qaav3yc7gcb7fb6srlov6pbsbqr43py6p7y43ju6zurmybgho6a",
    "instance-20240213-1519"
  ],
  [
    "ocid1.instance.oc1.ap-osaka-1.anvwsljr4qaav3ycs2tgp3vqkv6qkexqkelniph372t2lo25ubngd5wyxb3a",
    "instance-20240806-2324"
  ]
]
```

:::note warn
display-nameのようにハイフンなどの特殊文字が入る場合は\\"display-name\\"としてエスケープします。

:::


# 応用

## 複数のリソース情報を取得する

応用として`oci hogehoge list`で取得した複数のIDを使って`oci hogehoge get`を実行するスクリプトを記載します。

```bash

ids=(`oci compute instance list --compartment-id "ocid" --query "data[].id" | jq -r .[]`)

for id in ${ids[@]} ; do 
    oci compute instance get --instance-id ${id} ; 
done

```

`ids`変数は配列にするため`()`で囲みます。

`oci compute ~~ --query`のあとにパイプで`jq`コマンドに渡しています。
これは出力をテキスト出力にするためと、`[]`をなくすためです。

```bash:oci compute ~~ --queryのみ
[
  "ocid1.instance.oc1.ap-osaka-1.****gcb7fb6srlov6pbsbqr43py6p7y43ju6zurmybgho6a",
  "ocid1.instance.oc1.ap-osaka-1.****2tgp3vqkv6qkexqkelniph372t2lo25ubngd5wyxb3a"
]
```

上記のままだと`for`ループに配列として渡せないので、`jq .[]`で`[]`を取ります。

```bash:oci compute ~~ --query | jq .[]
"ocid1.instance.oc1.ap-osaka-1.****gcb7fb6srlov6pbsbqr43py6p7y43ju6zurmybgho6a"
"ocid1.instance.oc1.ap-osaka-1.****2tgp3vqkv6qkexqkelniph372t2lo25ubngd5wyxb3a"
```

上記のままだと、`"ocid"`のように`""`でIDが囲まれてしまっており、このまま`oci`コマンドに渡すとOCIDが一致せずにエラーが発生します。

そのため、`jq -r .[]`とします。
これは`raw text`で出力するオプションです。

```bash:oci compute ~~ --query | jq .[]
ocid1.instance.oc1.ap-osaka-1.****gcb7fb6srlov6pbsbqr43py6p7y43ju6zurmybgho6a
ocid1.instance.oc1.ap-osaka-1.****2tgp3vqkv6qkexqkelniph372t2lo25ubngd5wyxb3a
```

あとはbashの`for`ループでIDを取り出して`oci hogehoge get`コマンドを実行します。

任意の`--query`オプションをつけて出力をカスタマイズしてください。

# 参考

## OCI公式ドキュメント
[CLIの使用](https://docs.oracle.com/ja-jp/iaas/Content/API/SDKDocs/cliusing.htm)

## jqのraw出力
[How to remove double-quotes in jq output for parsing json files in bash?](https://stackoverflow.com/questions/44656515/how-to-remove-double-quotes-in-jq-output-for-parsing-json-files-in-bash)

質問
https://stackoverflow.com/q/44656515

参考にした回答
https://stackoverflow.com/a/44656583