@@ -19,6 +19,18 @@ if [[ -z "${RESOURCE_GROUP_ID}" ]]; then
1919 exit 1
2020fi
2121
22+ # ENVIRONMENT VARIABLE VALIDATION
23+ if [[ -z " ${IAM_TOKEN} " ]]; then
24+ echo " Environment variable IAM_TOKEN is not set." >&2
25+ exit 1
26+ fi
27+
28+ if [[ -z " ${ACCOUNT_ID} " ]]; then
29+ echo " Environment variable ACCOUNT_ID is not set." >&2
30+ exit 1
31+ fi
32+
33+
2234get_cloud_endpoint () {
2335 iam_cloud_endpoint=" ${IBMCLOUD_IAM_API_ENDPOINT:- " iam.cloud.ibm.com" } "
2436 IBMCLOUD_IAM_API_ENDPOINT=${iam_cloud_endpoint# https:// }
@@ -45,17 +57,51 @@ reset=true
4557# Function to fetch data and handle pagination
4658fetch_data () {
4759 local url=" $IAM_URL "
60+ local fetch_attempt=0
61+ local retry_wait_time=5
4862
4963 while [ " $url " != " null" ]; do
50- # Fetch data from the API
51- IAM_RESPONSE=$( curl -s " $url " --header " Authorization: $IAM_TOKEN " --header " Content-Type: application/json" )
52-
53- ERROR_MESSAGE=$( echo " ${IAM_RESPONSE} " | jq ' has("errors")' )
54- if [[ " ${ERROR_MESSAGE} " != false ]]; then
55- echo " ${IAM_RESPONSE} " | jq ' .errors'
56- echo " Could not obtain api keys"
57- exit 1
58- fi
64+ fetch_attempt=0
65+ # Retry loop for each API call
66+ while [ $fetch_attempt -lt $MAX_ATTEMPTS ]; do
67+
68+ # Fetch data from the API
69+ IAM_RESPONSE=$( curl -s " $url " --header " Authorization: $IAM_TOKEN " --header " Content-Type: application/json" )
70+
71+ # check if the response is valid JSON.
72+ if ! echo " ${IAM_RESPONSE} " | jq -e . > /dev/null 2>&1 ; then
73+ echo " Error: API did not return valid JSON on attempt $(( fetch_attempt + 1 )) ." >&2
74+ echo " Response was: ${IAM_RESPONSE} " >&2
75+ fetch_attempt=$(( fetch_attempt + 1 ))
76+
77+ if [ $fetch_attempt -lt $MAX_ATTEMPTS ]; then
78+ echo " Retrying in ${retry_wait_time} seconds..." >&2
79+ sleep $retry_wait_time
80+ continue
81+ else
82+ echo " Maximum retry attempts reached for fetching data." >&2
83+ exit 1
84+ fi
85+ fi
86+
87+ ERROR_MESSAGE=$( echo " ${IAM_RESPONSE} " | jq ' has("errors")' )
88+ if [[ " ${ERROR_MESSAGE} " != false ]]; then
89+ echo " API returned errors on attempt $(( fetch_attempt + 1 )) :" >&2
90+ echo " ${IAM_RESPONSE} " >&2
91+ fetch_attempt=$(( fetch_attempt + 1 ))
92+
93+ if [ $fetch_attempt -lt $MAX_ATTEMPTS ]; then
94+ echo " Retrying in ${retry_wait_time} seconds..." >&2
95+ sleep $retry_wait_time
96+ continue
97+ else
98+ echo " Maximum retry attempts reached. Could not obtain api keys." >&2
99+ exit 1
100+ fi
101+ fi
102+ # Success - break out of retry loop
103+ break
104+ done
59105
60106 next_url=$( echo " ${IAM_RESPONSE} " | jq -r ' .next' )
61107 key_descriptions=$( echo " $IAM_RESPONSE " | jq -r --arg name " ${APIKEY_KEY_NAME} " ' .apikeys | .[] | select(.name == $name) | .description' )
0 commit comments