|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +export COMPARTMENT_ID="${1}" |
| 4 | +export GROUP_ID="${2}" |
| 5 | +export RESOURCE_TYPES="${3}" |
| 6 | + |
| 7 | +output_file="oci_resources_${GROUP_ID}_${COMPARTMENT_ID}.json" |
| 8 | +echo "[]" > $output_file # Initialize the output file with an empty JSON array |
| 9 | +IFS=',' read -ra types <<< "$RESOURCE_TYPES" |
| 10 | + |
| 11 | +# Perform OCI CLI query for each resource type |
| 12 | +for rt in "${types[@]}"; do |
| 13 | + # Initialize variables for pagination |
| 14 | + next_page="init" |
| 15 | + |
| 16 | + # Loop through pages |
| 17 | + while [ "$next_page" != "null" ]; do |
| 18 | + if [ "$next_page" == "init" ]; then |
| 19 | + # First query without next page token |
| 20 | + response=$(oci search resource structured-search --query-text \ |
| 21 | + "QUERY $rt resources where compartmentId = '$COMPARTMENT_ID' && lifeCycleState != 'TERMINATED' && lifeCycleState != 'FAILED'" \ |
| 22 | + --output json) |
| 23 | + else |
| 24 | + # Query with next page token |
| 25 | + response=$(oci search resource structured-search --query-text \ |
| 26 | + "QUERY $rt resources where compartmentId = '$COMPARTMENT_ID' && lifeCycleState != 'TERMINATED' && lifeCycleState != 'FAILED'" \ |
| 27 | + --page "$next_page" \ |
| 28 | + --output json) |
| 29 | + fi |
| 30 | + |
| 31 | + # Check if the response contains an error |
| 32 | + if [ -z "$response" ]; then |
| 33 | + # Log ServiceError responses |
| 34 | + echo "ServiceError for $GROUP_ID, resource type: $rt" >> error.log |
| 35 | + break |
| 36 | + fi |
| 37 | + |
| 38 | + # Extract next page token |
| 39 | + next_page=$(echo "$response" | jq -r '."opc-next-page" // "null"') |
| 40 | + |
| 41 | + # Extract and transform items |
| 42 | + items=$(echo "$response" | jq --arg group_id "$GROUP_ID" -c '[.data.items[] | {compartmentId: ."compartment-id", displayName: ."display-name", identifier: ."identifier", resourceType: ."resource-type", groupId: $group_id}]') |
| 43 | + # Append items to the output file if not empty |
| 44 | + if [ "$(echo "$items" | jq length)" -gt 0 ]; then |
| 45 | + temp_items_file="temp_items_$${GROUP_ID}_$${COMPARTMENT_ID}.json" |
| 46 | + echo "$items" > "$temp_items_file" |
| 47 | + jq -s '.[0] + .[1]' "$output_file" "$temp_items_file" > tmp_${GROUP_ID}_${COMPARTMENT_ID}.json && mv tmp_${GROUP_ID}_${COMPARTMENT_ID}.json "$output_file" |
| 48 | + rm -f "$temp_items_file" |
| 49 | + fi |
| 50 | + done |
| 51 | +done |
| 52 | + |
| 53 | +# Read the file's content and return it as a JSON-encoded string |
| 54 | +content=$(jq -c . < "$output_file") |
| 55 | +rm -f "$output_file" |
| 56 | +echo "{\"content\": \"$(echo "$content" | sed 's/"/\\"/g')\"}" |
0 commit comments