You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Terraform plan输出转换为Bitbucket API可接受的JSON格式

Terraform Plan输出转Bitbucket API评论格式Bash实现方案

实现思路

Bitbucket Cloud提交评论API要求传入合法JSON格式的请求体,评论内容需要包装为Markdown代码块,核心难点是对Terraform Plan输出中的特殊字符(双引号、反斜杠、换行符等)做正确的JSON转义,避免请求格式错误。

最优实现方案(依赖jq,推荐)

使用jq做JSON序列化,无需手动处理转义规则,稳定性最高,适配所有Plan输出场景:
首先安装依赖(绝大多数Linux发行版官方源可直接安装):

# Debian/Ubuntu
apt install jq
# RHEL/CentOS
yum install jq

完整执行脚本:

# 1. 执行Terraform Plan并保存输出
terraform plan | tee tfplan.txt

# 2. 生成符合API要求的JSON请求体
# 自动对Plan内容做JSON转义,并包装为Markdown代码块
jq -n --rawfile plan_content tfplan.txt '
{
  "content": {
    "raw": "\n\n```\n\($plan_content)\n```\n"
  }
}' > comment_payload.json

# 3. 调用Bitbucket API提交评论
# 替换以下参数为你自己的配置
WORKSPACE="你的工作空间标识"
REPO_SLUG="你的仓库标识"
COMMIT_HASH="目标提交哈希值"
BITBUCKET_USER="你的账号用户名"
BITBUCKET_APP_PWD="你的应用密码" # 需配置仓库评论权限

curl -X POST \
  -u "${BITBUCKET_USER}:${BITBUCKET_APP_PWD}" \
  -H "Content-Type: application/json" \
  -d @comment_payload.json \
  "https://api.bitbucket.org/2.0/repositories/${WORKSPACE}/${REPO_SLUG}/commit/${COMMIT_HASH}/comments"

轻量实现方案(无依赖,纯sed)

如果环境无法安装jq,可以用sed手动做转义,仅建议Plan输出无特殊字符的场景使用:

# 直接生成请求体并调用API
{
  echo '{"content": {"raw": "\n\n```\n'
  sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/$/\\r\\n/g' tfplan.txt
  echo '```\n"}}'
} | curl -X POST \
  -u "${BITBUCKET_USER}:${BITBUCKET_APP_PWD}" \
  -H "Content-Type: application/json" \
  -d @- \
  "https://api.bitbucket.org/2.0/repositories/${WORKSPACE}/${REPO_SLUG}/commit/${COMMIT_HASH}/comments"

内容的提问来源于stack exchange,提问作者Angelo Pace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:36:03