-
Notifications
You must be signed in to change notification settings - Fork 0
261 lines (248 loc) · 9.67 KB
/
Copy pathterraform-plan.yml
File metadata and controls
261 lines (248 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
name: 'Terraform Plan'
# Runs `terraform plan` against real cloud state via GitHub OIDC, uploads the
# binary plan as an artifact (consumed by terraform-apply), and optionally posts
# the plan to the PR and estimates cost with Infracost.
on:
workflow_call:
inputs:
terraform-path:
description: 'Directory containing the Terraform configuration'
required: true
type: string
terraform-version:
description: 'Terraform version (exact, range, or "latest")'
required: false
type: string
default: 'latest'
var-file:
description: 'Path to a .tfvars file, relative to terraform-path'
required: false
type: string
default: ''
backend-config:
description: 'Path to a backend config file for `terraform init -backend-config` (relative to terraform-path)'
required: false
type: string
default: ''
checkout-ref:
description: 'Git ref to checkout before planning (default: the triggering SHA). Useful when an earlier job commits desired terraform inputs to a branch, then this plan should run against that updated ref.'
required: false
type: string
default: ''
aws-region:
description: 'AWS region for provider/backend'
required: false
type: string
default: 'us-west-2'
plan-artifact-name:
description: 'Name of the uploaded plan artifact (pass the same to terraform-apply)'
required: false
type: string
default: 'tfplan'
post-pr-comment:
description: 'Post the plan to the PR as a comment (PR events only)'
required: false
type: boolean
default: true
cost-estimation:
description: 'Run Infracost on the plan (requires infracost-api-key secret)'
required: false
type: boolean
default: false
allow-destroys:
description: 'Allow resources to be destroyed by this plan. false = fail after planning if any destroy/replace is present (artifacts still upload).'
required: false
type: boolean
default: false
runs-on:
description: 'Runner label to execute the job on'
required: false
type: string
default: 'ubuntu-latest'
secrets:
aws-role-arn:
description: 'IAM role ARN to assume via GitHub OIDC'
required: false
infracost-api-key:
description: 'Infracost API key (only used when cost-estimation=true)'
required: false
cloudflare-api-key:
description: 'Cloudflare Global API Key (optional; required only when the terraform uses the Cloudflare provider)'
required: false
cloudflare-email:
description: 'Cloudflare API Email (optional; required only when the terraform uses the Cloudflare provider)'
required: false
outputs:
has-changes:
description: 'true when the plan contains changes'
value: ${{ jobs.plan.outputs.has-changes }}
plan-artifact-name:
description: 'Name of the uploaded plan artifact'
value: ${{ inputs.plan-artifact-name }}
destroy-count:
description: 'Number of resources this plan would destroy (including replacements)'
value: ${{ jobs.plan.outputs.destroy-count }}
has-destroys:
description: 'true when the plan includes any delete/delete-create/create-delete actions'
value: ${{ jobs.plan.outputs.has-destroys }}
permissions:
contents: read
id-token: write
pull-requests: write
jobs:
plan:
name: Terraform Plan
runs-on: ${{ inputs.runs-on }}
timeout-minutes: 20
defaults:
run:
working-directory: ${{ inputs.terraform-path }}
env:
AWS_ROLE_ARN: ${{ secrets.aws-role-arn }}
CLOUDFLARE_API_KEY: ${{ secrets.cloudflare-api-key }}
CLOUDFLARE_EMAIL: ${{ secrets.cloudflare-email }}
outputs:
has-changes: ${{ steps.plan.outputs.has-changes }}
destroy-count: ${{ steps.analyze.outputs.destroy-count }}
has-destroys: ${{ steps.analyze.outputs.has-destroys }}
steps:
- name: Checkout repository
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
ref: ${{ inputs.checkout-ref || github.sha }}
- name: Configure AWS credentials
if: env.AWS_ROLE_ARN != ''
uses: aws-actions/configure-aws-credentials@254c19bd240aabef8777f48595e9d2d7b972184b # v6.2.1
with:
role-to-assume: ${{ env.AWS_ROLE_ARN }}
aws-region: ${{ inputs.aws-region }}
- name: Set up Terraform
uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_version: ${{ inputs.terraform-version }}
terraform_wrapper: false
- name: Terraform init
env:
BACKEND_CONFIG: ${{ inputs.backend-config }}
run: |
set -euo pipefail
args=(-input=false)
if [ -n "$BACKEND_CONFIG" ]; then args+=("-backend-config=$BACKEND_CONFIG"); fi
for attempt in 1 2 3; do
terraform init "${args[@]}" && exit 0
echo "::warning::terraform init failed (attempt $attempt/3); retrying"
sleep $((attempt * 10))
done
terraform init "${args[@]}"
- name: Terraform plan
id: plan
env:
VAR_FILE: ${{ inputs.var-file }}
run: |
set -euo pipefail
args=(-input=false -no-color -detailed-exitcode -out=tfplan)
if [ -n "$VAR_FILE" ]; then
args+=("-var-file=$VAR_FILE")
fi
set +e
terraform plan "${args[@]}" | tee plan.txt
code=${PIPESTATUS[0]}
set -e
case "$code" in
0) echo "has-changes=false" >> "$GITHUB_OUTPUT" ;;
2) echo "has-changes=true" >> "$GITHUB_OUTPUT" ;;
*) echo "::error::terraform plan failed (exit $code)"; exit "$code" ;;
esac
- name: Analyze plan actions
id: analyze
run: |
set -euo pipefail
terraform show -json tfplan > plan.json
python3 - <<'PY'
import json, os
plan = json.load(open('plan.json'))
destroys = 0
for rc in plan.get('resource_changes', []):
acts = rc.get('change', {}).get('actions', [])
if 'delete' in acts:
destroys += 1
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as out:
out.write(f'destroy-count={destroys}\n')
out.write(f'has-destroys={"true" if destroys > 0 else "false"}\n')
PY
- name: Upload plan artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: ${{ inputs.plan-artifact-name }}
path: |
${{ inputs.terraform-path }}/tfplan
${{ inputs.terraform-path }}/plan.txt
${{ inputs.terraform-path }}/plan.json
retention-days: 5
if-no-files-found: error
- name: Set up Infracost
if: inputs.cost-estimation
uses: infracost/actions/setup@fb736a8f219195d6efdca58682069b16fe1bc280 # v4.2.0
with:
api-key: ${{ secrets.infracost-api-key }}
- name: Infracost breakdown
if: inputs.cost-estimation
env:
VAR_FILE: ${{ inputs.var-file }}
run: |
set -euo pipefail
args=(breakdown --path .)
if [ -n "$VAR_FILE" ]; then
args+=(--terraform-var-file "$VAR_FILE")
fi
infracost "${args[@]}"
- name: Guard destroys
if: steps.analyze.outputs.destroy-count != '0' && !inputs.allow-destroys
run: |
echo "::error::terraform plan includes ${{ steps.analyze.outputs.destroy-count }} destroy actions; set allow-destroys=true only for intentional deletions"
exit 1
- name: Post plan to PR
if: ${{ inputs.post-pr-comment && github.event_name == 'pull_request' }}
uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0
env:
TF_PATH: ${{ inputs.terraform-path }}
HAS_CHANGES: ${{ steps.plan.outputs.has-changes }}
DESTROY_COUNT: ${{ steps.analyze.outputs.destroy-count }}
with:
script: |
const fs = require('fs')
const tfPath = process.env.TF_PATH
let plan = '(no plan output)'
try { plan = fs.readFileSync(`${tfPath}/plan.txt`, 'utf8') } catch (e) { /* keep default */ }
const max = 60000
if (plan.length > max) plan = plan.slice(0, max) + '\n... (truncated)'
const body = [
`### 🌍 Terraform Plan — \`${tfPath}\``,
'',
`Changes: \`${process.env.HAS_CHANGES}\` · Destroys: \`${process.env.DESTROY_COUNT}\``,
'',
'<details><summary>Show plan</summary>',
'',
'```',
plan,
'```',
'',
'</details>',
].join('\n')
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body,
})
- name: Summary
if: always()
run: |
{
echo "## 🌍 Terraform Plan"
echo ""
echo "**Path:** \`${{ inputs.terraform-path }}\`"
echo "**Var file:** \`${{ inputs.var-file || 'none' }}\`"
echo "**Has changes:** \`${{ steps.plan.outputs.has-changes }}\`"
echo "**Destroy count:** \`${{ steps.analyze.outputs.destroy-count }}\`"
} >> "$GITHUB_STEP_SUMMARY"