-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeploy.ps1
executable file
·187 lines (161 loc) · 8.15 KB
/
deploy.ps1
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
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Creates Azure Service Connection with Terraform
.DESCRIPTION
This script is a wrapper around Terraform. It is provided for convenience only, as it works around some limitations in the demo.
E.g. terraform might need resources to be started before executing, and resources may not be accessible from the current locastion (IP address).
.EXAMPLE
./deploy.ps1 -apply
#>
#Requires -Version 7.2
### Arguments
param (
[parameter(Mandatory=$false,HelpMessage="Initialize Terraform backend, modules & provider")][switch]$Init=$false,
[parameter(Mandatory=$false,HelpMessage="Perform Terraform plan stage")][switch]$Plan=$false,
[parameter(Mandatory=$false,HelpMessage="Perform Terraform validate stage")][switch]$Validate=$false,
[parameter(Mandatory=$false,HelpMessage="Perform Terraform apply stage (implies plan)")][switch]$Apply=$false,
[parameter(Mandatory=$false,HelpMessage="Deploys scale set pools")][switch]$CreateScaleSetPools=$false,
[parameter(Mandatory=$false,HelpMessage="Perform Terraform destroy stage")][switch]$Destroy=$false,
[parameter(Mandatory=$false,HelpMessage="Show Terraform output variables")][switch]$Output=$false,
[parameter(Mandatory=$false,HelpMessage="Don't show prompts unless something get's deleted that should not be")][switch]$Force=$false,
[parameter(Mandatory=$false,HelpMessage="Initialize Terraform backend, upgrade modules & provider")][switch]$Upgrade=$false,
[parameter(Mandatory=$false,HelpMessage="Don't try to set up a Terraform backend if it does not exist")][switch]$NoBackend=$false,
[parameter(Mandatory=$false,HelpMessage="Entra ID tenant id")][guid]$TenantId=($env:ARM_TENANT_ID ?? $env:AZURE_TENANT_ID)
)
### Internal Functions
. (Join-Path $PSScriptRoot functions.ps1)
### Validation
if (!(Get-Command terraform -ErrorAction SilentlyContinue)) {
$tfMissingMessage = "Terraform not found"
if ($IsWindows) {
$tfMissingMessage += "`nInstall Terraform e.g. from Chocolatey (https://chocolatey.org/packages/terraform) 'choco install terraform'"
} else {
$tfMissingMessage += "`nInstall Terraform e.g. using tfenv (https://github.com/tfutils/tfenv)"
}
throw $tfMissingMessage
}
Write-Verbose $MyInvocation.line
$script:ErrorActionPreference = "Stop"
$workspace = Get-TerraformWorkspace
$planFile = "${workspace}.tfplan".ToLower()
$varsFile = "${workspace}.tfvars".ToLower()
$inAutomation = ($env:TF_IN_AUTOMATION -ieq "true")
if (($workspace -ieq "prod") -and $Force) {
$Force = $false
Write-Warning "Ignoring -Force in workspace '${workspace}'"
}
try {
$tfdirectory = (Get-TerraformDirectory)
Push-Location $tfdirectory
# Print version info
terraform -version
if ($Init -or $Upgrade) {
if (!$NoBackend) {
$backendFile = (Join-Path $tfdirectory backend.tf)
$backendTemplate = "${backendFile}.sample"
$newBackend = (!(Test-Path $backendFile))
$tfbackendArgs = ""
$env:TF_STATE_backend_storage_account_name ??= $env:TF_STATE_BACKEND_STORAGE_ACCOUNT_NAME
$env:TF_STATE_backend_storage_container_name ??= $env:TF_STATE_BACKEND_STORAGE_CONTAINER_NAME
$env:TF_STATE_backend_resource_group_name ??= $env:TF_STATE_BACKEND_RESOURCE_GROUP_NAME
if ($newBackend) {
if (!$env:TF_STATE_backend_storage_account_name -or !$env:TF_STATE_backend_storage_container_name) {
Write-Warning "Environment variables TF_STATE_backend_storage_account_name and TF_STATE_backend_storage_container_name must be set when creating a new backend from $backendTemplate"
$fail = $true
}
if (!($env:TF_STATE_backend_resource_group_name -or $env:ARM_ACCESS_KEY -or $env:ARM_SAS_TOKEN)) {
Write-Warning "Environment variables ARM_ACCESS_KEY or ARM_SAS_TOKEN or TF_STATE_backend_resource_group_name (with Terraform identity granted 'Storage Blob Data Contributor' role) must be set when creating a new backend from $backendTemplate"
$fail = $true
}
if ($fail) {
Write-Warning "This script assumes Terraform backend exists at ${backendFile}, but it does not exist"
Write-Host "You can copy ${backendTemplate} -> ${backendFile} and configure a storage account manually"
Write-Host "See documentation at https://www.terraform.io/docs/backends/types/azurerm.html"
exit
}
# Terraform azurerm backend does not exist, create one
Write-Host "Creating '$backendFile'"
Copy-Item -Path $backendTemplate -Destination $backendFile
$tfbackendArgs += " -reconfigure"
}
if ($env:TF_STATE_backend_resource_group_name) {
$tfbackendArgs += " -backend-config=`"resource_group_name=${env:TF_STATE_backend_resource_group_name}`""
}
if ($env:TF_STATE_backend_storage_account_name) {
$tfbackendArgs += " -backend-config=`"storage_account_name=${env:TF_STATE_backend_storage_account_name}`""
}
if ($env:TF_STATE_backend_storage_container_name) {
$tfbackendArgs += " -backend-config=`"container_name=${env:TF_STATE_backend_storage_container_name}`""
}
}
$initCmd = "terraform init $tfbackendArgs"
if ($Upgrade) {
$initCmd += " -upgrade"
}
Invoke "$initCmd"
}
if ($Validate) {
Invoke "terraform validate"
}
# Prepare common arguments
if ($Force) {
$forceArgs = "-auto-approve"
}
if (!(Get-ChildItem Env:TF_VAR_* -Exclude TF_VAR_backend_*,TF_VAR_devops_pat) -and (Test-Path $varsFile)) {
# Load variables from file, if it exists and environment variables have not been set
$varArgs = " -var-file='$varsFile'"
}
if ($Plan -or $Apply -or $Destroy) {
Login-Az ([ref]$TenantId)
}
if ($Plan -or $Apply) {
# Create plan
Invoke "terraform plan $varArgs -out='$planFile' "
}
if ($Apply) {
Write-Verbose "Converting $planFile into JSON so we can perform some inspection..."
$planJSON = (terraform show -json $planFile)
if ($DebugPreference -ine "SilentlyContinue") {
New-TemporaryFile | Select-Object -ExpandProperty FullName | Set-Variable jsonPlanFile
$jsonPlanFile += ".json"
$planJSON | Set-Content $jsonPlanFile
Write-Debug "Plan file (json): ${jsonPlanFile}"
}
if (!$inAutomation) {
$defaultChoice = 0
if ($vmsReplaced) {
$defaultChoice = 1
Write-Warning "You're about to remove or replace these Virtual Machines in workspace '${workspace}':"
$vmsReplaced
}
if (!$Force) {
# Prompt to continue
$choices = @(
[System.Management.Automation.Host.ChoiceDescription]::new("&Continue", "Deploy infrastructure")
[System.Management.Automation.Host.ChoiceDescription]::new("&Exit", "Abort infrastructure deployment")
)
$decision = $Host.UI.PromptForChoice("Continue", "Do you wish to proceed executing Terraform plan $planFile in workspace $workspace?", $choices, $defaultChoice)
if ($decision -eq 0) {
Write-Host "$($choices[$decision].HelpMessage)"
} else {
Write-Host "$($PSStyle.Formatting.Warning)$($choices[$decision].HelpMessage)$($PSStyle.Reset)"
exit
}
}
}
Invoke "terraform apply $forceArgs '$planFile'"
}
if ($Output) {
Invoke "terraform output"
if (![string]::IsNullOrEmpty($env:TF_BUILD)) {
# Export Terraform output as Pipeline output variables for subsequent tasks
Set-PipelineVariablesFromTerraform
}
}
if ($Destroy) {
Invoke "terraform destroy $varArgs $forceArgs"
}
} finally {
Pop-Location
}