如果已经创建,则忽略 pubsub 主题

Ignore pubsub topic if it already created

我有一个简单的脚本来部署 pubsub 应用程序。

此脚本将 运行 用于我的云 运行 服务的每次部署,并且我有一行:

gcloud pubsub topics create some-topic

如果主题已经存在,我想改进我的脚本,目前如果我 运行 我的脚本,输出将是:

ERROR: Failed to create topic [projects/project-id/topics/some-topic]: Resource already exists in the project (resource=some-topic).

ERROR: (gcloud.pubsub.topics.create) Failed to create the following: [some-topic].

我尝试了标志 --no-user-output-enabled 但没有成功。

如果资源已经存在,有没有办法忽略,或者有办法在创建之前进行检查?

是的。

您可以重复该操作,因为如果主题事先不存在,如果命令成功,它将

你可以吞掉stderr(with2>/dev/null)然后检查之前的命令($?)是否成功(0):

gcloud pubsub topic create do-something 2>/dev/null
if [ $? -eq 0 ]
then
  # Command succeeded, topic did not exist
  echo "Topic ${TOPIC} did not exist, created."
else
  # Command did not succeed, topic may (!) not have existed
  echo "Failure"
fi

NOTE This approach misses the fact that, the command may fail and the topic didn't exist (i.e. some other issue).

或者(更准确且成本更高!)您可以先枚举主题,然后尝试 (!) 创建它(如果它不存在):

TOPIC="some-topic"
RESULT=$(\
  gcloud pubsub topics list \
  --filter="name.scope(topics)=${TOPIC}" \
  --format="value(name)" 2>/dev/null)

if [ "${RESULT}" == "" ]
then
  echo "Topic ${TOPIC} does not exist, creating..."
  gcloud pubsub topics create ${TOPIC}
  if [ $? -eq 0 ]
  then
    # Command succeeded, topic created
  else
    # Command did not succeed, topic was not created
  fi
fi

根据您需求的复杂程度,您可以使用以下方法实现自动化:

  • 任何 Google 的 (Pub/Sub) 库提供更好的错误处理和重试能力。
  • Terraform 例如google_pubsub_topic