Skip to content

Instantly share code, notes, and snippets.

@jroehl
Last active September 5, 2023 14:42
Show Gist options
  • Save jroehl/e96378b14cf35213bfdae060d965ec6f to your computer and use it in GitHub Desktop.
Save jroehl/e96378b14cf35213bfdae060d965ec6f to your computer and use it in GitHub Desktop.

Bash script to delete all entries of a specific content type of a contentful space

Usage

bash <(curl -s https://gist.githubusercontent.com/jroehl/e96378b14cf35213bfdae060d965ec6f/raw/unpublishAndDelete.sh) "contentTypeId"

#!/bin/bash
# Configuration
ACCESS_TOKEN=${CONTENTFUL_MANAGEMENT_TOKEN}
SPACE_ID=${CONTENTFUL_SPACE_ID}
ENVIRONMENT_ID=${CONTENTFUL_ENVIRONMENT_ID}
CONTENT_TYPE=$1
LIMIT=250
SKIP=0
if [ -z "$ACCESS_TOKEN" ] || [ -z "$SPACE_ID" ] || [ -z "$ENVIRONMENT_ID" ] || [ -z "$CONTENT_TYPE" ]; then
echo "Please provide all required parameters."
exit 1
fi
read -p "Are you sure you want to unpublish and delete all entries of content type $CONTENT_TYPE in space $SPACE_ID/$ENVIRONMENT_ID (y/n)? " answer
case ${answer:0:1} in
y|Y )
echo "Proceeding..."
;;
* )
echo "Aborted."
exit 1
;;
esac
# Function to unpublish an entry
unpublish_entry() {
RESPONSE=$(curl -s -X DELETE "https://api.contentful.com/spaces/$SPACE_ID/environments/$ENVIRONMENT_ID/entries/$1/published" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "X-Contentful-Version: $2" \
--write-out %{http_code} \
--silent \
--output /dev/null)
if [[ $RESPONSE -ne 200 ]]; then
echo "Failed to unpublish entry with ID: $1"
fi
}
# Function to delete an entry
delete_entry() {
curl -s -X DELETE "https://api.contentful.com/spaces/$SPACE_ID/environments/$ENVIRONMENT_ID/entries/$1" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "X-Contentful-Version: $2" > /dev/null
}
# Fetch entries
while true; do
ENTRIES=$(curl -s "https://api.contentful.com/spaces/$SPACE_ID/environments/$ENVIRONMENT_ID/entries?content_type=$CONTENT_TYPE&limit=$LIMIT&skip=$SKIP&select=sys" \
-H "Authorization: Bearer $ACCESS_TOKEN")
COUNT=$(echo $ENTRIES | jq '.items | length')
# Break if there are no more entries
if [[ $COUNT -eq 0 ]]; then
break
fi
# Iterate over each entry
for i in $( seq 0 $(($COUNT -1)) ); do
ID=$(echo $ENTRIES | jq -r ".items[$i].sys.id")
VERSION=$(echo $ENTRIES | jq -r ".items[$i].sys.version")
echo "Unpublishing and deleting entry with ID: $ID"
unpublish_entry $ID $VERSION
delete_entry $ID $VERSION
done
# Update SKIP for next batch
SKIP=$((SKIP + LIMIT))
done
echo "All done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment