Skip to content

Instantly share code, notes, and snippets.

@solarmicrobe
Created February 3, 2025 21:45
Show Gist options
  • Save solarmicrobe/baf8906753ef6717b7c86addf6a10844 to your computer and use it in GitHub Desktop.
Save solarmicrobe/baf8906753ef6717b7c86addf6a10844 to your computer and use it in GitHub Desktop.
Delete all resources from compartment in OCI
#!/usr/bin/env bash
# Taken from https://stackoverflow.com/a/65676174
# Input parameter pattern changed and run through shellcheck
delcmpt(){
if [ -z ${OCI_TENANCY_NAME+x} ]; then
echo "Tenancy Name:"
read -r OCI_TENANCY_NAME
echo ""
fi
if [ -z ${OCI_TENANCY_OCID+x} ]; then
echo "Tenancy OCID:"
read -r OCI_TENANCY_OCID
echo ""
fi
if [ -z ${OCI_CMPT_ID+x} ]; then
echo "Compartment IC:"
read -r OCI_CMPT_ID
echo ""
fi
if [ -z ${OCI_REGIONS+x} ]; then
declare -a OCI_REGIONS=("SJC"
"PHX" "IAD"
"BOM"
)
fi
OCI_CMPT_NAME=$(oci iam compartment get -c "${OCI_CMPT_ID}" | jq '.data.name')
echo -n "Compartment being deleted is ${OCI_CMPT_NAME} for ${#OCI_REGIONS[@]} regions ("
for r in "${OCI_REGIONS[@]}"; do
echo -n "$r "
done
echo ")."
for OCI_REGION_CODE in "${OCI_REGIONS[@]}"; do
echo "Deleting all resources in $OCI_REGION_CODE"
UNIQUE_STACK_ID=$(date "+DATE_%Y_%m_%d_TIME_%H_%M")
OCID_CMPT_STACK=$(oci resource-manager stack create-from-compartment --compartment-id "${OCI_TENANCY_OCID}" \
--config-source-compartment-id "${OCI_CMPT_ID}" \
--config-source-region "${OCI_REGION_CODE}" --terraform-version "1.0.x"\
--display-name "Stack_${UNIQUE_STACK_ID}_${OCI_REGION_CODE}" --description "Stack From Compartment ${OCI_CMPT_NAME} for region ${OCI_REGION_CODE}" --wait-for-state SUCCEEDED --query "data.resources[0].identifier" --raw-output)
echo "$OCID_CMPT_STACK"
oci resource-manager job create-destroy-job --execution-plan-strategy 'AUTO_APPROVED' --stack-id "${OCID_CMPT_STACK}" --wait-for-state SUCCEEDED --max-wait-seconds 300
# twice since it fails sometimes and running it twice and is idempotent
oci resource-manager job create-destroy-job --execution-plan-strategy 'AUTO_APPROVED' --stack-id "${OCID_CMPT_STACK}" --wait-for-state SUCCEEDED --max-wait-seconds 540
oci resource-manager stack delete --stack-id "${OCID_CMPT_STACK}" --force --wait-for-state DELETED
done
oci iam compartment delete -c "${OCI_CMPT_ID}" --force --wait-for-state SUCCEEDED
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment