Skip to content

Instantly share code, notes, and snippets.

@Daenyth
Created June 12, 2024 17:31
Show Gist options
  • Save Daenyth/38d52aebc29fe9cff1b5e44d558ba5ba to your computer and use it in GitHub Desktop.
Save Daenyth/38d52aebc29fe9cff1b5e44d558ba5ba to your computer and use it in GitHub Desktop.
Create a topic and subscription for gcp pubsub local emulator, idempotently
#!/usr/bin/env bash
# Exit immediately if a command exits with a non-zero status.
set -e
# Treat unset variables as an error and exit immediately.
set -u
# Return the exit status of the last command in the pipeline that failed.
set -o pipefail
PROJECT_ID="MYPROJECT"
TOPIC_ID="MYTOPIC"
SUBSCRIPTION_ID="MYSUB"
# We want maximum time since backfill can be slow potentially
ACK_DEADLINE_SECONDS=600
PROJECT_URL="http://$PUBSUB_EMULATOR_HOST/v1/projects/${PROJECT_ID}"
create_topic() {
curl -X PUT \
-H "Content-Type: application/json" \
"$PROJECT_URL/topics/${TOPIC_ID}"
echo "Topic '${TOPIC_ID}' created successfully."
}
create_subscription() {
curl -X PUT \
-H "Content-Type: application/json" \
-d "{
\"topic\": \"projects/${PROJECT_ID}/topics/${TOPIC_ID}\",
\"ackDeadlineSeconds\": ${ACK_DEADLINE_SECONDS}
}" \
"$PROJECT_URL/subscriptions/${SUBSCRIPTION_ID}"
echo "Subscription '${SUBSCRIPTION_ID}' created successfully."
}
# Check if the topic already exists
if curl -s "$PROJECT_URL/topics/${TOPIC_ID}" | grep -q "${TOPIC_ID}"; then
echo "Topic '${TOPIC_ID}' already exists."
else
create_topic
fi
# Check if the subscription already exists
if curl -s "$PROJECT_URL/subscriptions/${SUBSCRIPTION_ID}" | grep -q "${SUBSCRIPTION_ID}"; then
echo "Subscription '${SUBSCRIPTION_ID}' already exists."
else
create_subscription
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment