簡體   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