Skip to content

Instantly share code, notes, and snippets.

@rchaganti
Created October 13, 2020 09:18
Show Gist options
  • Save rchaganti/078556db37f43ec4d33de8f3a2bb9b16 to your computer and use it in GitHub Desktop.
Save rchaganti/078556db37f43ec4d33de8f3a2bb9b16 to your computer and use it in GitHub Desktop.
Download and Install Terraform - Windows (PowerShell)
[CmdletBinding(DefaultParameterSetName='Version')]
param
(
[Parameter(ParameterSetName='Latest', Mandatory = $true)]
[Parameter(ParameterSetName='Version', Mandatory = $true)]
[String]
$SaveToPath,
[Parameter(ParameterSetName='Version', Mandatory = $true)]
[String]
$Version,
[Parameter(ParameterSetName='Latest')]
[Switch]
$Latest
)
try
{
if ($PSCmdlet.ParameterSetName -eq 'Version')
{
$downloadVersion = $Version
}
else
{
$releasesUrl = 'https://api.github.com/repos/hashicorp/terraform/releases'
$releases = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $releasesUrl
$downloadVersion = $releases.Where({!$_.prerelease})[0].name.trim('v')
}
$terraformFile = "terraform_${downloadVersion}_windows_amd64.zip"
$terraformURL = "https://releases.hashicorp.com/terraform/${downloadVersion}/${terraformFile}"
$download = Invoke-WebRequest -UseBasicParsing -Uri $terraformURL -DisableKeepAlive -OutFile "${env:Temp}\${terraformFile}" -ErrorAction SilentlyContinue -PassThru
if (($download.StatusCode -eq 200) -and (Test-Path "${env:Temp}\${terraformFile}"))
{
# If SaveToPath does not exist, create it
if (-not (Test-Path -Path $SaveToPath))
{
$null = New-Item -Path $SaveToPath -ItemType Directory -Force
}
# Unblock File
Unblock-File "${env:Temp}\${terraformFile}"
# Unpack archive
Start-Sleep -Seconds 10
Expand-Archive -Path "${env:Temp}\${terraformFile}" -DestinationPath $SaveToPath -Force
# Clean up temp folder
Remove-Item -Path "${env:Temp}\${terraformFile}" -Force
# Set up environment variable
$path = [Environment]::GetEnvironmentVariable('Path','User')
[Environment]::SetEnvironmentVariable('PATH', "${path};${SaveToPath}", 'User')
}
}
catch
{
Write-Error $_
}
@prathibhapadma
Copy link

Hi Rama Krishna, this script is not working

@rchaganti
Copy link
Author

What have you tried?
.\downloadTerraform.ps1 -SaveToPath C:\Terraform -Latest worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment