|
| 1 | +name: Terraform Format and Style |
| 2 | +on: |
| 3 | + pull_request: |
| 4 | + paths: |
| 5 | + - '**.tf' |
| 6 | + - '**.tfvars' |
| 7 | + - '**.tftest.hcl' |
| 8 | + |
| 9 | +jobs: |
| 10 | + check: |
| 11 | + runs-on: ubuntu-latest |
| 12 | + permissions: |
| 13 | + pull-requests: write |
| 14 | + steps: |
| 15 | + - uses: actions/checkout@v4 |
| 16 | + - uses: hashicorp/setup-terraform@v3 |
| 17 | + |
| 18 | + - name: terraform fmt |
| 19 | + id: fmt |
| 20 | + run: terraform fmt -check -recursive -diff |
| 21 | + continue-on-error: true |
| 22 | + |
| 23 | + - uses: actions/github-script@v7 |
| 24 | + if: github.event_name == 'pull_request' |
| 25 | + with: |
| 26 | + github-token: ${{ secrets.GITHUB_TOKEN }} |
| 27 | + script: | |
| 28 | + // 1. Retrieve existing bot comments for the PR |
| 29 | + const { data: comments } = await github.rest.issues.listComments({ |
| 30 | + owner: context.repo.owner, |
| 31 | + repo: context.repo.repo, |
| 32 | + issue_number: context.issue.number, |
| 33 | + }) |
| 34 | + const botComment = comments.find(comment => { |
| 35 | + return comment.user.type === 'Bot' && comment.body.includes('Terraform Format and Style') |
| 36 | + }) |
| 37 | +
|
| 38 | + // 2. Prepare format of the comment |
| 39 | + const output = `#### Terraform Format and Style 🖌\`${{ steps.fmt.outcome }}\` |
| 40 | + <details><summary>Format Output</summary> |
| 41 | +
|
| 42 | + \`\`\`diff\n |
| 43 | + ${{ steps.fmt.outputs.stdout }} |
| 44 | + \`\`\` |
| 45 | +
|
| 46 | + </details>`; |
| 47 | +
|
| 48 | + // 3. If we have a comment, update it, otherwise create a new one |
| 49 | + if (botComment) { |
| 50 | + github.rest.issues.updateComment({ |
| 51 | + owner: context.repo.owner, |
| 52 | + repo: context.repo.repo, |
| 53 | + comment_id: botComment.id, |
| 54 | + body: output |
| 55 | + }) |
| 56 | + } else { |
| 57 | + github.rest.issues.createComment({ |
| 58 | + issue_number: context.issue.number, |
| 59 | + owner: context.repo.owner, |
| 60 | + repo: context.repo.repo, |
| 61 | + body: output |
| 62 | + }) |
| 63 | + } |
| 64 | +
|
| 65 | + - name: Fail on formatting error |
| 66 | + if: ${{ steps.fmt.outcome != 'success' }} |
| 67 | + run: | |
| 68 | + echo "::error title=Terraform::Unresolved formatting errors are present" |
| 69 | + exit 1 |
0 commit comments