|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +# wrap takes some output and wraps it in a collapsible markdown section if |
| 4 | +# it's over $TF_ACTION_WRAP_LINES long. |
| 5 | +wrap() { |
| 6 | + if [[ $(echo "$1" | wc -l) -gt ${TF_ACTION_WRAP_LINES:-20} ]]; then |
| 7 | + echo " |
| 8 | +<details><summary>Show Output</summary> |
| 9 | +
|
| 10 | +\`\`\` |
| 11 | +$1 |
| 12 | +\`\`\` |
| 13 | +
|
| 14 | +</details> |
| 15 | +" |
| 16 | +else |
| 17 | + echo " |
| 18 | +\`\`\` |
| 19 | +$1 |
| 20 | +\`\`\` |
| 21 | +" |
| 22 | +fi |
| 23 | +} |
| 24 | + |
| 25 | +set -e |
| 26 | + |
| 27 | +cd "${TF_ACTION_WORKING_DIR:-.}" |
| 28 | + |
| 29 | +if [[ ! -z "$TF_ACTION_TFE_TOKEN" ]]; then |
| 30 | + cat > ~/.terraformrc << EOF |
| 31 | +credentials "${TF_ACTION_TFE_HOSTNAME:-app.terraform.io}" { |
| 32 | + token = "$TF_ACTION_TFE_TOKEN" |
| 33 | +} |
| 34 | +EOF |
| 35 | +fi |
| 36 | + |
| 37 | +if [[ ! -z "$TF_ACTION_WORKSPACE" ]] && [[ "$TF_ACTION_WORKSPACE" != "default" ]]; then |
| 38 | + terraform workspace select "$TF_ACTION_WORKSPACE" |
| 39 | +fi |
| 40 | + |
| 41 | +set +e |
| 42 | +OUTPUT=$(sh -c "TF_IN_AUTOMATION=true terraform apply -no-color -auto-approve -input=false $*" 2>&1) |
| 43 | +SUCCESS=$? |
| 44 | +echo "$OUTPUT" |
| 45 | +set -e |
| 46 | + |
| 47 | +# If PR_DATA is null, then this is not a pull request event and so there's |
| 48 | +# no where to comment. |
| 49 | +PR_DATA=$(cat /github/workflow/event.json | jq -r .pull_request) |
| 50 | +if [ "$TF_ACTION_COMMENT" = "1" ] || [ "$TF_ACTION_COMMENT" = "false" ] || [ "$PR_DATA" = "null" ]; then |
| 51 | + exit $SUCCESS |
| 52 | +fi |
| 53 | + |
| 54 | +# Build the comment we'll post to the PR. |
| 55 | +COMMENT="" |
| 56 | +if [ $SUCCESS -ne 0 ]; then |
| 57 | + OUTPUT=$(wrap "$OUTPUT") |
| 58 | + COMMENT="#### \`terraform apply\` Failed |
| 59 | +$OUTPUT |
| 60 | +
|
| 61 | +*Workflow: \`$GITHUB_WORKFLOW\`, Action: \`$GITHUB_ACTION\`*" |
| 62 | +else |
| 63 | + # Call wrap to optionally wrap our output in a collapsible markdown section. |
| 64 | + OUTPUT=$(wrap "$OUTPUT") |
| 65 | + COMMENT="#### \`terraform apply\` Success |
| 66 | +$OUTPUT |
| 67 | +
|
| 68 | +*Workflow: \`$GITHUB_WORKFLOW\`, Action: \`$GITHUB_ACTION\`*" |
| 69 | +fi |
| 70 | + |
| 71 | +# Post the comment. |
| 72 | +PAYLOAD=$(echo '{}' | jq --arg body "$COMMENT" '.body = $body') |
| 73 | +COMMENTS_URL=$(cat /github/workflow/event.json | jq -r .pull_request.comments_url) |
| 74 | +curl -s -S -H "Authorization: token $GITHUB_TOKEN" --header "Content-Type: application/json" --data "$PAYLOAD" "$COMMENTS_URL" > /dev/null |
| 75 | + |
| 76 | +exit $SUCCESS |
0 commit comments