Private/Install-TerraformVersion.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
Function Install-TerraformVersion {
    [cmdletbinding()]
    Param(
        [parameter(Mandatory = $True)]
        [string]
        $Version,

        [parameter(Mandatory = $True)]
        $Config
    )
    
    # install desired version
    # platform = windows, linux, darwin
    # arch = 386, amd64
    # version
    # E.g https://releases.hashicorp.com/terraform/0.12.19/terraform_0.12.19_windows_386.zip
    
    $Environment = @{
        Platform   = $null
        Arch       = $null
        BinaryPath = $null
        BinaryName = $null
    }

    # Determine platform
    $Environment.Platform = Get-Platform
    if ($Environment.Platform -eq "windows"){
        $Environment.BinaryName = "terraform.exe"
    }
    else{
        $Environment.BinaryName = "terraform"
    }
    
    # Determine arch
    if ([Environment]::Is64BitOperatingSystem) {
        $Environment.Arch = "amd64"
    }
    else {
        $Environment.Arch = "386"
    }
    
    $Url = "https://releases.hashicorp.com/terraform/{0}/terraform_{0}_{1}_{2}.zip" -f $Version, $Environment.Platform, $Environment.Arch
    $UserProfile = (Get-Item ~).FullName
    $WorkingDir = Join-Path -Path $UserProfile -ChildPath ".terrafun"
    $BaseName = (Split-Path -Path $Url -Leaf)
    $DownloadFilePath = Join-Path -Path $WorkingDir -ChildPath $BaseName
    $DestinationDir = Join-Path -Path $WorkingDir -ChildPath ("terraform_{0}_{1}_{2}" -f $Version, $Environment.Platform, $Environment.Arch)
    $Environment.BinaryPath = Join-Path -Path $DestinationDir -ChildPath $Environment.BinaryName
    if (Test-Path -Path $Environment.BinaryPath) {
        Return $Environment
    }
    
    if ($Config.AvailableVersions -notcontains $Version) {
        throw ("Could not find release for version {0}" -f $Version)
    }

    New-Item -Path $DestinationDir -ItemType Directory -Force | Out-Null
    Write-Verbose ("downloading {0}..." -f $Url)
    $ProgressPreference = 'silentlyContinue'
    Invoke-WebRequest -Uri $Url -OutFile $DownloadFilePath
    Expand-Archive -Path $DownloadFilePath -DestinationPath $DestinationDir -Force
    Remove-Item $DownloadFilePath

    if (Test-Path -Path $Environment.BinaryPath) {

        if ($Environment.Platform -ne "windows"){
            & chmod +x $Environment.BinaryPath
        }

        Return $Environment
    }
    else {
        throw ("failed to install terraform {0}" -f $Version)
    }
    
}