Search code examples
powershellazure-devopsyamldevopsazure-pipelines-yaml

Error parsing JSON: Invalid JSON primitive


My Azure YAML Pipeline is failing at Powershell step, not sure why but ConvertFrom-Json line is failing no matter what

Below is the appsettings.json file looks like:

{
  "TestExecution": {
    "TestEnvironment": "$(RUNENVIRONMENTGLOBALLY)",
    "DefaultWaitInSec": 30
  }
}

Below is the YAML I am using

variables:
  RUNENVIRONMENTGLOBALLY : PREPROD

 steps:
  - task: PowerShell@2
    displayName: 'Set Environment To Run'
    inputs:
      targetType: 'inline'
      script: |        
        $appsettingsPath = '$(Build.SourcesDirectory)\appsettings.json'
        $appsettingsContent = Get-Content -Path $appsettingsPath -Raw
        Write-Output $appsettingsContent

        try 
        {
            $appsettingsObject = ConvertFrom-Json $appsettingsContent
            Write-Output $appsettingsObject        
            $appsettingsObject.TestEnvironment = ${RUNENVIRONMENTGLOBALLY}
            $updatedAppsettings = ConvertTo-Json $appsettingsObject -Compress
            Set-Content -Path $appsettingsPath -Value $updatedAppsettings -Force
            Write-Output "Successfully updated appsettings.json"
        }
        catch
        {
              Write-Output "Error parsing JSON: $_"
        }

Solution

  • Please note that the right syntax for referencing a pipeline variable is $(myvar) (macro syntax) or ${{ variables.myvar }} (template expression syntax).

    Also, the json string has an extra property that is not being referenced (TestExecution)

    Instead of:

    $appsettingsObject.TestEnvironment = ${RUNENVIRONMENTGLOBALLY}
    

    Try:

    $appsettingsObject.TestExecution.TestEnvironment = "$(RUNENVIRONMENTGLOBALLY)"