在GitHub的PR上自动评论terraform plan结果太长时出现的错误处理

在HashiCorp的官方文档中提供了一个示例,可以自动将terraform plan的结果作为评论发布到GitHub的PR上。

 

然而,如果使用这种方法,当plan结果过长时会引发以下错误。

An error occurred trying to start process '/home/runner/runners/2.303.0/externals/node16/bin/node' with working directory '/home/runner/work/<リポジトリ名>/<リポジトリ名>'.
Argument list too long

由于GitHub Actions的环境变量的最大长度为65535,所以如果计划结果过长,可以通过截断计划结果来正常执行。

    - name: Terraform Plan
      run: |
        terraform-bin plan -out=tfplan
        terraform-bin show -no-color tfplan > show_result.txt
        plan_result=$(cat show_result.txt)
        tf_plan_summary=$(grep -x -E "Plan: [0-9]+ to add, [0-9]+ to change, [0-9]+ to destroy\.|No changes. .*" show_result.txt) || true
        echo "TF_PLAN_SUMMARY=${tf_plan_summary}" >> $GITHUB_ENV
        EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
        echo "TRUNCATED_TF_PLAN<<$EOF" >> $GITHUB_ENV
        echo "${plan_result:0:65536}" >> $GITHUB_ENV
        echo "$EOF" >> $GITHUB_ENV
    
    - uses: actions/github-script@v6
      id: tf_plan_result
      with:
        github-token: ${{ secrets.GITHUB_TOKEN }}
        result-encoding: string
        script: |
          const tf_plan = process.env.TRUNCATED_TF_PLAN;
          const tf_plan_summary = process.env.TF_PLAN_SUMMARY.length == 0 ? "Unexpected plan output." : process.env.TF_PLAN_SUMMARY
          const run_id = process.env.GITHUB_RUN_ID;
          const repository_name = process.env.GITHUB_REPOSITORY;
          const tf_plan_in_comment = tf_plan.length == 65536 ? "\nTerraform plan too long. Refer to its workflow run in Actions tab for the full-length plan.\n\n" + tf_plan + "...\n" : tf_plan;

          const output = `#### terraform plan: \`${ tf_plan_summary }\`
          [CI Details](https://github.com/${ repository_name }/actions/runs/${ run_id })

          <details><summary>Show Plan</summary>
            \`\`\`
            ${ tf_plan_in_comment }
            \`\`\`
          </details>

          ---

          *Pusher: Action: \`${{ github.event_name }}\`, Workflow: \`${{ github.workflow }}\`*`;

          return output

通过setup-terraform操作设置的terraform命令是GitHub Actions内部使用的包装器,它还输出了用于内部使用的信息,以便使用原始的terraform命令,需要使用terraform-bin命令。

 

另外,每次从随机数中生成EOF是为了增强GitHub Actions的安全性。

 

广告
将在 10 秒后关闭
bannerAds