Use Powershell to setup any Azure environment for Terraform

Use this Powershell to setup any Azure environment to execute Terraform.

Connect-AzureAD

#Create Terraform Application Registration
$appRegistration = New-AzureADApplication -DisplayName "Terraform" -IdentifierUris "https://localhost/Terraform"
$app = Get-AzureADApplication -Filter "DisplayName eq 'Terraform'"

#Create new Service Principal to execute the Terraform
Connect-AzAccount
$sp = New-AzureADServicePrincipal -AppId $app.AppId -DisplayName "Terraform"
$spCred = Get-AzADServicePrincipal -ObjectId $sp.ObjectId | New-AzADSpCredential

#Convert Secret to unsecure String to pipe to TF environment variables
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spCred.Secret)
$unsecSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

#Get Tenant ID
$tenantId = (Get-AzContext).Tenant.Id

#Get Current Subscription ID
$subId = (Get-AzSubscription).Id

#Connect with Service Principal and set environment variables
$psCredential = New-Object System.Management.Automation.PSCredential ($app.AppId, $spCred.Secret)
Connect-AzAccount -ServicePrincipal -Credential $psCredential -Tenant $tenantID

$env:ARM_CLIENT_ID=$app.AppId
$env:ARM_CLIENT_SECRET=$unsecSecret
$env:ARM_SUBSCRIPTION_ID=$subId
$env:ARM_TENANT_ID=$tenantId

Write-Host TF Environment Variables set:
Write-Host ARM_CLIENT_ID=($app.AppId)
Write-Host ARM_CLIENT_SECRET=($unsecSecret)
Write-Host ARM_SUBSCRIPTION_ID=($subId)
Write-Host ARM_TENANT_ID=($tenantId)
Write-Host Ready to Execute TF!

Leave a comment