-
Notifications
You must be signed in to change notification settings - Fork 0
1533 lines (1499 loc) · 69.2 KB
/
terraform-job.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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name: "⚙️ terraform-job"
on:
workflow_call:
inputs:
environment:
description: "The terraform environment name."
required: false
default: "cloud"
type: string
level:
description: "The level in the CAF hierarchy where to deploy the resources."
required: false
default: "level4"
type: string
azure_tenant_id:
description: "The tenant ID in which the subscription exists."
required: true
type: string
azure_ad_client_id:
description: "The client ID of the service principal used by terraform."
required: true
type: string
state_name:
description: "The blob name for the terraform state file. If empty, tfstate will be used. It must be tfstate or end with .tfstate."
required: false
default: "tfstate"
type: string
state_container:
description: "The storage account container name for the terraform state. If empty, tfstate will be used."
required: false
default: "tfstate"
type: string
state_location:
description: "The Azure location for the required terraform state resources."
required: false
default: "westeurope"
type: string
state_subscription_id:
description: "The subscription of the terraform state management resources."
required: true
type: string
target_subscription_id:
description: "The subscription ID in which to deploy the resources."
required: true
type: string
library_01_app_id:
description: "The App ID of a GitHub App with read access the repository specified in input variable library_01_repo."
required: false
default: ""
type: string
library_01_repo:
description: "The name of a repository with library files that is needed by terraform files."
required: false
default: ""
type: string
library_01_path:
description: "The path where the repository, specified in library_01_repo, will be checked out to."
required: false
default: ""
type: string
library_02_app_id:
description: "The App ID of a GitHub App with read access the repository specified in input variable library_02_repo."
required: false
default: ""
type: string
library_02_repo:
description: "The name of a repository with library files that is needed by terraform files."
required: false
default: ""
type: string
library_02_path:
description: "The path where the repository, specified in library_02_repo, will be checked out to."
required: false
default: ""
type: string
library_03_app_id:
description: "The App ID of a GitHub App with read access the repository specified in input variable library_03_repo."
required: false
default: ""
type: string
library_03_repo:
description: "The name of a repository with library files that is needed by terraform files."
required: false
default: ""
type: string
library_03_path:
description: "The path where the repository, specified in library_03_repo, will be checked out to."
required: false
default: ""
type: string
library_04_app_id:
description: "The App ID of a GitHub App with read access the repository specified in input variable library_04_repo."
required: false
default: ""
type: string
library_04_repo:
description: "The name of a repository with library files that is needed by terraform files."
required: false
default: ""
type: string
library_04_path:
description: "The path where the repository, specified in library_04_repo, will be checked out to."
required: false
default: ""
type: string
library_05_app_id:
description: "The App ID of a GitHub App with read access the repository specified in input variable library_05_repo."
required: false
default: ""
type: string
library_05_repo:
description: "The name of a repository with library files that is needed by terraform files."
required: false
default: ""
type: string
library_05_path:
description: "The path where the repository, specified in library_05_repo, will be checked out to."
required: false
default: ""
type: string
code_path:
description: "Path to terraform code (.tf files) to be executed."
required: false
default: "."
type: string
var_path:
description: "Path to the configuration files. All .tfvars files in the directory will be expanded."
required: false
default: "."
type: string
log_severity:
description: "The log verbosity."
required: false
default: "ERROR"
type: string
merge_method:
description: "The merge method to use after successful terraform apply. Can be one of: merge, squash, rebase or disable to turn off auto merge."
required: false
default: "squash"
type: string
keep_branch_after_merge:
description: "Prevent deleting the branch after merge."
required: false
default: false
type: boolean
date_time_language_format:
description: "The format to use for date and time in comments. Corresponds to the locales parameter of the Intl.DateTimeFormat() constructor."
required: false
default: "sv-SE"
type: string
time_zone:
description: "The time zone to use when converting UTC time, to show time in comments. See https://www.iana.org/time-zones."
required: false
default: "Europe/Oslo"
type: string
pull_request_base_ref:
description: "The base ref of the pull request."
required: true
type: string
pull_request_base_sha:
description: "The base SHA of the pull request."
required: true
type: string
pull_request_head_ref:
description: "The head ref of the pull request."
required: true
type: string
pull_request_head_sha:
description: "The head SHA of the pull request."
required: true
type: string
comment_id:
description: "The comment id for this event that can be used to update the comment."
required: false
default: ""
type: string
signed_in_sp_name:
description: "The service principal name used to run terraform."
required: true
type: string
target_subscription_name:
description: "The subscription name in which to deploy the resources."
required: true
type: string
state_subscription_name:
description: "The subscription name in which the terraform state management resources exists."
required: true
type: string
state_resource_group_name:
description: "The resource group name in which the terraform state management resources exists."
required: true
type: string
state_storage_account_name:
description: "The storage account name for terraform state management."
required: true
type: string
state_key_vault_name:
description: "The key vault name in which the secrets are located for state management."
required: true
type: string
state_backup_vault_name:
description: "The backup vault name that protects the blobs in the storage account for state management."
required: true
type: string
saved_plan_diff:
description: "A list of the terraform files that have changed since saved plan."
required: true
type: string
terraform_command:
description: "The terraform command, plan, apply, force-unlock, graph, import, state or untaint."
required: true
type: string
terraform_arguments:
description: "The arguments to pass on to terraform command."
required: false
type: string
terraform_comment:
description: "The comment after terraform commands."
required: false
type: string
terraform_version:
description: "The version of terraform to use."
required: true
type: string
secrets:
AZURE_AD_CLIENT_SECRET:
description: "The client secret of the service principal."
required: true
INFRACOST_API_KEY:
description: "The infrastructure cost API key for calculating cost impact of the terraform plan."
required: true
LIBRARY_01_PRIVATE_KEY:
description: "A private key from the GitHub App specified in library_01_app_id."
required: false
LIBRARY_02_PRIVATE_KEY:
description: "A private key from the GitHub App specified in library_02_app_id."
required: false
LIBRARY_03_PRIVATE_KEY:
description: "A private key from the GitHub App specified in library_03_app_id."
required: false
LIBRARY_04_PRIVATE_KEY:
description: "A private key from the GitHub App specified in library_04_app_id."
required: false
LIBRARY_05_PRIVATE_KEY:
description: "A private key from the GitHub App specified in library_05_app_id."
required: false
defaults:
run:
shell: bash
jobs:
job:
runs-on: ubuntu-latest
name: "⚙️ Job"
permissions:
actions: write # for actions to get workflow details and upload artifacts
contents: write # for checkout and for auto merge
pull-requests: write # for updating issue comment
env:
COMMENT_BODY: ${{ github.event.comment.body }}
TERRAFORM_COMMENT: ${{ inputs.terraform_comment }}
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
PLAN_CONTAINER: github-action-artifacts
PLAN_FOLDER: definition-plan_${{ github.event.repository.name }}_PR${{ github.event.pull_request.number || github.event.issue.number }}
steps:
- name: Checkout head ref (src)
id: checkout_src
uses: actions/checkout@v4
with:
path: src
ref: ${{ inputs.pull_request_head_ref }}
persist-credentials: false
fetch-depth: 1
- name: Get library 01 token
id: library_01
if: inputs.library_01_repo != '' && inputs.library_01_app_id != ''
uses: innofactororg/github-app-token@v2
with:
app_id: ${{ inputs.library_01_app_id }}
private_key: ${{ secrets.LIBRARY_01_PRIVATE_KEY }}
repository: ${{ inputs.library_01_repo }}
repositories: |-
["${{ inputs.library_01_repo }}"]
permissions: |-
{"contents":"read"}
- name: Checkout library 01 (private)
id: checkout_library_01
if: inputs.library_01_repo != '' && steps.library_01.outputs.token != ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_01_repo }}
path: ${{ inputs.library_01_path }}
token: ${{ steps.library_01.outputs.token }}
persist-credentials: false
fetch-depth: 1
- name: Checkout library 01 (public)
id: checkout_library_01_pub
if: inputs.library_01_repo != '' && steps.library_01.outputs.token == ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_01_repo }}
path: ${{ inputs.library_01_path }}
persist-credentials: false
fetch-depth: 1
- name: Get library 02 token
id: library_02
if: inputs.library_02_repo != '' && inputs.library_02_app_id != ''
uses: innofactororg/github-app-token@v2
with:
app_id: ${{ inputs.library_02_app_id }}
private_key: ${{ secrets.LIBRARY_02_PRIVATE_KEY }}
repository: ${{ inputs.library_02_repo }}
repositories: |-
["${{ inputs.library_02_repo }}"]
permissions: |-
{"contents":"read"}
- name: Checkout library 02 (private)
id: checkout_library_02
if: inputs.library_02_repo != '' && steps.library_02.outputs.token != ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_02_repo }}
path: ${{ inputs.library_02_path }}
token: ${{ steps.library_02.outputs.token }}
persist-credentials: false
fetch-depth: 1
- name: Checkout library 02 (public)
id: checkout_library_02_pub
if: inputs.library_02_repo != '' && steps.library_02.outputs.token == ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_02_repo }}
path: ${{ inputs.library_02_path }}
persist-credentials: false
fetch-depth: 1
- name: Get library 03 token
id: library_03
if: inputs.library_03_repo != '' && inputs.library_03_app_id != ''
uses: innofactororg/github-app-token@v2
with:
app_id: ${{ inputs.library_03_app_id }}
private_key: ${{ secrets.LIBRARY_03_PRIVATE_KEY }}
repository: ${{ inputs.library_03_repo }}
repositories: |-
["${{ inputs.library_03_repo }}"]
permissions: |-
{"contents":"read"}
- name: Checkout library 03 (private)
id: checkout_library_03
if: inputs.library_03_repo != '' && steps.library_03.outputs.token != ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_03_repo }}
path: ${{ inputs.library_03_path }}
token: ${{ steps.library_03.outputs.token }}
persist-credentials: false
fetch-depth: 1
- name: Checkout library 03 (public)
id: checkout_library_03_pub
if: inputs.library_03_repo != '' && steps.library_03.outputs.token == ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_03_repo }}
path: ${{ inputs.library_03_path }}
persist-credentials: false
fetch-depth: 1
- name: Get library 04 token
id: library_04
if: inputs.library_04_repo != '' && inputs.library_04_app_id != ''
uses: innofactororg/github-app-token@v2
with:
app_id: ${{ inputs.library_04_app_id }}
private_key: ${{ secrets.LIBRARY_04_PRIVATE_KEY }}
repository: ${{ inputs.library_04_repo }}
repositories: |-
["${{ inputs.library_04_repo }}"]
permissions: |-
{"contents":"read"}
- name: Checkout library 04 (private)
id: checkout_library_04
if: inputs.library_04_repo != '' && steps.library_04.outputs.token != ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_04_repo }}
path: ${{ inputs.library_04_path }}
token: ${{ steps.library_04.outputs.token }}
persist-credentials: false
fetch-depth: 1
- name: Checkout library 04 (public)
id: checkout_library_04_pub
if: inputs.library_04_repo != '' && steps.library_04.outputs.token == ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_04_repo }}
path: ${{ inputs.library_04_path }}
persist-credentials: false
fetch-depth: 1
- name: Get library 05 token
id: library_05
if: inputs.library_05_repo != '' && inputs.library_05_app_id != ''
uses: innofactororg/github-app-token@v2
with:
app_id: ${{ inputs.library_05_app_id }}
private_key: ${{ secrets.LIBRARY_05_PRIVATE_KEY }}
repository: ${{ inputs.library_05_repo }}
repositories: |-
["${{ inputs.library_05_repo }}"]
permissions: |-
{"contents":"read"}
- name: Checkout library 05 (private)
id: checkout_library_05
if: inputs.library_05_repo != '' && steps.library_05.outputs.token != ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_05_repo }}
path: ${{ inputs.library_05_path }}
token: ${{ steps.library_05.outputs.token }}
persist-credentials: false
fetch-depth: 1
- name: Checkout library 05 (public)
id: checkout_library_05_pub
if: inputs.library_05_repo != '' && steps.library_05.outputs.token == ''
uses: actions/checkout@v4
with:
repository: ${{ inputs.library_05_repo }}
path: ${{ inputs.library_05_path }}
persist-credentials: false
fetch-depth: 1
- name: Log in to Azure
id: login
shell: bash
run: |
set -Eeu
start_path=$(readlink -f .)
mkdir -p ${start_path}/logs
log_file="${start_path}/logs/steps.log"
touch $log_file
trap 'error_handler $? $LINENO "$BASH_COMMAND" $log_file' ERR
error_handler() {
if [[ "$3" != 'return ${PIPESTATUS[0]}' ]]; then
msg="Error $1 at line $(expr $2 + 1) in '${{ github.action }}': $3"
echo "::error file=${{ github.action }},line=$(expr $2 + 1)::$msg"
echo "$(date '+%Y-%m-%d %H:%M:%S') $msg" >>$4
fi
exit $1
}
+cmdstd() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 1> >(tee -a $log_file) 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdnoerr() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 2>/dev/null || true
return 0
}
+cmdnostd() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 1> /dev/null 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdval() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdstd az config set extension.use_dynamic_install=yes_without_prompt --only-show-errors
+cmdstd az config set core.display_survey_message=false --only-show-errors
sp_tenant_id='${{ inputs.azure_tenant_id }}'
sp_client_id='${{ inputs.azure_ad_client_id }}'
sp_client_secret='${{ secrets.AZURE_AD_CLIENT_SECRET }}'
signed_in_sp_name='${{ inputs.signed_in_sp_name }}'
+cmdnostd az login --service-principal \
-t $sp_tenant_id \
-u $sp_client_id \
-p $sp_client_secret \
--only-show-errors
echo "Logged in to Azure tenant ${sp_tenant_id} with ${signed_in_sp_name}"
state_key_vault_name='${{ inputs.state_key_vault_name }}'
if [ -n "${state_key_vault_name}" ]; then
new_sp_client_id=$(+cmdnoerr az keyvault secret show \
--id https://${state_key_vault_name}.vault.azure.net/secrets/sp-client-id \
--only-show-errors \
--query value \
-o tsv)
if [[ -n "${new_sp_client_id}" && "${new_sp_client_id}" != "${sp_client_id}" ]]; then
echo "The input client id '${sp_client_id}' is different from key vault client id '${new_sp_client_id}'"
new_sp_client_secret=$(+cmdnoerr az keyvault secret show \
--id https://${state_key_vault_name}.vault.azure.net/secrets/sp-client-secret \
--only-show-errors \
--query value \
-o tsv)
if [ -n "${new_sp_client_secret}" ]; then
echo "::add-mask::${new_sp_client_secret}"
if [ -z "${sp_tenant_id}" ]; then
sp_tenant_id=$(+cmdnoerr az keyvault secret show \
--id https://${state_key_vault_name}.vault.azure.net/secrets/sp-tenant-id \
--only-show-errors \
--query value \
-o tsv)
fi
echo "Use secrets from key vault ${state_key_vault_name} for Azure login"
+cmdnostd az login --service-principal \
-t $sp_tenant_id \
-u $new_sp_client_id \
-p $new_sp_client_secret \
--only-show-errors
signed_in_sp_name=$(+cmdval az ad sp show \
--id $new_sp_client_id \
--query displayName \
--only-show-errors \
-o tsv)
signed_in_sp_name=${signed_in_sp_name:-$new_sp_client_id}
echo "Logged in to Azure tenant ${sp_tenant_id} with ${signed_in_sp_name}"
else
echo "::error file=${{ github.action }}::Failed to get https://${state_key_vault_name}.vault.azure.net/secrets/sp-client-secret"
exit 1
fi
fi
fi
active_subscription=$(+cmdval az account show --query id -o tsv)
if [ "${active_subscription}" != '${{ inputs.state_subscription_id }}' ]; then
+cmdstd az account set -s ${{ inputs.state_subscription_id }} --only-show-errors
echo 'Changed active subscription to ${{ inputs.state_subscription_name }} (${{ inputs.state_subscription_id }})'
fi
echo "ARM_TENANT_ID=${sp_tenant_id}" >> $GITHUB_ENV
echo "ARM_CLIENT_ID=${sp_client_id}" >> $GITHUB_ENV
echo "ARM_CLIENT_SECRET=${sp_client_secret}" >> $GITHUB_ENV
- name: Get terraform plan
id: get_terraform_plan
if: >
contains(inputs.terraform_command, 'apply') || (
contains(inputs.terraform_command, 'graph') &&
contains(inputs.terraform_arguments, '-type=apply')
)
shell: bash
run: |
set -Eeu
start_path=$(readlink -f .)
code_path=$(readlink -f src/${{ inputs.code_path }})
mkdir -p ${start_path}/logs
log_file="${start_path}/logs/steps.log"
touch $log_file
trap 'error_handler $? $LINENO "$BASH_COMMAND" $log_file' ERR
error_handler() {
if [[ "$3" != 'return ${PIPESTATUS[0]}' ]]; then
msg="Error $1 at line $(expr $2 + 1) in '${{ github.action }}': $3"
echo "::error file=${{ github.action }},line=$(expr $2 + 1)::$msg"
echo "$(date '+%Y-%m-%d %H:%M:%S') $msg" >>$4
fi
exit $1
}
+cmdstd() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 1> >(tee -a $log_file) 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdnoerr() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 2>/dev/null || true
return 0
}
state_storage_account_name='${{ inputs.state_storage_account_name }}'
blob_list=('tfplan' 'tfplan.SHA' '.terraform.lock.hcl')
path_list=("${start_path}" "${start_path}" "${code_path}")
for i in "${!blob_list[@]}"; do
blob_exists=$(+cmdnoerr az storage blob exists \
--name \"${PLAN_FOLDER}/${blob_list[i]}\" \
--container-name $PLAN_CONTAINER \
--account-name $state_storage_account_name \
--auth-mode login \
--only-show-errors \
--query exists \
-o tsv)
if [ "${blob_exists}" == 'true' ]; then
echo "Download https://${state_storage_account_name}.blob.core.windows.net/${PLAN_CONTAINER}/${PLAN_FOLDER}/${blob_list[i]}"
+cmdstd az storage blob download \
--name \"${PLAN_FOLDER}/${blob_list[i]}\" \
--container-name $PLAN_CONTAINER \
--file \"${path_list[i]}/${blob_list[i]}\" \
--account-name $state_storage_account_name \
--auth-mode login \
--no-progress \
--overwrite \
--only-show-errors \
-o none
else
echo "::error file=${{ github.action }}::Unable to find https://${state_storage_account_name}.blob.core.windows.net/${PLAN_CONTAINER}/${PLAN_FOLDER}/${blob_list[i]}" | tee -a $log_file
exit 1
fi
done
- name: Get terraform state
id: get_terraform_state
shell: bash
run: |
set -Eeu
start_path=$(readlink -f .)
mkdir -p ${start_path}/logs
log_file="${start_path}/logs/steps.log"
touch $log_file
trap 'error_handler $? $LINENO "$BASH_COMMAND" $log_file' ERR
error_handler() {
if [[ "$3" != 'return ${PIPESTATUS[0]}' ]]; then
msg="Error $1 at line $(expr $2 + 1) in '${{ github.action }}': $3"
echo "::error file=${{ github.action }},line=$(expr $2 + 1)::$msg"
echo "$(date '+%Y-%m-%d %H:%M:%S') $msg" >>$4
fi
exit $1
}
+cmdstd() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 1> >(tee -a $log_file) 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdnoerr() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 2>/dev/null || true
return 0
}
state_storage_account_name='${{ inputs.state_storage_account_name }}'
blob='${{ inputs.state_name }}'
blob_exists=$(+cmdnoerr az storage blob exists \
--name $blob \
--container-name ${{ inputs.state_container }} \
--account-name $state_storage_account_name \
--auth-mode login \
--only-show-errors \
--query exists \
-o tsv)
if [ "${blob_exists}" == 'true' ]; then
echo "Download https://${state_storage_account_name}.blob.core.windows.net/${{ inputs.state_container }}/${blob}"
+cmdstd az storage blob download \
--name $blob \
--container-name ${{ inputs.state_container }} \
--file \"${start_path}/logs/${blob}.before\" \
--account-name $state_storage_account_name \
--auth-mode login \
--no-progress \
--overwrite \
--only-show-errors \
-o none
serial=$(cat ${start_path}/logs/${blob}.before | jq -r .serial)
echo "State file has serial ${serial}"
echo "serial=${serial}" >> $GITHUB_OUTPUT
else
echo "Unable to find https://${state_storage_account_name}.blob.core.windows.net/${{ inputs.state_container }}/${blob}"
echo "serial=0" >> $GITHUB_OUTPUT
fi
- name: Set up Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: ${{ inputs.terraform_version }}
- name: Terraform
# The output file for plan is modified using sed: all lines that begin with one
# or more spaces followed by a `+` or `-` is modified so the `+` and `-`
# end up at the start of the line followed by the number of matched spaces
id: terraform
shell: bash
run: |
set -Eeu
start_path=$(readlink -f .)
code_path=$(readlink -f src/${{ inputs.code_path }})
mkdir -p ${start_path}/logs
debug_file="${start_path}/logs/tf_debug.log"
touch $debug_file
log_file="${start_path}/logs/steps.log"
touch $log_file
trap 'error_handler $? $LINENO "$BASH_COMMAND" $log_file' ERR
error_handler() {
if [[ "$3" != 'return ${PIPESTATUS[0]}' ]]; then
msg="Error $1 at line $(expr $2 + 1) in '${{ github.action }}': $3"
echo "::error file=${{ github.action }},line=$(expr $2 + 1)::$msg"
echo "$(date '+%Y-%m-%d %H:%M:%S') $msg" >>$4
fi
exit $1
}
+cmdstd() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 1> >(tee -a $log_file) 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdval() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
terraform_version=$(terraform version -json | jq -r '.terraform_version')
account=$(+cmdval az account show --only-show-errors -o json)
active_subscription_id=$(echo ${account} | jq -r .id)
if [ "${active_subscription_id}" != '${{ inputs.target_subscription_id }}' ]; then
+cmdstd az account set -s ${{ inputs.target_subscription_id }} --only-show-errors
echo "Changed active subscription to ${{ inputs.target_subscription_name }} (${{ inputs.target_subscription_id }})"
account=$(+cmdval az account show --only-show-errors -o json)
fi
export ARM_SUBSCRIPTION_ID="${{ inputs.target_subscription_id }}"
echo "Target subscription:"
echo ${account} | jq -r
export TF_LOG='${{ inputs.log_severity }}'
export TF_LOG_PATH=$debug_file
export TF_VAR_environment='${{ inputs.environment }}'
export TF_VAR_level='${{ inputs.level }}'
export TF_VAR_workspace='${{ inputs.state_container }}'
export TF_VAR_tf_name='${{ inputs.state_name }}'
export TF_VAR_tfstate_key='${{ inputs.state_name }}'
export TF_VAR_tfstate_container_name='${{ inputs.state_container }}'
export TF_VAR_tfstate_storage_account_name='${{ inputs.state_storage_account_name }}'
export TF_VAR_tfstate_resource_group_name='${{ inputs.state_resource_group_name }}'
export TF_VAR_tfstate_subscription_id='${{ inputs.state_subscription_id }}'
export TF_VAR_tenant_id="${ARM_TENANT_ID}"
export TF_IN_AUTOMATION='true'
echo "Terraform version ${terraform_version}"
cd $code_path
backend_azurerm=$(find $code_path -maxdepth 1 -type f -name '*.tf' -exec grep -l -m 1 '^[^#]*backend "azurerm" {' {} \+ || true)
if [ -n "${backend_azurerm}" ]; then
echo "::warning file=${{ github.action }}::Found azurerm backend in ${backend_azurerm}. It will be ignored. This workflow will set backend config when running terraform init."
else
printf 'terraform {\n backend "azurerm" {\n }\n}' > $code_path/backend.azurerm.tf
fi
echo 'Running terraform init with...'
echo ' -no-color -upgrade -reconfigure -backend=true'
echo ' -backend-config storage_account_name=${{ inputs.state_storage_account_name }}'
echo ' -backend-config resource_group_name=${{ inputs.state_resource_group_name }}'
echo ' -backend-config container_name=${{ inputs.state_container }}'
echo ' -backend-config subscription_id=${{ inputs.state_subscription_id }}'
echo ' -backend-config key=${{ inputs.state_name }}'
echo '>==============>==============>==============>==============>'
terraform init \
-no-color \
-upgrade \
-reconfigure \
-backend=true \
-backend-config storage_account_name=${{ inputs.state_storage_account_name }} \
-backend-config resource_group_name=${{ inputs.state_resource_group_name }} \
-backend-config container_name=${{ inputs.state_container }} \
-backend-config subscription_id=${{ inputs.state_subscription_id }} \
-backend-config key=${{ inputs.state_name }} | grep -P '^- (?=Downloading|Using|Finding|Installing)|^[^-]' 2> >(tee -a $log_file >&2)
echo '<==============<==============<==============<==============<'
readarray -td '|' command_list <<< '${{ inputs.terraform_command }}'
readarray -td '|' arguments_list <<< '${{ inputs.terraform_arguments }}'
for i in "${!command_list[@]}"; do
command=$(echo "${command_list[i]}" | xargs)
passed_arguments=$(echo "${arguments_list[i]}")
arguments=''
if [ -n "${command}" ]; then
if [ ! -d "${start_path}/logs" ]; then
echo "::error file=${{ github.action }}::Folder ${start_path}/logs does not exist."
exit 1
fi
tf_output_file="${start_path}/logs/terraform${i}_${command}.output"
if [ -f "${tf_output_file}" ]; then
echo 'The file ${tf_output_file} exist, removing old log file'
rm -f ${tf_output_file}
fi
touch $tf_output_file
tf_error_file="${start_path}/logs/terraform${i}_${command}.error"
if [ -f "${tf_error_file}" ]; then
echo 'The file ${tf_error_file} exist, removing old error file'
rm -f ${tf_error_file}
fi
touch $tf_error_file
echo "output file: ${tf_output_file}"
echo "error file: ${tf_error_file}"
arg_vars=''
if [[ "${command}" =~ (plan|import) ]]; then
var_path=$(readlink -f ${{ inputs.var_path }})
if [ ! -d "${var_path}" ]; then
echo "::error file=${{ github.action }}::Folder ${var_path} does not exist."
exit 1
fi
for filename in "${var_path}"/*.tfvars; do
if [ "${filename}" != "${var_path}/*.tfvars" ]; then
arg_vars+="-var-file ${filename} "
fi
done
for filename in "${var_path}"/*.tfvars.json; do
if [ "${filename}" != "${var_path}/*.tfvars.json" ]; then
arg_vars+="-var-file ${filename} "
fi
done
if [[ -z "${arg_vars}" ]]; then
echo '::error file=${{ github.action }}::Folder ${{ inputs.var_path }} does not have any tfvars files.'
exit 1
fi
fi
case "${command}" in
'plan')
arguments="-refresh=true -lock=false -no-color -input=false ${passed_arguments} ${arg_vars} -out=${start_path}/tfplan"
;;
'apply')
arguments="-no-color -auto-approve -input=false ${start_path}/tfplan"
;;
'force-unlock')
if [ -n "${passed_arguments}" ]; then
elements=(${passed_arguments})
if [ ${#elements[@]} -ne 1 ]; then
echo "::error file=${{ github.action }}::The force-unlock command expects one argument LOCK_ID. Arguments received: ${passed_arguments}" | tee -a $tf_error_file
exit 1
else
arguments="-force ${passed_arguments}"
fi
else
echo "::error file=${{ github.action }}::No arguments received. The force-unlock command expects one argument LOCK_ID." | tee -a $tf_error_file
exit 1
fi
;;
'graph')
if [[ "${passed_arguments}" == *'-type=apply'* && -f "${start_path}/tfplan" ]]; then
arguments="${passed_arguments} -plan=${start_path}/tfplan"
else
arguments="${passed_arguments}"
fi
;;
'import')
if [ -n "${passed_arguments}" ]; then
elements=(${passed_arguments})
if [ ${#elements[@]} -ne 2 ]; then
echo "::error file=${{ github.action }}::The import command expects two arguments ADDR ID. Arguments received: ${passed_arguments}" | tee -a $tf_error_file
exit 1
else
arguments="-no-color ${arg_vars} ${passed_arguments}"
fi
else
echo "::error file=${{ github.action }}::No arguments received. The import command expects two arguments ADDR ID." | tee -a $tf_error_file
exit 1
fi
;;
'state')
if [ -n "${passed_arguments}" ]; then
elements=(${passed_arguments})
sub_command=${elements[0]}
case "${sub_command}" in
'list')
arguments="${passed_arguments}"
;;
'mv')
if [ ${#elements[@]} -lt 3 ]; then
echo "::error file=${{ github.action }}::The state mv command expects two arguments SOURCE DESTINATION. Arguments received: ${passed_arguments}" | tee -a $tf_error_file
exit 1
else
arguments="${passed_arguments}"
fi
;;
'rm')
if [ ${#elements[@]} -lt 2 ]; then
echo "::error file=${{ github.action }}::The state rm command expects one or more ADDRESS. Arguments received: ${passed_arguments}" | tee -a $tf_error_file
exit 1
else
arguments="${passed_arguments}"
fi
;;
'show')
if [ ${#elements[@]} -lt 2 ]; then
echo "::error file=${{ github.action }}::The state show command expects an ADDRESS. Arguments received: ${passed_arguments}" | tee -a $tf_error_file
exit 1
else
arguments="${passed_arguments}"
fi
;;
*)
echo "::error file=${{ github.action }}::The state command expects the sub command to be either list, mv, rm or show. Sub command received: ${sub_command}" | tee -a $tf_error_file
exit 1
;;
esac
else
echo "::error file=${{ github.action }}::No arguments received. The state command expects arguments." | tee -a $tf_error_file
exit 1
fi
;;
'untaint')
if [ -n "${passed_arguments}" ]; then
arguments="-no-color ${passed_arguments}"
else
echo "::error file=${{ github.action }}::No arguments received. The untaint command expects one argument ADDRESS." | tee -a $tf_error_file
exit 1
fi
;;
*)
echo "::error file=${{ github.action }}::The terraform $command command is unsupported" | tee -a $tf_error_file
exit 1
;;
esac
echo "Running terraform ${command} with..."
if [ -n "${arguments}" ]; then
echo " ${arguments}"
fi
echo '>==============>==============>==============>==============>'
terraform ${command} ${arguments} 2> >(tee -a $tf_error_file >&2) | tee -a $tf_output_file
echo '<==============<==============<==============<==============<'
if [ -f "${tf_output_file}" ]; then
if [ "${command}" == 'plan' ]; then
if [ -f "${start_path}/tfplan" ]; then
cp -f $tf_output_file ${start_path}/logs/terraform_${command}.original.output
cat $tf_output_file | \
sed -n '/Terraform used the selected providers to generate the following execution/,$p' | \
sed -E 's/^([[:space:]]+)([-+])/\2\1/g' > ${start_path}/plan.txt
mv -f ${start_path}/plan.txt $tf_output_file
else
echo "::error file=${{ github.action }}::Unable to find plan at ${start_path}/tfplan" | tee -a $tf_error_file
exit 1
fi
fi
else
echo "::error file=${{ github.action }}::Unable to find output at ${tf_output_file}" | tee -a $tf_error_file
exit 1
fi
fi
done
if [[ '${{ inputs.terraform_command }}' == *'apply'* ]]; then
echo "applied=true" >> $GITHUB_OUTPUT
fi
find . -name "backend.*.tf" -delete || true
find . -name "terraform.tfstate*" -delete || true
- name: Check terraform state
id: check_terraform_state
shell: bash
run: |
set -Eeu
start_path=$(readlink -f .)
mkdir -p ${start_path}/logs
log_file="${start_path}/logs/steps.log"
touch $log_file
trap 'error_handler $? $LINENO "$BASH_COMMAND" $log_file' ERR
error_handler() {
if [[ "$3" != 'return ${PIPESTATUS[0]}' ]]; then
msg="Error $1 at line $(expr $2 + 1) in '${{ github.action }}': $3"
echo "::error file=${{ github.action }},line=$(expr $2 + 1)::$msg"
echo "$(date '+%Y-%m-%d %H:%M:%S') $msg" >>$4
fi
exit $1
}
+cmdstd() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 1> >(tee -a $log_file) 2> >(tee -a $log_file >&2)
return ${PIPESTATUS[0]}
}
+cmdnoerr() {
echo "${@:1:4}" | sed -e "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" >>$log_file
eval "$@" 2>/dev/null || true
return 0
}
state_storage_account_name='${{ inputs.state_storage_account_name }}'
blob='${{ inputs.state_name }}'
blob_exists=$(+cmdnoerr az storage blob exists \
--name $blob \
--container-name ${{ inputs.state_container }} \
--account-name $state_storage_account_name \
--auth-mode login \
--only-show-errors \
--query exists \
-o tsv)
if [ "${blob_exists}" == 'true' ]; then
echo "Download https://${state_storage_account_name}.blob.core.windows.net/${{ inputs.state_container }}/${blob}"
+cmdstd az storage blob download \
--name $blob \
--container-name ${{ inputs.state_container }} \
--file \"${start_path}/logs/${blob}.after\" \
--account-name $state_storage_account_name \
--auth-mode login \
--no-progress \
--overwrite \
--only-show-errors \
-o none
serial=$(cat ${start_path}/logs/${blob}.after | jq -r .serial)
if [ "${serial}" != '${{ steps.get_terraform_state.outputs.serial }}' ]; then
echo "State file serial changed from ${{ steps.get_terraform_state.outputs.serial }} to ${serial}"
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "State file serial is still ${serial}"
echo "changed=false" >> $GITHUB_OUTPUT
fi
else
echo "Unable to find https://${state_storage_account_name}.blob.core.windows.net/${{ inputs.state_container }}/${blob}"
echo "changed=false" >> $GITHUB_OUTPUT
fi
- name: Upload terraform state
id: upload_state
if: contains(fromJSON('["plan", "apply"]'), inputs.terraform_command)