-
Notifications
You must be signed in to change notification settings - Fork 9
/
vdc-terraform-apply.yml
1132 lines (1019 loc) · 47.1 KB
/
vdc-terraform-apply.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
# This pipeline performs a full CI test of the VDC:
# - Provision infrastructure
# - Deploy application
# - Test application
# - Destroy infrastructure
parameters:
- name: name
displayName: Stage Name
type: string
- name: displayName
displayName: Stage Display Name
type: string
- name: inherit
displayName: Inherit state
type: boolean
default: false
- name: provision
displayName: Provision infrastructure
type: boolean
default: true
- name: reprovision
displayName: Provision infrastructure
type: boolean
default: true
- name: deploy
displayName: Deploy applications
type: boolean
default: true
- name: deployIaaS
displayName: Deploy IaaS application
type: boolean
default: true
- name: destroy
displayName: Destroy infrastructure
type: string
default: Always
values:
- Always
- Never
- 'On failure'
- 'On success'
- name: workspace
displayName: Pipeline Environment / Terraform Workspace
type: string
default: ci
values:
- ci
- ci1
- ci2
- ci3
- cd1
- cd2
- cd3
- rel
- rel1
- rel2
- rel3
- test
- tst1
- tst2
- tst3
- name: deploymentName
displayName: Deployment name (middle part resource names)
type: string
default: ''
- name: resourceSuffix
displayName: Deployment name (middle part resource names)
type: string
default: ''
- name: unpinTerraform
displayName: Unpin Terraform version
type: boolean
default: false
- name: unpinTerraformProviders
displayName: Unpin Terraform provider versions
type: boolean
default: false
- name: vdcArtifactPipeline
displayName: Pipeline (alias) for artifacts
type: string
default: ''
- name: testMode
displayName: Test Mode (disable most tasks)
type: boolean
default: false
stages:
- stage: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
# Global variables shared by all jobs
variables:
- name: 'agentTag'
value: 'web'
- name: 'vdcArtifactName'
value: 'drop'
- name: 'TF_WORKSPACE'
value: ${{ parameters.workspace }}
- name: 'scriptDirectory'
${{ if eq(length(parameters.vdcArtifactPipeline),0) }}:
value: '$(Build.SourcesDirectory)/scripts'
${{ if and(gt(length(parameters.vdcArtifactPipeline),0),ne(parameters.vdcArtifactPipeline,'current')) }}:
value: '$(Pipeline.Workspace)/${{parameters.vdcArtifactPipeline}}/$(vdcArtifactName)/s/scripts'
${{ if eq(parameters.vdcArtifactPipeline,'current') }}:
value: '$(Pipeline.Workspace)/$(vdcArtifactName)/s/scripts'
- name: 'terraformDirectory'
${{ if eq(length(parameters.vdcArtifactPipeline),0) }}:
value: '$(Build.SourcesDirectory)/terraform'
${{ if and(gt(length(parameters.vdcArtifactPipeline),0),ne(parameters.vdcArtifactPipeline,'current')) }}:
value: '$(Pipeline.Workspace)/${{parameters.vdcArtifactPipeline}}/$(vdcArtifactName)/s/terraform'
${{ if eq(parameters.vdcArtifactPipeline,'current') }}:
value: '$(Pipeline.Workspace)/$(vdcArtifactName)/s/terraform'
- name: 'TF_VAR_deployment_name'
${{ if eq(length(parameters.deploymentName),0) }}:
value: ${{ parameters.workspace }}
${{ if gt(length(parameters.deploymentName),0) }}:
value: ${{ parameters.deploymentName }}
- ${{ if gt(length(parameters.resourceSuffix),0) }}:
- name: 'TF_VAR_resource_suffix'
value: ${{ parameters.resourceSuffix }}
- name: 'iaasResourceGroup'
value: '$(TF_VAR_resource_prefix)-$(TF_VAR_deployment_name)-iaasapp-$(TF_VAR_resource_suffix)'
- name: 'paasResourceGroup'
value: '$(TF_VAR_resource_prefix)-$(TF_VAR_deployment_name)-paasapp-$(TF_VAR_resource_suffix)'
- name: 'vdcResourceGroup'
value: '$(TF_VAR_resource_prefix)-$(TF_VAR_deployment_name)-$(TF_VAR_resource_suffix)'
- name: 'terraformVersionRequest'
${{ if parameters.unpinTerraform }}:
value: 'latest'
${{ if not(parameters.unpinTerraform) }}:
value: 'preferred'
jobs:
- job: 'Prepare'
displayName: 'Prepare'
condition: succeeded()
timeoutInMinutes: $[ variables['jobTimeOutMinutes'] ]
pool:
name: '$(pool)'
vmImage: $(vmImage)
workspace:
clean: all
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Script Directory: $(scriptDirectory)"
Write-Host "Workspace Contents:"
Get-ChildItem $(Pipeline.Workspace) -Recurse
Write-Host "Environment:"
Get-ChildItem -Path Env:* | Sort-Object -Property Name
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
- task: AzureCLI@2
displayName: 'Gather Terraform settings'
enabled: ${{ not(parameters.testMode) }}
name: terraformConfig
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
inlineScript: |
# List environment variables
Get-ChildItem -Path Env: -Recurse -Include ARM_*,TF_* | Sort-Object -Property Name
# This will write version info as output variable
$(scriptDirectory)/get_tf_version.ps1 -version $(terraformVersionRequest)
addSpnToEnvironment: true
useGlobalConfig: true
failOnStandardError: true
workingDirectory: '$(scriptDirectory)'
- ${{ if or(eq(parameters.provision, true),eq(parameters.reprovision, true),eq(parameters.deploy, true),eq(parameters.deployIaaS, true)) }}:
# Creates an environment if it doesn't exist yet
- deployment: CreateEnvironment
displayName: Create Environment (if it does not exist yet)
pool:
name: '$(pool)'
vmImage: $(vmImage)
environment: '${{ parameters.workspace }}'
strategy:
runOnce:
deploy:
steps:
- script: echo Environment ${{ parameters.workspace }} exists
displayName: 'Create environment ${{ parameters.workspace }}'
- ${{ if or(eq(parameters.provision, true),eq(parameters.reprovision, true),eq(parameters.deploy, true),eq(parameters.deployIaaS, true)) }}:
# Provision on self-hosted agent
- job: 'Provision'
dependsOn:
- Prepare
- CreateEnvironment
displayName: 'Provision Infrastructure with Terraform'
condition: succeeded()
timeoutInMinutes: $[ variables['jobTimeOutMinutes'] ]
variables:
# Use earlier prepared Terraform config
terraformVersion: $[ dependencies.Prepare.outputs['terraformConfig.version'] ]
pool:
name: '$(pool)'
vmImage: $(vmImage)
workspace:
clean: all
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
- task: DownloadSecureFile@1
displayName: 'Download SSL certificate'
enabled: ${{ not(parameters.testMode) }}
inputs:
secureFile: '$(TF_VAR_vanity_certificate_path)'
- task: DownloadSecureFile@1
displayName: 'Download SSL root certificate'
enabled: ${{ not(parameters.testMode) }}
inputs:
secureFile: '$(TF_VAR_vanity_root_certificate_cer_path)'
# We could do this with tfenv, however there is no task for that
- task: TerraformInstaller@0
displayName: 'Use preferred Terraform version'
enabled: ${{ not(parameters.testMode) }}
inputs:
terraformVersion: '$(terraformVersion)'
- ${{ if eq(length(parameters.vdcArtifactPipeline),0) }}:
# Unpin version e.g. "= 2.17" -> "~> 2.17", but only in CI build
- pwsh: |
(Get-Content ./provider.tf) -replace " = `" *= +",' = "~> ' | Out-File provider.tf
Get-Content ./provider.tf
if (Test-Path .terraform.lock.hcl) {
Remove-Item .terraform.lock.hcl -Force
}
displayName: 'Unpin Terraform provider version'
enabled: ${{ and(not(parameters.testMode),parameters.unpinTerraformProviders) }}
workingDirectory: '$(terraformDirectory)'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- bash: |
find . -name *_x?
find . -name *_x? | xargs chmod +x
displayName: 'Make Terraform providers executable'
enabled: ${{ not(parameters.testMode) }}
workingDirectory: $(terraformDirectory)/.terraform/providers/registry.terraform.io/hashicorp
- task: AzureCLI@2
# Name is required so Terraform output exported by tf_deploy.ps1 can be referenced by subsequent Pipeline steps
name: terraform
displayName: 'Terraform init & apply'
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
# ARM_* environment variables are required by Terraform azurerm provider and backend
# https://www.terraform.io/docs/providers/azurerm/index.html
# https://www.terraform.io/docs/backends/types/azurerm.html
# Use Pipeline Service Principal and Service Connection to set up these variables
inlineScript: |
$(scriptDirectory)/tf_deploy.ps1 -init -clear:$${{ not(parameters.inherit) }} -stickysuffix:$${{ parameters.inherit }} -apply -force -trace $(trace) -parallelism $(parallelism)
addSpnToEnvironment: true
useGlobalConfig: true
failOnStandardError: true
retryCountOnTaskFailure: 3
powerShellIgnoreLASTEXITCODE: false
workingDirectory: '$(scriptDirectory)'
env:
TF_VAR_default_delete_timeout: '$(jobTimeOutMinutes)m'
TF_VAR_default_create_timeout: '$(jobTimeOutMinutes)m'
TF_VAR_default_update_timeout: '$(jobTimeOutMinutes)m'
- pwsh: |
Write-Host "Indicating success for job '$(Agent.JobName)'"
Write-Host "##vso[task.setvariable variable=result;isOutput=true]success"
name: provisioningResult
displayName: 'Indicate provisioning success'
condition: succeeded()
- ${{ if eq(parameters.reprovision, true) }}:
# Provision again to test for issue's that only come up when resources already exist
- job: 'Reprovision'
dependsOn:
- Prepare
- Provision
displayName: 'Provision Infrastructure with Terraform (re-entrance test)'
condition: succeeded()
timeoutInMinutes: $[ variables['jobTimeOutMinutes'] ]
variables:
iaasResourceGroup: $[ dependencies.Provision.outputs['terraform.iaas_app_resource_group'] ]
vdcResourceGroup: $[ dependencies.Provision.outputs['terraform.vdc_resource_group'] ]
# Use earlier prepared Terraform config
terraformVersion: $[ dependencies.Prepare.outputs['terraformConfig.version'] ]
pool:
name: '$(pool)'
vmImage: $(vmImage)
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
# Assume workspace is empty and re-download secure files
- task: DownloadSecureFile@1
displayName: 'Download SSL certificate'
enabled: ${{ not(parameters.testMode) }}
inputs:
secureFile: '$(TF_VAR_vanity_certificate_path)'
- task: DownloadSecureFile@1
displayName: 'Download SSL root certificate'
enabled: ${{ not(parameters.testMode) }}
inputs:
secureFile: '$(TF_VAR_vanity_root_certificate_cer_path)'
- task: TerraformInstaller@0
displayName: 'Use preferred Terraform version'
enabled: ${{ not(parameters.testMode) }}
inputs:
terraformVersion: '$(terraformVersion)'
- ${{ if eq(length(parameters.vdcArtifactPipeline),0) }}:
# Unpin version e.g. "= 2.17" -> "~> 2.17", but only in CI build
- pwsh: |
(Get-Content ./provider.tf) -replace " = `" *= +",' = "~> ' | Out-File provider.tf
Get-Content ./provider.tf
if (Test-Path .terraform.lock.hcl) {
Remove-Item .terraform.lock.hcl -Force
}
displayName: 'Unpin Terraform provider version'
enabled: ${{ and(not(parameters.testMode),parameters.unpinTerraformProviders) }}
workingDirectory: '$(terraformDirectory)'
# Deallocate/Stop MV's to force tf_deploy.ps1 to test for stopped VM's
# Stopped VM's do not allow extensions to be installed
- task: AzureResourceGroupDeployment@2
displayName: 'Stop VM''s in VDC resource group'
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
action: Stop
resourceGroupName: '$(vdcResourceGroup)'
- task: AzureResourceGroupDeployment@2
displayName: 'Deallocate VM''s in App resource group'
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
action: StopWithDeallocate
resourceGroupName: '$(iaasResourceGroup)'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- bash: |
find . -name *_x?
find . -name *_x? | xargs chmod +x
displayName: 'Make Terraform providers executable'
enabled: ${{ not(parameters.testMode) }}
workingDirectory: $(terraformDirectory)/.terraform/providers/registry.terraform.io/hashicorp
# Test for failures that only occur when resources already exist
- task: AzureCLI@2
name: terraform
displayName: 'Terraform init and apply (re-entrance test)'
continueOnError: true # Treat failure as warning during re-entrance, we should have a testable infrastructure now
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
# ARM_* environment variables are required by Terraform azurerm provider and backend
# https://www.terraform.io/docs/providers/azurerm/index.html
# https://www.terraform.io/docs/backends/types/azurerm.html
# Use Pipeline Service Principal and Service Connection to set up these variables
inlineScript: |
$(scriptDirectory)/tf_deploy.ps1 -init -apply -force -stickysuffix -trace $(trace) -parallelism $(parallelism)
addSpnToEnvironment: true
useGlobalConfig: true
failOnStandardError: true
retryCountOnTaskFailure: 3
workingDirectory: '$(scriptDirectory)'
env:
TF_VAR_default_create_timeout: '$(jobTimeOutMinutes)m'
- pwsh: |
Write-Host "Indicating success for job '$(Agent.JobName)'"
Write-Host "##vso[task.setvariable variable=result;isOutput=true]success"
name: provisioningResult
displayName: 'Indicate provisioning success'
condition: succeeded()
- ${{ if eq(parameters.deploy, true) }}:
# Deploy PaaS application
- job: 'Deploy'
dependsOn:
- Prepare
- Provision
- ${{ if eq(parameters.reprovision, true) }}:
- Reprovision
displayName: 'Deploy PaaS Application'
condition: succeeded()
timeoutInMinutes: 60
variables:
appArtifactDirectory: '$(Pipeline.Workspace)/aspnetcoresql'
appBuild: 'Release'
appPackage: '$(appArtifactDirectory)/s/bin/$(appBuild)/netcoreapp3.1/publish.zip'
# Get application configuration from Terraform output
appServiceName: $[ dependencies.Provision.outputs['terraform.paas_app_service_name'] ]
appMSIName: $[ dependencies.Provision.outputs['terraform.paas_app_service_msi_name'] ]
appMSIClientID: $[ dependencies.Provision.outputs['terraform.paas_app_service_msi_client_id'] ]
appSQLAdmin: 'vdcadmin'
appSQLDatabase: $[ dependencies.Provision.outputs['terraform.paas_app_sql_database'] ]
appSQLFirewallImportRule: 'AllowAllWindowsAzureIPs'
appSQLServer: $[ dependencies.Provision.outputs['terraform.paas_app_sql_server'] ]
appSQLServerFQDN: $[ dependencies.Provision.outputs['terraform.paas_app_sql_server_fqdn'] ]
appURL: $[ dependencies.Provision.outputs['terraform.paas_app_url'] ]
devOpsOrgURL: $[ dependencies.Provision.outputs['terraform.devops_org_url'] ]
devOpsProject: $[ dependencies.Provision.outputs['terraform.devops_project'] ]
dbaName: $[ dependencies.Provision.outputs['terraform.admin_login'] ]
dbaObjectID: $[ dependencies.Provision.outputs['terraform.admin_object_id'] ]
paasResourceGroup: $[ dependencies.Provision.outputs['terraform.paas_app_resource_group'] ]
storageUrl: 'https://ewimages.blob.core.windows.net/databasetemplates/vdcdevpaasappsqldb-2020-1-18-15-13.bacpac'
storageSAS: '?st=2020-03-20T13%3A57%3A32Z&se=2023-04-12T13%3A57%3A00Z&sp=r&sv=2018-03-28&sr=c&sig=qGpAjJlpDQsq2SB6ev27VbwOtgCwh2qu2l3G8kYX4rU%3D'
# Use earlier prepared Terraform config
terraformVersion: $[ dependencies.Prepare.outputs['terraformConfig.version'] ]
pool:
name: '$(pool)'
# SqlAzureDacpacDeployment@1 only runs on Windows
vmImage: $(vmImage)
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
# Assume workspace is empty and re-download secure files
- task: TerraformInstaller@0
displayName: 'Use preferred Terraform version'
enabled: ${{ not(parameters.testMode) }}
inputs:
terraformVersion: '$(terraformVersion)'
- ${{ if eq(length(parameters.vdcArtifactPipeline),0) }}:
# Unpin version e.g. "= 2.17" -> "~> 2.17", but only in CI build
- pwsh: |
(Get-Content ./provider.tf) -replace " = `" *= +",' = "~> ' | Out-File provider.tf
Get-Content ./provider.tf
if (Test-Path .terraform.lock.hcl) {
Remove-Item .terraform.lock.hcl -Force
}
displayName: 'Unpin Terraform provider version'
enabled: ${{ and(not(parameters.testMode),parameters.unpinTerraformProviders) }}
workingDirectory: '$(terraformDirectory)'
- task: AzureCLI@2
name: terraformConfig
displayName: 'Terraform init'
condition: succeededOrFailed()
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
# ARM_* environment variables are required by Terraform azurerm provider and backend
# https://www.terraform.io/docs/providers/azurerm/index.html
# https://www.terraform.io/docs/backends/types/azurerm.html
# Use Pipeline Service Principal and Service Connection to set up these variables
inlineScript: |
# List environment variables
Get-ChildItem -Path Env: -Recurse -Include ARM_*,TF_* | Sort-Object -Property Name
$(scriptDirectory)/tf_deploy.ps1 -init
addSpnToEnvironment: true
useGlobalConfig: true
failOnStandardError: true
workingDirectory: '$(scriptDirectory)'
env:
TF_VAR_default_delete_timeout: '$(jobTimeOutMinutes)m'
- pwsh: |
Invoke-Webrequest -Uri "$(storageUrl)$(storageSAS)" -OutFile $(System.DefaultWorkingDirectory)/database.bacpac
displayName: 'Download BACPAC'
enabled: false
- task: SqlAzureDacpacDeployment@1
# https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/sql-azure-dacpac-deployment
displayName: 'Import database'
enabled: false
inputs:
azureSubscription: '$(subscriptionConnection)'
authenticationType: aadAuthenticationIntegrated
serverName: $(appSQLServerFQDN)
databaseName: $(appSQLDatabase)
deploymentAction: Import
bacpacFile: '$(System.DefaultWorkingDirectory)/database.bacpac'
ipDetectionMethod: 'AutoDetect'
deleteFirewallRule: true
- task: AzureCLI@2
displayName: 'Import database, set permissions (with script) & swap App Service slots'
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
inlineScript: |
$env:ARM_CLIENT_ID ??= $env:servicePrincipalId
$env:ARM_CLIENT_SECRET ??= $env:servicePrincipalKey
$env:ARM_TENANT_ID ??= $env:tenantId
$env:ARM_TENANT_ID ??= $(az account show --query tenantId -o tsv)
$env:ARM_SUBSCRIPTION_ID ??= $(az account show --query id -o tsv)
$(scriptDirectory)/punch_hole.ps1 -UsePreviewApis
cd $(scriptDirectory)
$(scriptDirectory)/deploy_paas_app.ps1 -All `
-AppResourceGroup $(paasResourceGroup) `
-AppAppServiceName $(appServiceName) `
-AppAppServiceIdentity $(appMSIName) `
-AppAppServiceClientID $(appMSIClientID) `
-DBAName $(dbaName) `
-DBAObjectId $(dbaObjectId) `
-AppUrl $(appURL) `
-DevOpsOrgUrl $(devOpsOrgURL) `
-DevOpsProject $(devOpsProject) `
-SqlServer $(appSQLServer) `
-SqlServerFQDN $(appSQLServerFQDN) `
-SqlDatabase $(appSQLDatabase)
addSpnToEnvironment: true
useGlobalConfig: true
workingDirectory: '$(terraformDirectory)'
failOnStandardError: true
retryCountOnTaskFailure: 3
- ${{ if eq(parameters.deployIaaS, true) }}:
# First things first, we need to check whether the environment is ready to deploy to
- job: 'DeployEnvironmentPrep'
dependsOn:
- Prepare
- Provision
- ${{ if eq(parameters.reprovision, true) }}:
- Reprovision
displayName: 'Prepare Environment'
condition: succeeded()
timeoutInMinutes: $[ variables['jobTimeOutMinutes'] ]
variables:
iaasResourceGroup: $[ dependencies.Provision.outputs['terraform.iaas_app_resource_group'] ]
resourceSuffix: $[ dependencies.Provision.outputs['terraform.resource_suffix'] ]
timeOutSeconds: 1200
pool:
name: '$(pool)'
# SqlAzureDacpacDeployment@1 only runs on Windows
vmImage: $(vmImage)
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
# If applications are deployed, wait for environment agents to come online
# Requires Project Collection Build Service reader access to Environment
- task: AzureCLI@2
name: waitforagents
displayName: 'Wait for environment agents to come online'
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
inlineScript: |
$global:InformationPreference = "Continue"
$global:VerbosePreference = "Continue"
#$(scriptDirectory)/wait_for_agents.ps1 -ResourceGroup $(iaasResourceGroup) -TimeoutSeconds $(timeOutSeconds)
$(scriptDirectory)/wait_for_agents.ps1 -Environment ${{ parameters.workspace }} -OrganizationUrl $(System.TeamFoundationCollectionUri) -Project $(System.TeamProject) -Tags $(agentTag),$(resourceSuffix) -TimeoutSeconds $(timeOutSeconds)
useGlobalConfig: true
failOnStandardError: true
workingDirectory: '$(scriptDirectory)'
env:
# Use Pipeline token to access Azure DevOps
AZURE_DEVOPS_EXT_PAT: '$(System.AccessToken)'
- ${{ if eq(parameters.deployIaaS, true) }}:
- deployment: 'DeployEnvironment'
dependsOn:
- Prepare
- Provision
- DeployEnvironmentPrep
- ${{ if eq(parameters.reprovision, true) }}:
- Reprovision
displayName: 'Deploy IaaS Application'
condition: succeeded()
timeoutInMinutes: 30
variables:
appArtifactDirectory: '$(Pipeline.Workspace)/aspnet'
appScriptsDirectory: '$(Pipeline.Workspace)/aspnetscripts'
appPackage: '$(appArtifactDirectory)/SampleIisWebApp.zip'
resourceSuffix: $[ dependencies.Provision.outputs['terraform.resource_suffix'] ]
${{ if eq(parameters.testMode, true) }}:
pool:
name: '$(pool)'
vmImage: $(vmImage)
${{ if eq(parameters.testMode, true) }}:
environment:
name: '${{ parameters.workspace }}'
${{ if eq(parameters.testMode, false) }}:
environment:
name: '${{ parameters.workspace }}'
resourceType: virtualMachine
# BUG: Only literals are allowed
# https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema%2Cparameter-schema#environment
# tags: string | [ string ] # tag names to filter the resources in the environment
# tags: $(agentTag) $(resourceSuffix)
tags: web
strategy:
runOnce:
deploy:
steps:
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
Write-Host "Tags: $(agentTag), $(resourceSuffix)"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
# Download IaaS Application Pipeline artifacts
# This consumes artifacts published by this pipeline:
# https://github.com/geekzter/azure-vdc/blob/master/pipelines/iis-asp.net-ci.yml
- task: DownloadPipelineArtifact@2
displayName: 'Download ASP.NET Core App Artifacts'
enabled: ${{ not(parameters.testMode) }}
inputs:
buildType: 'specific'
project: '$(appArtifectProject)'
definition: '$(appBuildDefinitionIaaS)'
specificBuildWithTriggering: true
buildVersionToDownload: 'latest'
artifactName: 'aspnet'
downloadPath: '$(appArtifactDirectory)'
- task: DownloadBuildArtifacts@0
displayName: 'Download ASP.NET Core App Artifacts'
enabled: false
inputs:
buildType: 'specific'
project: '$(appArtifectProject)'
definition: '$(appBuildDefinitionIaaS)'
specificBuildWithTriggering: true
buildVersionToDownload: 'latest'
artifactName: 'aspnet'
downloadPath: '$(appArtifactDirectory)'
- task: DownloadPipelineArtifact@2
displayName: 'Download Scripts'
enabled: ${{ not(parameters.testMode) }}
inputs:
buildType: 'specific'
project: '$(appArtifectProject)'
definition: '$(appBuildDefinitionIaaS)'
specificBuildWithTriggering: true
buildVersionToDownload: 'latest'
artifactName: 'aspnetscripts'
downloadPath: '$(appScriptsDirectory)'
- task: DownloadBuildArtifacts@0
displayName: 'Download Scripts'
enabled: false
inputs:
buildType: 'specific'
project: '$(appArtifectProject)'
definition: '$(appBuildDefinitionIaaS)'
specificBuildWithTriggering: true
buildVersionToDownload: 'latest'
artifactName: 'aspnetscripts'
downloadPath: '$(appScriptsDirectory)'
# Configure IIS on VM's
- task: IISWebAppManagementOnMachineGroup@0
displayName: 'Configure IIS App'
enabled: ${{ not(parameters.testMode) }}
inputs:
EnableIIS: true
WebsiteName: 'Default Web Site'
AddBinding: true
Bindings: '{"bindings":[{"protocol":"http","ipAddress":"All Unassigned","port":"80","hostname":"","sslThumbprint":"","sniFlag":false}]}'
CreateOrUpdateAppPoolForWebsite: true
AppPoolNameForWebsite: DemoAppPool
AppCmdCommands: |
start apppool /apppool.name:DemoAppPool
set config /section:defaultDocument "/~files"
set config /section:defaultDocument "/+files.[@start,value='default.aspx']"
- task: IISWebAppDeploymentOnMachineGroup@0
displayName: 'Deploy IIS App'
enabled: ${{ not(parameters.testMode) }}
inputs:
WebSiteName: 'Default Web Site'
Package: '$(appPackage)'
TakeAppOfflineFlag: true
- powershell: |
Invoke-WebRequest -Uri http://127.0.0.1/default.aspx -UseBasicParsing
errorActionPreference: continue
displayName: 'Initial Warmup'
enabled: false
- task: CopyFiles@2
displayName: 'Copy Warmup Scripts'
enabled: ${{ not(parameters.testMode) }}
inputs:
SourceFolder: '$(appScriptsDirectory)'
TargetFolder: 'C:\Users\Public\Documents'
- task: BatchScript@1
displayName: 'Schedule Warmup Scripts'
enabled: ${{ not(parameters.testMode) }}
inputs:
filename: '$(appScriptsDirectory)/schedule-warmup.cmd'
- ${{ if eq(parameters.deploy, true) }}:
# Test applications
- job: 'Test'
dependsOn:
- Deploy
- ${{ if eq(parameters.deployIaaS, true) }}:
- DeployEnvironment
- Provision
- ${{ if eq(parameters.reprovision, true) }}:
- Reprovision
displayName: 'Test Applications'
condition: succeeded()
timeoutInMinutes: $[ variables['jobTimeOutMinutes'] ]
variables:
apimGWUrl: $[ dependencies.Provision.outputs['terraform.apim_gateway_url'] ]
apimPortalUrl: $[ dependencies.Provision.outputs['terraform.apim_developer_portal_url'] ]
deployAPIM: $[ eq(variables['TF_VAR_deploy_api_gateway'], 'true') ]
iaasAppUrl: $[ dependencies.Provision.outputs['terraform.iaas_app_url'] ]
paasAppUrl: $[ dependencies.Provision.outputs['terraform.paas_app_url'] ]
# apim_demo_api_key get's updated on every terraform apply, make sure we get up to date data
${{ if eq(parameters.reprovision, false) }}:
apimDemoKey: $[ dependencies.Provision.outputs['terraform.apim_demo_api_key'] ]
${{ if eq(parameters.reprovision, true) }}:
apimDemoKey: $[ dependencies.Reprovision.outputs['terraform.apim_demo_api_key'] ]
pool:
name: '$(pool)'
vmImage: $(vmImage)
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
# Test IaaS Application
- task: PowerShell@2
displayName: 'Test IaaS Application'
enabled: ${{ and(not(parameters.testMode),parameters.deployIaaS) }}
inputs:
targetType: 'inline'
script: |
# Wait for the WAF to get ready
Start-Sleep -Seconds 10
# Request page
Write-Host "Requesting $(iaasAppUrl)..."
Invoke-WebRequest -Uri $(iaasAppUrl) -MaximumRetryCount 9
failOnStderr: true
pwsh: true
# Test PaaS Application
- task: PowerShell@2
displayName: 'Test PaaS Application'
enabled: ${{ not(parameters.testMode) }}
inputs:
targetType: 'inline'
script: |
# Wait for the WAF to get ready
Start-Sleep -Seconds 10
# Request page
Write-Host "Requesting $(paasAppUrl)..."
Invoke-WebRequest -Uri $(paasAppUrl) -MaximumRetryCount 9
failOnStderr: true
pwsh: true
# Test API Management
- task: PowerShell@2
displayName: 'Test API Management Portal'
condition: and(succeeded(), eq(variables.deployAPIM, true))
enabled: ${{ not(parameters.testMode) }}
inputs:
targetType: 'inline'
script: |
# Request page
Write-Host "Requesting $(apimPortalUrl)..."
Invoke-WebRequest -Uri $(apimPortalUrl) -MaximumRetryCount 9
failOnStderr: true
pwsh: true
- task: PowerShell@2
displayName: 'Test API Management Gateway'
condition: and(succeeded(), eq(variables.deployAPIM, true))
enabled: ${{ not(parameters.testMode) }}
inputs:
targetType: 'inline'
script: |
# Call REST Api
$apimDemoUrl = "$(apimGWUrl)echo/resource?param1=sample"
Write-Host "Performing GET request of $apimDemoUrl with Header Ocp-Apim-Subscription-Key = $(apimDemoKey)..."
Invoke-RestMethod -Header @{ "Ocp-Apim-Subscription-Key" = "$(apimDemoKey)" } -Method Get -Uri $apimDemoUrl -MaximumRetryCount 9
failOnStderr: true
pwsh: true
- pwsh: |
Write-Host "Indicating success for job '$(Agent.JobName)'"
Write-Host "##vso[task.setvariable variable=result;isOutput=true]success"
name: testResult
displayName: 'Indicate test success'
condition: succeeded()
- ${{ if ne(parameters.destroy, 'Never') }}:
# Destroy infrastructure
- job: 'Destroy'
dependsOn:
- Prepare
- ${{ if or(eq(parameters.provision, true),eq(parameters.deploy, true)) }}:
- Provision
- ${{ if eq(parameters.deployIaaS, true) }}:
- DeployEnvironment
- ${{ if eq(parameters.deploy, true) }}:
- Deploy
- Test
displayName: 'Destroy Infrastructure with Terraform'
${{ if eq(parameters.destroy, 'Always') }}:
condition: succeededOrFailed()
${{ if eq(parameters.destroy, 'On failure') }}:
condition: failed()
${{ if eq(parameters.destroy, 'On success') }}:
condition: succeeded()
timeoutInMinutes: 120
variables:
# Use earlier prepared Terraform config
terraformVersion: $[ dependencies.Prepare.outputs['terraformConfig.version'] ]
pool:
name: '$(pool)'
vmImage: $(vmImage)
steps:
- pwsh: |
Write-Host "Azure Instance Metadata:"
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -NoProxy -Uri "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | ConvertTo-Json -Depth 64
displayName: 'Get Azure Instance Metadata'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- download: ${{parameters.vdcArtifactPipeline}}
artifact: $(vdcArtifactName)
- pwsh: |
Write-Host "Hello Task"
displayName: 'Test task'
enabled: ${{ parameters.testMode }}
# Assume workspace is empty and re-download secure files
- task: DownloadSecureFile@1
displayName: 'Download SSL certificate'
enabled: ${{ not(parameters.testMode) }}
inputs:
secureFile: '$(TF_VAR_vanity_certificate_path)'
- task: DownloadSecureFile@1
displayName: 'Download SSL root certificate'
enabled: ${{ not(parameters.testMode) }}
inputs:
secureFile: '$(TF_VAR_vanity_root_certificate_cer_path)'
- task: TerraformInstaller@0
displayName: 'Use preferred Terraform version'
enabled: ${{ not(parameters.testMode) }}
inputs:
terraformVersion: '$(terraformVersion)'
- ${{ if eq(length(parameters.vdcArtifactPipeline),0) }}:
# Unpin version e.g. "= 2.17" -> "~> 2.17", but only in CI build
- pwsh: |
(Get-Content ./provider.tf) -replace " = `" *= +",' = "~> ' | Out-File provider.tf
Get-Content ./provider.tf
if (Test-Path .terraform.lock.hcl) {
Remove-Item .terraform.lock.hcl -Force
}
displayName: 'Unpin Terraform provider version'
enabled: ${{ and(not(parameters.testMode),parameters.unpinTerraformProviders) }}
workingDirectory: '$(terraformDirectory)'
- ${{ if gt(length(parameters.vdcArtifactPipeline),0) }}:
- bash: |
find . -name *_x?
find . -name *_x? | xargs chmod +x
displayName: 'Make Terraform providers executable'
enabled: ${{ not(parameters.testMode) }}
workingDirectory: $(terraformDirectory)/.terraform/providers/registry.terraform.io/hashicorp
- task: AzureCLI@2
displayName: 'Terraform destroy'
condition: succeededOrFailed()
continueOnError: true # Treat failure as warning during destroy, we will clean up anyway
enabled: ${{ not(parameters.testMode) }}
inputs:
azureSubscription: '$(subscriptionConnection)'
scriptType: pscore
scriptLocation: inlineScript
# ARM_* environment variables are required by Terraform azurerm provider and backend
# https://www.terraform.io/docs/providers/azurerm/index.html
# https://www.terraform.io/docs/backends/types/azurerm.html
# Use Pipeline Service Principal and Service Connection to set up these variables
inlineScript: |
$(scriptDirectory)/tf_deploy.ps1 -init -upgrade -destroy -force -trace $(trace) -parallelism $(parallelism)
addSpnToEnvironment: true
useGlobalConfig: true
workingDirectory: '$(scriptDirectory)'
retryCountOnTaskFailure: 3
env:
TF_VAR_default_delete_timeout: '$(jobTimeOutMinutes)m'