oci-cli icon indicating copy to clipboard operation
oci-cli copied to clipboard

Running OCI command in bash script not working

Open FF186 opened this issue 3 years ago • 2 comments

Following bash script

#!/bin/bash
LSL=$(oci iam compartment list  | jq .data[].id)

declare -a ARRAY
ARRAY=($LSL)

for i in "${ARRAY[@]}"; do
  echo "RUNNING: oci compute instance list -c $i | jq '.data[].\"display-name\"'"
  oci compute instance list -c $i | jq '.data[]."display-name"'  
done

I get the following error:

RUNNING: oci compute instance list -c "ocid1.compartment...." | jq '.data[]."display-name"'
ServiceError:
{
    "code": "InvalidParameter",
    "message": "Invalid compartmentId. Please visit https://docs.oracle.com/en-us/iaas/Content/API/References/apierrors.htm to learn more about this error code",
    "opc-request-id": "...",
    "status": 400
}

However when I run the command manually it works without problem.

FF186 avatar Aug 03 '22 08:08 FF186

Issue is with the jq command including " in the output. You need the -r flag so that output will be in raw format.

Please see the below snippet.

#!/bin/bash
LSL=$(oci iam compartment list  | jq -r .data[].id)

declare -a ARRAY
ARRAY=($LSL)

for i in "${ARRAY[@]}"; do
  echo "RUNNING: oci compute instance list -c $i | jq '.data[].\"display-name\"'"
  oci compute instance list -c $i | jq '.data[]."display-name"'  
done

vissree avatar Aug 11 '22 04:08 vissree

You can simplify the script by using xargs to iterate over the compartment list.
In your script or from the command line:

oci iam compartment list  | jq -r .data[].id | 
    xargs -t -L1 -I ID oci compute instance list -c ID | jq -r '.data[]."display-name"'

kevco-us avatar Aug 17 '22 17:08 kevco-us