---
parameters:
  - name: terraform_action
    default: 'apply'
  - name: serviceConnection
  - name: root_module_folder_relative_path
    default: '.'

steps:
  - task: AzureCLI@2
    displayName: Terraform Apply for $${{ coalesce(parameters.terraform_action, 'Apply') }}
    inputs:
      azureSubscription: $${{ parameters.serviceConnection }}
      scriptType: pscore
      scriptLocation: inlineScript
      addSpnToEnvironment: true
      inlineScript: |
        # Get settings from service connection
        az account show 2>$null | ConvertFrom-Json | Set-Variable account
        $clientId = $account.user.name
        $oidcToken = $env:idToken # requires addSpnToEnvironment: true
        $subscriptionId = $account.id
        $tenantId = $account.tenantId

        $env:ARM_TENANT_ID = $account.tenantId
        $env:ARM_SUBSCRIPTION_ID = $account.id
        $env:ARM_OIDC_TOKEN = $oidcToken
        $env:ARM_USE_OIDC = "true"
        $env:ARM_CLIENT_ID = $clientId
        $env:ARM_USE_AZUREAD = "true"
        $env:AZAPI_RETRY_GET_AFTER_PUT_MAX_TIME = "60m" # Accounts for eventually consistent management group permissions propagation

        # Run Terraform Apply
        $command = "terraform"
        $arguments = @()
        $arguments += "-chdir=$${{ parameters.root_module_folder_relative_path }}"
        $arguments += "apply"
        $arguments += "-auto-approve"
        $arguments += "tfplan"
        Write-Host "Running: $command $arguments"
        & $command $arguments
