繁体   English   中英

如何将多行字符串文件解析为 API 可以接受的单个 JSON 字符串?

[英]How can i parse a multi-line file of strings into a single JSON string that can be accepted by an API?

我试图弄清楚如何解析 Terraform 计划文件,以便我可以将其发布为针对 Bitbucket 云中的提交或拉取请求的评论。 我正在使用的 api 端点在这里: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/#api-repositories-workspace-repo-slug-commit-commit-comments-post

我运行 terraform 计划并将 output 发送到一个名为 tfplan.txt 的文件,它看起来像这样:

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create
 <= read (data resources)

Terraform will perform the following actions:

  # data.aws_iam_policy_document.combined_bucket_policy will be read during apply
  # (config refers to values not yet known)
 <= data "aws_iam_policy_document" "combined_bucket_policy"  {
      + id                      = (known after apply)
      + json                    = (known after apply)
      + source_json             = (known after apply)
      + source_policy_documents = []
    }

我需要将此 output 转换为 api 端点可以接受的东西。 当我通过 Bitbucket Cloud web 接口执行此操作,并使用 Inspect 捕获 output 时,其格式如下:(为简洁起见截断)

"\n\n```\nTerraform 使用选定的提供程序来生成以下执行\r\n计划。资源操作用以下符号表示:\r\n + create\r\n <= read(数据资源) \r\n\r\nTerraform 将执行以下操作:\r\n\r\n # data.aws_iam_policy_document.combined_bucket_policy 将在应用期间读取\r\n #(配置指的是未知的值)\r\ n <= data "aws_iam_policy_document" "combined_bucket_policy" {\r\n + id =(应用后已知)\r\n + json =(应用后已知)\r\n + source_json =(应用后已知)\r\ n + source_policy_documents = []\r\n }

什么是有效的方法,最好是在 bash 中,我可以将计划 output 转换为可接受的结构以发送到 api?

谢谢

您可以做几件事来简化这里的解析。

TF_LOG_PATH变量,因此您可以将 terraform 自动 output 写入文件。

TF_LOG变量允许您将内容类型设置为 JSON。 这实际上是一个跟踪,但无论如何,日志现在变得更容易解析。

一旦有了可解析的日志文件,您就可以使用 JQ 实用程序轻松过滤您需要的内容并将它们构建到新的 JSON 字符串中。

一旦有了包含消息的新 JSON 字符串,您就可以构建需要传递给 curl 以调用端点的字符串。 根据我的经验,PR 消息比包含代码引用的提交消息要简单得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM