cls function Get-AzureRmCachedAccessToken() { # Get-AzureRmCachedAccessToken function is downloaded from https://gallery.technet.microsoft.com/scriptcenter/Easily-obtain-AccessToken-3ba6e593/ $ErrorActionPreference = 'Stop' if(-not (Get-Module AzureRm.Profile)) { Import-Module AzureRm.Profile } $azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version # refactoring performed in AzureRm.Profile v3.0 or later if($azureRmProfileModuleVersion.Major -ge 3) { $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile if(-not $azureRmProfile.Accounts.Count) { Write-Error "Ensure you have logged in before calling this function." } } else { # AzureRm.Profile < v3.0 $azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile if(-not $azureRmProfile.Context.Account.Count) { Write-Error "Ensure you have logged in before calling this function." } } $currentAzureContext = Get-AzureRmContext $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile) Write-Debug ("Getting access token for tenant" + $currentAzureContext.Subscription.TenantId) $token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId) $token.AccessToken } # Powershell Azure login requires https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps Login-AzureRmAccount # Using Get-AzureRmCachedAccessToken function to get logged in user access token powershell session $TerraformAzureAccessToken = Get-AzureRmCachedAccessToken $Context = $(Get-AzureRmContext |Select-object Subscription, Tenant) # Putting access token in to a console avalible environemt variable for consumtion by Terraform [Environment]::SetEnvironmentVariable("ARM_ACCESSTOKEN", $TerraformAzureAccessToken , "Process") [Environment]::SetEnvironmentVariable("ARM_SUBSCRIPTION_ID", $($Context.Subscription) , "Process") [Environment]::SetEnvironmentVariable("ARM_TENANT_ID", $($Context.Tenant) , "Process")