-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathaction.yml
705 lines (654 loc) · 39.8 KB
/
action.yml
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
---
name: Terraform/OpenTofu via Pull Request
author: Rishav Dhar (@rdhar)
description: Plan and apply Terraform/OpenTofu via PR automation, using best practices for secure and scalable IaC workflows.
runs:
using: composite
steps:
- shell: bash
run: |
# Check for required tools.
which gh > /dev/null 2>&1 || { echo "Please install GitHub CLI before running this action as it is required for interacting with GitHub."; exit 1; }
which jq > /dev/null 2>&1 || { echo "Please install jq before running this action as it is required for processing JSON outputs."; exit 1; }
which md5sum > /dev/null 2>&1 || { echo "Please install md5sum before running this action as it is required for naming the plan file artifact uniquely."; exit 1; }
which unzip > /dev/null 2>&1 || { echo "Please install unzip before running this action as it is required for unpacking the plan file artifact."; exit 1; }
which ${{ inputs.tool }} > /dev/null 2>&1 || { echo "Please install ${{ inputs.tool }} before running this action as it is required for provisioning TF code."; exit 1; }
if [[ "${{ inputs.plan-encrypt }}" ]]; then which openssl > /dev/null 2>&1 || { echo "Please install openssl before running this action as it is required for plan file encryption."; exit 1; }; fi
if [[ "${{ inputs.plan-parity }}" ]]; then which diff > /dev/null 2>&1 || { echo "Please install diff before running this action as it is required for comparing plan file parity."; exit 1; }; fi
- id: arg
env:
TF_WORKSPACE: ${{ env.TF_WORKSPACE || inputs.arg-workspace }}
shell: bash
run: |
# Populate variables.
# Environment variables.
echo GH_API="X-GitHub-Api-Version:2022-11-28" >> "$GITHUB_ENV"
echo GH_TOKEN="${{ inputs.token }}" >> "$GITHUB_ENV"
echo TF_CLI_ARGS=$([[ -n "${{ env.TF_CLI_ARGS }}" ]] && echo "${{ env.TF_CLI_ARGS }} -no-color" || echo "-no-color") >> "$GITHUB_ENV"
echo TF_IN_AUTOMATION="true" >> "$GITHUB_ENV"
echo TF_INPUT="false" >> "$GITHUB_ENV"
echo TF_WORKSPACE="$TF_WORKSPACE" >> "$GITHUB_ENV"
if [[ "$GITHUB_SERVER_URL" != "https://github.com" ]]; then echo GH_HOST=$(echo "$GITHUB_SERVER_URL" | sed 's/.*:\/\///') >> "$GITHUB_ENV"; fi
# CLI arguments.
echo arg-auto-approve=$([[ -n "${{ inputs.arg-auto-approve }}" ]] && echo " -auto-approve" || echo "") >> "$GITHUB_OUTPUT"
echo arg-backend-config=$([[ -n "${{ inputs.arg-backend-config }}" ]] && echo " -backend-config=${{ inputs.arg-backend-config }}" | sed "s/,/ -backend-config=/g" || echo "") >> "$GITHUB_OUTPUT"
echo arg-backend=$([[ -n "${{ inputs.arg-backend }}" ]] && echo " -backend=${{ inputs.arg-backend }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-backup=$([[ -n "${{ inputs.arg-backup }}" ]] && echo " -backup=${{ inputs.arg-backup }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-chdir=$([[ -n "${{ inputs.arg-chdir || inputs.working-directory }}" ]] && echo " -chdir=${{ inputs.arg-chdir || inputs.working-directory }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-check=$([[ -n "${{ inputs.arg-check }}" ]] && echo " -check" || echo "") >> "$GITHUB_OUTPUT"
echo arg-compact-warnings=$([[ -n "${{ inputs.arg-compact-warnings }}" ]] && echo " -compact-warnings" || echo "") >> "$GITHUB_OUTPUT"
echo arg-concise=$([[ -n "${{ inputs.arg-concise }}" ]] && echo " -concise" || echo "") >> "$GITHUB_OUTPUT"
echo arg-destroy=$([[ -n "${{ inputs.arg-destroy }}" ]] && echo " -destroy" || echo "") >> "$GITHUB_OUTPUT"
echo arg-detailed-exitcode=$([[ -n "${{ inputs.arg-detailed-exitcode }}" ]] && echo " -detailed-exitcode" || echo "") >> "$GITHUB_OUTPUT"
echo arg-diff=$([[ -n "${{ inputs.arg-diff }}" ]] && echo " -diff" || echo "") >> "$GITHUB_OUTPUT"
echo arg-force-copy=$([[ -n "${{ inputs.arg-force-copy }}" ]] && echo " -force-copy" || echo "") >> "$GITHUB_OUTPUT"
echo arg-from-module=$([[ -n "${{ inputs.arg-from-module }}" ]] && echo " -from-module=${{ inputs.arg-from-module }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-generate-config-out=$([[ -n "${{ inputs.arg-generate-config-out }}" ]] && echo " -generate-config-out=${{ inputs.arg-generate-config-out }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-get=$([[ -n "${{ inputs.arg-get }}" ]] && echo " -get=${{ inputs.arg-get }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-list=$([[ -n "${{ inputs.arg-list }}" ]] && echo " -list=${{ inputs.arg-list }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-lock-timeout=$([[ -n "${{ inputs.arg-lock-timeout }}" ]] && echo " -lock-timeout=${{ inputs.arg-lock-timeout }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-lock=$([[ -n "${{ inputs.arg-lock }}" ]] && echo " -lock=${{ inputs.arg-lock }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-lockfile=$([[ -n "${{ inputs.arg-lockfile }}" ]] && echo " -lockfile=${{ inputs.arg-lockfile }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-migrate-state=$([[ -n "${{ inputs.arg-migrate-state }}" ]] && echo " -migrate-state" || echo "") >> "$GITHUB_OUTPUT"
echo arg-no-tests=$([[ -n "${{ inputs.arg-no-tests }}" ]] && echo " -no-tests" || echo "") >> "$GITHUB_OUTPUT"
echo arg-parallelism=$([[ -n "${{ inputs.arg-parallelism }}" ]] && echo " -parallelism=${{ inputs.arg-parallelism }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-plugin-dir=$([[ -n "${{ inputs.arg-plugin-dir }}" ]] && echo " -plugin-dir=${{ inputs.arg-plugin-dir }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-reconfigure=$([[ -n "${{ inputs.arg-reconfigure }}" ]] && echo " -reconfigure" || echo "") >> "$GITHUB_OUTPUT"
echo arg-recursive=$([[ -n "${{ inputs.arg-recursive }}" ]] && echo " -recursive" || echo "") >> "$GITHUB_OUTPUT"
echo arg-refresh-only=$([[ -n "${{ inputs.arg-refresh-only }}" ]] && echo " -refresh-only" || echo "") >> "$GITHUB_OUTPUT"
echo arg-refresh=$([[ -n "${{ inputs.arg-refresh }}" ]] && echo " -refresh=${{ inputs.arg-refresh }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-replace=$([[ -n "${{ inputs.arg-replace }}" ]] && echo " -replace=${{ inputs.arg-replace }}" | sed "s/,/ -replace=/g" || echo "") >> "$GITHUB_OUTPUT"
echo arg-state-out=$([[ -n "${{ inputs.arg-state-out }}" ]] && echo " -state-out=${{ inputs.arg-state-out }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-state=$([[ -n "${{ inputs.arg-state }}" ]] && echo " -state=${{ inputs.arg-state }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-target=$([[ -n "${{ inputs.arg-target }}" ]] && echo " -target=${{ inputs.arg-target }}" | sed "s/,/ -target=/g" || echo "") >> "$GITHUB_OUTPUT"
echo arg-test-directory=$([[ -n "${{ inputs.arg-test-directory }}" ]] && echo " -test-directory=${{ inputs.arg-test-directory }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-upgrade=$([[ -n "${{ inputs.arg-upgrade }}" ]] && echo " -upgrade" || echo "") >> "$GITHUB_OUTPUT"
echo arg-var-file=$([[ -n "${{ inputs.arg-var-file }}" ]] && echo " -var-file=${{ inputs.arg-var-file }}" | sed "s/,/ -var-file=/g" || echo "") >> "$GITHUB_OUTPUT"
echo arg-var=$([[ -n "${{ inputs.arg-var }}" ]] && echo " -var=${{ inputs.arg-var }}" | sed "s/,/ -var=/g" || echo "") >> "$GITHUB_OUTPUT"
echo arg-write=$([[ -n "${{ inputs.arg-write }}" ]] && echo " -write=${{ inputs.arg-write }}" || echo "") >> "$GITHUB_OUTPUT"
echo arg-workspace=$([[ -n "$TF_WORKSPACE" ]] && echo " -workspace=$TF_WORKSPACE" || echo "") >> "$GITHUB_OUTPUT"
- id: identifier
env:
GH_MATRIX: ${{ toJSON(matrix) }}
shell: bash
run: |
# Unique identifier.
# Get PR number using GitHub API for different event triggers.
if [[ "$GITHUB_EVENT_NAME" == "push" ]]; then
# List PRs associated with the commit, then get the PR number from the head ref or the latest PR.
associated_prs=$(gh api /repos/${{ github.repository }}/commits/${{ github.event.pull_request.head.sha || github.sha }}/pulls --header "$GH_API" --method GET --field per_page=100)
pr_number=$(echo "$associated_prs" | jq --raw-output '(.[] | select(.head.ref == env.GITHUB_REF_NAME) | .number) // .[0].number // 0')
elif [[ "$GITHUB_EVENT_NAME" == "merge_group" ]]; then
# Get the PR number by parsing the ref name.
pr_number=$(echo "${{ github.ref_name }}" | sed -n 's/.*pr-\([0-9]*\)-.*/\1/p')
else
# Get the PR number from branch name, otherwise fallback on 0 if the PR number is not found.
pr_number=${{ github.event.number || github.event.issue.number }} || $(gh api /repos/${{ github.repository }}/pulls --header "$GH_API" --method GET --field per_page=100 --field head="${{ github.ref_name || github.head_ref || github.ref || '0' }}" | jq '.[0].number // 0')
fi
echo "pr=$pr_number" >> "$GITHUB_OUTPUT"
# Generate identifier for the workflow run using MD5 hashing algorithm for concise and unique naming.
identifier="${{ steps.arg.outputs.arg-chdir }}${{ steps.arg.outputs.arg-workspace }}${{ steps.arg.outputs.arg-backend-config }}${{ steps.arg.outputs.arg-var-file }}${{ steps.arg.outputs.arg-var }}${{ steps.arg.outputs.arg-replace }}${{ steps.arg.outputs.arg-target }}${{ steps.arg.outputs.arg-destroy }}"
identifier=$(echo -n "$identifier" | md5sum | awk '{print $1}')
echo "name=${{ inputs.tool }}-${pr_number}-${identifier}.tfplan" >> "$GITHUB_OUTPUT"
# List jobs from the current workflow run.
workflow_run=$(gh api /repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }}/jobs --header "$GH_API" --method GET --field per_page=100)
# Get the current job ID from the workflow run using different query methods for matrix and regular jobs.
if [[ "$GH_MATRIX" == "null" ]]; then
# For regular jobs, get the ID of the job with the same name as job_id (lowercase and '-' or '_' replaced with ' ').
# Otherwise, get the ID of the first job in the list as a fallback.
job_id=$(echo "$workflow_run" | jq --raw-output '(.jobs[] | select((.name | ascii_downcase | gsub("-|_"; " ")) == (env.GITHUB_JOB | ascii_downcase | gsub("-|_"; " "))) | .id) // .jobs[0].id' | tail -n 1)
else
# For matrix jobs, join the matrix values with comma separator into a single string and get the ID of the job which contains it.
matrix=$(echo "$GH_MATRIX" | jq --raw-output 'to_entries | map(if .value | type == "object" then (.value | to_entries[0].value) else .value end) | join(", ")')
job_id=$(echo "$workflow_run" | jq --raw-output --arg matrix "$matrix" '.jobs[] | select(.name | contains($matrix)) | .id' | tail -n 1)
fi
echo "job=$job_id" >> "$GITHUB_OUTPUT"
# Get the step number that has status "in_progress" from the current job.
workflow_step=$(echo "$workflow_run" | jq --raw-output --arg job_id "$job_id" '.jobs[] | select(.id == ($job_id | tonumber)) | .steps[] | select(.status == "in_progress") | .number')
echo "step=$workflow_step" >> "$GITHUB_OUTPUT"
- if: ${{ inputs.format == 'true' }}
id: format
shell: bash
run: |
# TF format.
trap 'exit_code="$?"; echo "exit_code=$exit_code" >> "$GITHUB_OUTPUT"' EXIT
args="${{ steps.arg.outputs.arg-check }}${{ steps.arg.outputs.arg-diff }}${{ steps.arg.outputs.arg-list }}${{ steps.arg.outputs.arg-recursive }}${{ steps.arg.outputs.arg-write }}"
echo "${{ inputs.tool }} fmt${{ steps.arg.outputs.arg-chdir }}${args}" | sed 's/ -/\n -/g' > tf.command.txt
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} fmt${args} 2> >(tee tf.console.txt) > >(tee tf.console.txt)
- if: ${{ contains(fromJSON('["plan", "apply", "init"]'), inputs.command) }}
id: initialize
shell: bash
run: |
# TF initialize.
trap 'exit_code="$?"; echo "exit_code=$exit_code" >> "$GITHUB_OUTPUT"' EXIT
args="${{ steps.arg.outputs.arg-backend-config }}${{ steps.arg.outputs.arg-backend }}${{ inputs.tool == 'tofu' && steps.arg.outputs.arg-var-file || '' }}${{ inputs.tool == 'tofu' && steps.arg.outputs.arg-var || '' }}${{ steps.arg.outputs.arg-force-copy }}${{ steps.arg.outputs.arg-from-module }}${{ steps.arg.outputs.arg-get }}${{ steps.arg.outputs.arg-lock-timeout }}${{ steps.arg.outputs.arg-lock }}${{ steps.arg.outputs.arg-lockfile }}${{ steps.arg.outputs.arg-migrate-state }}${{ steps.arg.outputs.arg-plugin-dir }}${{ steps.arg.outputs.arg-reconfigure }}${{ steps.arg.outputs.arg-test-directory }}${{ steps.arg.outputs.arg-upgrade }}"
echo "${{ inputs.tool }} init${{ steps.arg.outputs.arg-chdir }}${args}" | sed 's/ -/\n -/g' > tf.command.txt
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} init${args} 2> >(tee tf.console.txt) > >(tee tf.console.txt)
- if: ${{ inputs.validate == 'true' && contains(fromJSON('["plan", "apply", "init"]'), inputs.command) }}
id: validate
shell: bash
run: |
# TF validate.
trap 'exit_code="$?"; echo "exit_code=$exit_code" >> "$GITHUB_OUTPUT"' EXIT
args="${{ inputs.tool == 'tofu' && steps.arg.outputs.arg-var-file || '' }}${{ inputs.tool == 'tofu' && steps.arg.outputs.arg-var || '' }}${{ steps.arg.outputs.arg-no-tests }}${{ steps.arg.outputs.arg-test-directory }}"
echo "${{ inputs.tool }} validate${{ steps.arg.outputs.arg-chdir }}${args}" | sed 's/ -/\n -/g' > tf.command.txt
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} validate${args} 2> >(tee tf.console.txt) > >(tee tf.console.txt)
- if: ${{ inputs.label-pr == 'true' && steps.identifier.outputs.pr != 0 && contains(fromJSON('["plan", "apply"]'), inputs.command) }}
shell: bash
run: |
# Label PR.
gh api /repos/${{ github.repository }}/issues/${{ steps.identifier.outputs.pr }}/labels --header "$GH_API" --method POST --silent --field "labels[]=tf:${{ inputs.command }}"
- if: ${{ inputs.command == 'plan' }}
id: plan
env:
PLAN_FILE: ${{ inputs.plan-file }}
path: ${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}
shell: bash
run: |
# TF plan.
trap 'exit_code="$?"; echo "exit_code=$exit_code" >> "$GITHUB_OUTPUT"; if [[ "$exit_code" == "2" ]]; then exit 0; fi' EXIT
args="${{ steps.arg.outputs.arg-destroy }}${{ steps.arg.outputs.arg-var-file }}${{ steps.arg.outputs.arg-var }}${{ steps.arg.outputs.arg-compact-warnings }}${{ steps.arg.outputs.arg-concise }}${{ steps.arg.outputs.arg-detailed-exitcode }}${{ steps.arg.outputs.arg-generate-config-out }}${{ steps.arg.outputs.arg-lock-timeout }}${{ steps.arg.outputs.arg-lock }}${{ steps.arg.outputs.arg-parallelism }}${{ steps.arg.outputs.arg-refresh-only }}${{ steps.arg.outputs.arg-refresh }}${{ steps.arg.outputs.arg-replace }}${{ steps.arg.outputs.arg-target }} -out=tfplan"
echo "${{ inputs.tool }} plan${{ steps.arg.outputs.arg-chdir }}${args}" | sed 's/ -/\n -/g' > tf.command.txt
if [[ -n "$PLAN_FILE" ]]; then mv --force --verbose "$PLAN_FILE" "$path" 2>/dev/null && exit 0; fi
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} plan${args} 2> >(tee tf.console.txt) > >(tee tf.console.txt)
- if: ${{ inputs.command == 'apply' && inputs.arg-auto-approve != 'true' && inputs.plan-file == '' }}
id: download
shell: bash
run: |
# Download plan file.
# Get the artifact ID of the latest matching plan files for download.
artifact_id=$(gh api /repos/${{ github.repository }}/actions/artifacts --header "$GH_API" --method GET --field "name=${{ steps.identifier.outputs.name }}" --jq '.artifacts[0].id' 2>/dev/null)
if [ -z "$artifact_id" ]; then echo "Unable to locate plan file: ${{ steps.identifier.outputs.name }}." && exit 1; fi
gh api /repos/${{ github.repository }}/actions/artifacts/${artifact_id}/zip --header "$GH_API" --method GET > "${{ steps.identifier.outputs.name }}.zip"
# Unzip the plan file to the working directory, then clean up the zip file.
unzip "${{ steps.identifier.outputs.name }}.zip" -d "${{ inputs.arg-chdir || inputs.working-directory }}"
rm --force "${{ steps.identifier.outputs.name }}.zip"
- if: ${{ inputs.plan-encrypt != '' && steps.download.outcome == 'success' }}
env:
pass: ${{ inputs.plan-encrypt }}
path: ${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}
shell: bash
run: |
# Decrypt plan file.
temp_file=$(mktemp)
printf "%s" "$pass" > "$temp_file"
openssl enc -aes-256-ctr -pbkdf2 -salt -in "$path.encrypted" -out "$path.decrypted" -pass file:"$temp_file" -d
mv --force --verbose "$path.decrypted" "$path"
- if: ${{ steps.plan.outcome == 'success' || steps.download.outcome == 'success' }}
shell: bash
run: |
# TF show.
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} show tfplan > tf.console.txt
# Diff of changes.
# Filter lines starting with " # " and save to tf.diff.txt, then prepend diff-specific symbols based on specific keywords.
grep '^ # ' tf.console.txt | sed \
-e 's/^ # \(.* be created\)/+ \1/' \
-e 's/^ # \(.* be destroyed\)/- \1/' \
-e 's/^ # \(.* be updated\|.* be replaced\)/! \1/' \
-e 's/^ # \(.* be read\)/~ \1/' \
-e 's/^ # \(.*\)/# \1/' > tf.diff.txt || true
- if: ${{ inputs.plan-encrypt != '' && steps.plan.outcome == 'success' }}
env:
PRESERVE_PLAN: ${{ inputs.preserve-plan }}
pass: ${{ inputs.plan-encrypt }}
path: ${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}
shell: bash
run: |
# Encrypt plan file.
temp_file=$(mktemp)
printf "%s" "$pass" > "$temp_file"
openssl enc -aes-256-ctr -pbkdf2 -salt -in "$path" -out "$path.encrypted" -pass file:"$temp_file"
# Optionally delete the plan file.
if [[ "$PRESERVE_PLAN" != "true" ]]; then
rm --force "$path"
fi
- if: ${{ inputs.command == 'plan' && inputs.upload-plan == 'true' && github.server_url == 'https://github.com' }}
id: upload
uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1
with:
name: ${{ steps.identifier.outputs.name }}
path: ${{ format('{0}{1}tfplan{2}', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '', inputs.plan-encrypt != '' && '.encrypted' || '') }}
retention-days: ${{ inputs.retention-days }}
overwrite: true
- if: ${{ inputs.command == 'plan' && inputs.upload-plan == 'true' && github.server_url != 'https://github.com' }}
id: upload-v3
uses: actions/upload-artifact@c24449f33cd45d4826c6702db7e49f7cdb9b551d # v3.2.1-node20
with:
name: ${{ steps.identifier.outputs.name }}
path: ${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}
retention-days: ${{ inputs.retention-days }}
- if: ${{ inputs.plan-parity == 'true' && (steps.download.outcome == 'success' || inputs.plan-file != '') }}
env:
PLAN_FILE: ${{ inputs.plan-file }}
path: ${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}
shell: bash
run: |
# TF plan parity.
# Generate a new plan file, then compare it with the previous one.
# Both plan files are normalized by sorting JSON keys, removing timestamps and ${{ steps.arg.outputs.arg-detailed-exitcode }} to avoid false-positives.
if [[ -n "$PLAN_FILE" ]]; then mv --force --verbose "$PLAN_FILE" "$path" 2>/dev/null; fi
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} plan${{ steps.arg.outputs.arg-destroy }}${{ steps.arg.outputs.arg-var-file }}${{ steps.arg.outputs.arg-var }}${{ steps.arg.outputs.arg-compact-warnings }}${{ steps.arg.outputs.arg-concise }}${{ steps.arg.outputs.arg-generate-config-out }}${{ steps.arg.outputs.arg-lock-timeout }}${{ steps.arg.outputs.arg-lock }}${{ steps.arg.outputs.arg-parallelism }}${{ steps.arg.outputs.arg-refresh-only }}${{ steps.arg.outputs.arg-refresh }}${{ steps.arg.outputs.arg-replace }}${{ steps.arg.outputs.arg-target }} -out=tfplan.parity
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} show -json tfplan.parity | jq --sort-keys '[.resource_changes[] | select(.change.actions != ["no-op"])]' > tfplan.new
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} show -json tfplan | jq --sort-keys '[.resource_changes[] | select(.change.actions != ["no-op"])]' > tfplan.old
# If both plan files are identical, then replace the old plan file with the new one to prevent avoidable stale apply.
diff tfplan.new tfplan.old && mv --force --verbose "${{ format('{0}{1}tfplan.parity', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}" "${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}"
rm --force tfplan.new tfplan.old "${{ format('{0}{1}tfplan.parity', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}"
- id: apply
if: ${{ inputs.command == 'apply' }}
env:
PLAN_FILE: ${{ inputs.plan-file }}
PLAN_PARITY: ${{ inputs.plan-parity }}
path: ${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}
shell: bash
run: |
# TF apply.
trap 'exit_code="$?"; echo "exit_code=$exit_code" >> "$GITHUB_OUTPUT"' EXIT
# If arg-auto-approve is true, then pass in variables, otherwise pass in the plan file without variables.
if [[ "${{ inputs.arg-auto-approve }}" == "true" ]]; then
plan="${{ steps.arg.outputs.arg-auto-approve }}"
var_file="${{ steps.arg.outputs.arg-var-file }}"
var="${{ steps.arg.outputs.arg-var }}"
else
if [[ -n "$PLAN_FILE" && "$PLAN_PARITY" != "true" ]]; then mv --force --verbose "$PLAN_FILE" "$path" 2>/dev/null; fi
plan=" tfplan"
var_file=""
var=""
fi
args="${{ steps.arg.outputs.arg-destroy }}${var_file}${var}${{ steps.arg.outputs.arg-backup }}${{ steps.arg.outputs.arg-compact-warnings }}${{ steps.arg.outputs.arg-concise }}${{ steps.arg.outputs.arg-lock-timeout }}${{ steps.arg.outputs.arg-lock }}${{ steps.arg.outputs.arg-parallelism }}${{ steps.arg.outputs.arg-refresh-only }}${{ steps.arg.outputs.arg-refresh }}${{ steps.arg.outputs.arg-replace }}${{ steps.arg.outputs.arg-state-out }}${{ steps.arg.outputs.arg-state }}${{ steps.arg.outputs.arg-target }}${plan}"
echo "${{ inputs.tool }} apply${{ steps.arg.outputs.arg-chdir }}${args}" | sed 's/ -/\n -/g' > tf.command.txt
${{ inputs.tool }}${{ steps.arg.outputs.arg-chdir }} apply${args} 2> >(tee tf.console.txt) > >(tee tf.console.txt)
- id: post
if: ${{ !cancelled() && steps.identifier.outcome == 'success' && contains(fromJSON('["plan", "apply", "init"]'), inputs.command) }}
env:
exitcode: ${{ steps.apply.outputs.exit_code || steps.plan.outputs.exit_code || steps.validate.outputs.exit_code || steps.workspace.outputs.exit_code || steps.initialize.outputs.exit_code || steps.format.outputs.exit_code }}
PRESERVE_PLAN: ${{ inputs.preserve-plan }}
shell: bash
run: |
# Post output.
# Parse the "tf.command.txt" file.
command=$(cat tf.command.txt)
# Remove each comma-delemited "hide-args" argument from the command.
IFS=',' read -ra hide_args <<< "${{ inputs.hide-args }}"
for arg in "${hide_args[@]}"; do
command=$(echo "$command" | grep --invert-match "^ -${arg}" || true)
done
# Conversely, show each comma-delemited "show-args" argument in the command.
command_append=""
IFS=',' read -ra show_args <<< "${{ inputs.show-args }}"
for arg in "${show_args[@]}"; do
command_append+=$(echo "${{ steps.arg.outputs.arg-workspace }}${{ steps.arg.outputs.arg-backend-config }}${{ steps.arg.outputs.arg-backend }}${{ steps.arg.outputs.arg-backup }}${{ steps.arg.outputs.arg-check }}${{ steps.arg.outputs.arg-compact-warnings }}${{ steps.arg.outputs.arg-concise }}${{ steps.arg.outputs.arg-destroy }}${{ steps.arg.outputs.arg-detailed-exitcode }}${{ steps.arg.outputs.arg-diff }}${{ steps.arg.outputs.arg-force-copy }}${{ steps.arg.outputs.arg-from-module }}${{ steps.arg.outputs.arg-generate-config-out }}${{ steps.arg.outputs.arg-get }}${{ steps.arg.outputs.arg-list }}${{ steps.arg.outputs.arg-lock-timeout }}${{ steps.arg.outputs.arg-lock }}${{ steps.arg.outputs.arg-lockfile }}${{ steps.arg.outputs.arg-migrate-state }}${{ steps.arg.outputs.arg-no-tests }}${{ steps.arg.outputs.arg-parallelism }}${{ steps.arg.outputs.arg-plugin-dir }}${{ steps.arg.outputs.arg-reconfigure }}${{ steps.arg.outputs.arg-recursive }}${{ steps.arg.outputs.arg-refresh-only }}${{ steps.arg.outputs.arg-refresh }}${{ steps.arg.outputs.arg-replace }}${{ steps.arg.outputs.arg-state-out }}${{ steps.arg.outputs.arg-state }}${{ steps.arg.outputs.arg-target }}${{ steps.arg.outputs.arg-test-directory }}${{ steps.arg.outputs.arg-upgrade }}${{ steps.arg.outputs.arg-var-file }}${{ steps.arg.outputs.arg-var }}${{ steps.arg.outputs.arg-write }}${{ steps.arg.outputs.arg-auto-approve }}" | sed 's/ -/\n -/g' | grep "^ -${arg}" || true)
done
# Consolidate 'command', taking both "hide-args" and "show-args" into account.
command=$(echo "$command" | tr -d '\n')$command_append
echo "command=$command" >> "$GITHUB_OUTPUT"
# Parse the "tf.console.txt" file, truncated for character limit.
console=$(head --bytes=42000 tf.console.txt)
if [[ ${#console} -eq 42000 ]]; then console="${console}"$'\n…'; fi
echo "result<<EORESULTTFVIAPR"$'\n'"$console"$'\n'EORESULTTFVIAPR >> "$GITHUB_OUTPUT"
# Parse the "tf.console.txt" file for the summary.
summary=$(awk '/^(Error:|Plan:|Apply complete!|No changes.|Success)/ {line=$0} END {if (line) print line; else print "View output."}' tf.console.txt)
echo "summary=$summary" >> "$GITHUB_OUTPUT"
# If "steps.format.outcome" failed, set syntax highlighting to "diff", otherwise set it to "hcl".
syntax="hcl"
if [[ "${{ steps.format.outcome }}" == "failure" ]]; then syntax="diff"; fi
# Add summary to the job status.
check_run=$(gh api /repos/${{ github.repository }}/check-runs/${{ steps.identifier.outputs.job }} --header "$GH_API" --method PATCH --field "output[title]=${summary}" --field "output[summary]=${summary}")
# From "check_run", echo "html_url".
check_url=$(echo "$check_run" | jq --raw-output '.html_url')
echo "check_id=$(echo "$check_run" | jq --raw-output '.id')" >> "$GITHUB_OUTPUT"
run_url=$(echo ${check_url}#step:${{ steps.identifier.outputs.step }}:1)
echo "run_url=$run_url" >> "$GITHUB_OUTPUT"
# If "tf.diff.txt" exists, display it within a "diff" block, truncated for character limit.
if [[ -s tf.diff.txt ]]; then
# Get count of lines in "tf.diff.txt" which do not start with "# ".
diff_count=$(grep --invert-match '^# ' tf.diff.txt | wc --lines)
if [[ $diff_count -eq 1 ]]; then diff_change="change"; else diff_change="changes"; fi
# Parse diff of changes, truncated for character limit.
diff_truncated=$(head --bytes=24000 tf.diff.txt)
if [[ ${#diff_truncated} -eq 24000 ]]; then diff_truncated="${diff_truncated}"$'\n…'; fi
echo "diff<<EODIFFTFVIAPR"$'\n'"$diff_truncated"$'\n'EODIFFTFVIAPR >> "$GITHUB_OUTPUT"
diff="
<details><summary>Diff of ${diff_count} ${diff_change}.</summary>
\`\`\`diff
${diff_truncated}
\`\`\`
</details>"
else
diff=""
fi
# Set flags for creating PR comment and tagging actor.
create_comment=""
tag_actor=""
if [[ $exitcode -ne 0 ]]; then
if [[ "${{ inputs.comment-pr }}" == "on-change" ]]; then create_comment="true"; fi
if [[ "${{ inputs.tag-actor }}" == "on-change" ]]; then tag_actor="true"; fi
fi
if [[ "${{ inputs.comment-pr }}" == "always" ]]; then create_comment="true"; fi
if [[ "${{ inputs.tag-actor }}" == "always" ]]; then tag_actor="true"; fi
if [[ "$tag_actor" == "true" ]]; then handle="@"; else handle=""; fi
# Collate body content.
body=$(cat <<EOBODYTFVIAPR
<!-- placeholder-1 -->
\`\`\`fish
${command}
\`\`\`
<!-- placeholder-2 -->
${diff}
<!-- placeholder-3 -->
<details><summary>${summary}</br>
<!-- placeholder-4 -->
###### By ${handle}${{ github.triggering_actor }} at ${{ github.event.pull_request.updated_at || github.event.comment.created_at || github.event.head_commit.timestamp || github.event.merge_group.head_commit.timestamp }} [(view log)](${run_url}).
</summary>
\`\`\`${syntax}
${console}
\`\`\`
</details>
<!-- placeholder-5 -->
<!-- ${{ steps.identifier.outputs.name }} -->
<!-- placeholder-6 -->
EOBODYTFVIAPR
)
# Post output to job summary.
echo "$body" >> $GITHUB_STEP_SUMMARY
echo "comment_body<<EOCOMMENTTFVIAPR"$'\n'"$body"$'\n'EOCOMMENTTFVIAPR >> "$GITHUB_OUTPUT"
# Post PR comment if configured and PR exists.
if [[ "$create_comment" == "true" && "${{ steps.identifier.outputs.pr }}" != "0" ]]; then
# Check if the PR contains a bot comment with the same identifier.
list_comments=$(gh api /repos/${{ github.repository }}/issues/${{ steps.identifier.outputs.pr }}/comments --header "$GH_API" --method GET --field per_page=100)
bot_comment=$(echo "$list_comments" | jq --raw-output --arg identifier "${{ steps.identifier.outputs.name }}" '.[] | select(.user.type == "Bot") | select(.body | contains($identifier)) | .id' | tail -n 1)
if [[ -n "$bot_comment" ]]; then
if [[ "${{ inputs.comment-method }}" == "recreate" ]]; then
# Delete previous comment before posting a new one.
gh api /repos/${{ github.repository }}/issues/comments/${bot_comment} --header "$GH_API" --method DELETE
pr_comment=$(gh api /repos/${{ github.repository }}/issues/${{ steps.identifier.outputs.pr }}/comments --header "$GH_API" --method POST --field "body=${body}")
echo "comment_id=$(echo "$pr_comment" | jq --raw-output '.id')" >> "$GITHUB_OUTPUT"
elif [[ "${{ inputs.comment-method }}" == "update" ]]; then
# Update existing comment.
pr_comment=$(gh api /repos/${{ github.repository }}/issues/comments/${bot_comment} --header "$GH_API" --method PATCH --field "body=${body}")
echo "comment_id=$(echo "$pr_comment" | jq --raw-output '.id')" >> "$GITHUB_OUTPUT"
fi
else
# Post new comment.
pr_comment=$(gh api /repos/${{ github.repository }}/issues/${{ steps.identifier.outputs.pr }}/comments --header "$GH_API" --method POST --field "body=${body}")
echo "comment_id=$(echo "$pr_comment" | jq --raw-output '.id')" >> "$GITHUB_OUTPUT"
fi
elif [[ "${{ inputs.comment-pr }}" == "on-change" && "${{ steps.identifier.outputs.pr }}" != "0" ]]; then
# Delete previous comment due to no changes.
list_comments=$(gh api /repos/${{ github.repository }}/issues/${{ steps.identifier.outputs.pr }}/comments --header "$GH_API" --method GET --field per_page=100)
bot_comment=$(echo "$list_comments" | jq --raw-output --arg identifier "${{ steps.identifier.outputs.name }}" '.[] | select(.user.type == "Bot") | select(.body | contains($identifier)) | .id' | tail -n 1)
if [[ -n "$bot_comment" ]]; then
gh api /repos/${{ github.repository }}/issues/comments/${bot_comment} --header "$GH_API" --method DELETE
fi
fi
# Optionally delete the plan file.
if [[ "$PRESERVE_PLAN" != "true" ]]; then
rm --force "${{ format('{0}{1}tfplan', inputs.arg-chdir || inputs.working-directory, (inputs.arg-chdir || inputs.working-directory) && '/' || '') }}"
fi
# Clean up files.
rm --force tf.command.txt tf.console.txt tf.diff.txt
outputs:
check-id:
description: "ID of the check run."
value: ${{ steps.post.outputs.check_id }}
command:
description: "Input of the last TF command."
value: ${{ steps.post.outputs.command }}
comment-body:
description: "Body of the PR comment."
value: ${{ steps.post.outputs.comment_body }}
comment-id:
description: "ID of the PR comment."
value: ${{ steps.post.outputs.comment_id }}
diff:
description: "Diff of changes, if present (truncated)."
value: ${{ steps.post.outputs.diff }}
exitcode:
description: "Exit code of the last TF command."
value: ${{ steps.apply.outputs.exit_code || steps.plan.outputs.exit_code || steps.validate.outputs.exit_code || steps.workspace.outputs.exit_code || steps.initialize.outputs.exit_code || steps.format.outputs.exit_code }}
identifier:
description: "Unique name of the workflow run and artifact."
value: ${{ steps.identifier.outputs.name }}
job-id:
description: "ID of the workflow job."
value: ${{ steps.identifier.outputs.job }}
plan-id:
description: "ID of the plan file artifact."
value: ${{ steps.upload.outputs.artifact-id || steps.upload-v3.outputs.artifact-id }}
plan-url:
description: "URL of the plan file artifact."
value: ${{ steps.upload.outputs.artifact-url || steps.upload-v3.outputs.artifact-url }}
result:
description: "Result of the last TF command (truncated)."
value: ${{ steps.post.outputs.result }}
run-url:
description: "URL of the workflow run."
value: ${{ steps.post.outputs.run_url }}
summary:
description: "Summary of the last TF command."
value: ${{ steps.post.outputs.summary }}
inputs:
# Action parameters.
command:
default: ""
description: "Command to run between: `plan` or `apply`. Optionally `init` for checks and outputs only (e.g., `plan`)."
required: false
comment-method:
default: "update"
description: "PR comment by: `update` existing comment or `recreate` and delete previous one (e.g., `update`)."
required: false
comment-pr:
default: "always"
description: "Add a PR comment: `always`, `on-change`, or `never` (e.g., `always`)."
required: false
format:
default: "false"
description: "Check format of TF code (e.g., `false`)."
required: false
hide-args:
default: "detailed-exitcode,parallelism,lock,out,var="
description: "Hide comma-separated arguments from the command input (e.g., `detailed-exitcode,lock,out,var=`)."
required: false
label-pr:
default: "true"
description: "Add a PR label with the command input (e.g., `true`)."
required: false
plan-encrypt:
default: ""
description: "Encrypt plan file artifact with the given input (e.g., `secrets.PASSPHRASE`)."
required: false
plan-file:
default: ""
description: "Supply existing plan file path instead of the auto-generated one (e.g., `path/to/file.tfplan`)."
required: false
plan-parity:
default: "false"
description: "Replace the plan file if it matches a newly-generated one to prevent stale apply (e.g., `false`)."
required: false
preserve-plan:
default: "false"
description: "Preserve plan file in the given working directory after workflow execution (e.g., `false`)."
required: false
retention-days:
default: ""
description: "Duration after which plan file artifact will expire in days (e.g., '90')."
required: false
show-args:
default: "workspace"
description: "Show comma-separated arguments in the command input (e.g., `workspace`)."
required: false
tag-actor:
default: "always"
description: "Tag the workflow triggering actor: `always`, `on-change`, or `never` (e.g., `always`)."
required: false
token:
default: ${{ github.token }}
description: "Specify a GitHub token (e.g., `secrets.GITHUB_TOKEN`)."
required: false
tool:
default: "terraform"
description: "Provisioning tool to use between: `terraform` or `tofu` (e.g., `terraform`)."
required: false
upload-plan:
default: "true"
description: "Upload plan file as GitHub workflow artifact (e.g., `true`)."
required: false
validate:
default: "false"
description: "Check validation of TF code (e.g., `false`)."
required: false
working-directory:
default: ""
description: "Specify the working directory of TF code, alias of `arg-chdir` (e.g., `stacks/dev`)."
required: false
# CLI arguments.
arg-auto-approve:
default: ""
description: "auto-approve"
required: false
arg-backend-config:
default: ""
description: "backend-config"
required: false
arg-backend:
default: ""
description: "backend"
required: false
arg-backup:
default: ""
description: "backup"
required: false
arg-chdir:
default: ""
description: "chdir"
required: false
arg-check:
default: "true"
description: "check"
required: false
arg-compact-warnings:
default: ""
description: "compact-warnings"
required: false
arg-concise:
default: ""
description: "concise"
required: false
arg-destroy:
default: ""
description: "destroy"
required: false
arg-detailed-exitcode:
default: "true"
description: "detailed-exitcode"
required: false
arg-diff:
default: "true"
description: "diff"
required: false
arg-force-copy:
default: ""
description: "force-copy"
required: false
arg-from-module:
default: ""
description: "from-module"
required: false
arg-generate-config-out:
default: ""
description: "generate-config-out"
required: false
arg-get:
default: ""
description: "get"
required: false
arg-list:
default: ""
description: "list"
required: false
arg-lock-timeout:
default: ""
description: "lock-timeout"
required: false
arg-lock:
default: ""
description: "lock"
required: false
arg-lockfile:
default: ""
description: "lockfile"
required: false
arg-migrate-state:
default: ""
description: "migrate-state"
required: false
arg-no-tests:
default: ""
description: "no-tests"
required: false
arg-parallelism:
default: ""
description: "parallelism"
required: false
arg-plugin-dir:
default: ""
description: "plugin-dir"
required: false
arg-reconfigure:
default: ""
description: "reconfigure"
required: false
arg-recursive:
default: "true"
description: "recursive"
required: false
arg-refresh-only:
default: ""
description: "refresh-only"
required: false
arg-refresh:
default: ""
description: "refresh"
required: false
arg-replace:
default: ""
description: "replace"
required: false
arg-state-out:
default: ""
description: "state-out"
required: false
arg-state:
default: ""
description: "state"
required: false
arg-target:
default: ""
description: "target"
required: false
arg-test-directory:
default: ""
description: "test-directory"
required: false
arg-upgrade:
default: ""
description: "upgrade"
required: false
arg-var-file:
default: ""
description: "var-file"
required: false
arg-var:
default: ""
description: "var"
required: false
arg-workspace:
default: ""
description: "workspace"
required: false
arg-write:
default: ""
description: "write"
required: false
branding:
color: purple
icon: package