2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

長過ぎるterraform planの結果をGitHubのPRに自動コメントするときのエラーの対処

Posted at

HashiCorp公式のActionでは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であることによります。
そのため、plan結果が長くなりすぎる場合は以下のようにplan結果の切り詰めを行うと正常に実行されます。

    - 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のセキュリティを高めるためです。

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?