【问题标题】:How to set a JSON file as a variable in Azure Pipeline and use it in subsequent task?如何在 Azure Pipeline 中将 JSON 文件设置为变量并在后续任务中使用它?
【发布时间】:2022-11-23 17:38:11
【问题描述】:

我有一个 myJson.json 看起来像这样:

{
  "FirewallGroupsToEnable": [
    "Remote Event Log Management",
    "Windows Remote Management",
    "Performance Logs and Alerts",
    "File and Printer Sharing",
    "Windows Management Instrumentation (WMI)"
  ],
  "MemoryStartupBytes": "3GB"
}

我想将它序列化为一个字符串,然后将它设置为一个变量以供其他任务使用。如果有更好的方法在管道中使用此文件,请告诉我。

我正在序列化它并像这样设置它:

          - task: PowerShell@2
            inputs:
              targetType: 'inline'
              script: |

                  $Configs= Get-Content -Path $(Build.SourcesDirectory)\sources\myJson.json -Raw | ConvertFrom-Json
                  
                  Write-Host "##vso[task.setvariable variable=Configs]$Configs"

在以下任务中,我正在运行 PowerShell 脚本。

          - task: PowerShell@2
            displayName: 'myTask'
            inputs:
              targetType: 'filePath'
              filePath: 'sources\myScript.ps1'
              pwsh: true

我在我的脚本中使用变量是这样的:

$env:Configs
[Configs]$envConfigs = ConvertFrom-Json -InputObject $env:Configs -ErrorAction Stop

Configs 是一个在脚本顶部导入的类,如Using module .\Configs.psm1。我知道它正在被阅读,因为如果不是这样,错误将是关于缺少类型的。

配置.psm1

class Configs
{
    [string[]]$FirewallGroupsToEnable
    [string]$MemoryStartupBytes
}

这就是我在管道中得到的。

##[debug]Processed: ##vso[task.setvariable variable=Configs]@{FirewallGroupsToEnable=System.Object[]; MemoryStartupBytes=3GB}

@{FirewallGroupsToEnable=System.Object[]; MemoryStartupBytes=3GB}
Cannot convert the "@{FirewallGroupsToEnable=System.Object[]; MemoryStartupBytes=3GB}" value of type "System.String" to type "Configs".

我总是将反序列化的 JSON 转换为这样的自定义类型,并且它始终有效。但是现在有点不对劲!

我试图在序列化 JSON 时删除 ConvertFrom-Json(在将其设置为变量之前),但它没有正确序列化。它在管道中显示如下:

看起来它只是得到第一个花括号!

那么,我该如何序列化一个 JSON,而不管它在管道中的深度如何,以便在以后的任务中使用在脚本文件中

【问题讨论】:

    标签: json azure azure-devops azure-pipelines


    【解决方案1】:

    您可以通过文件传递 json 数据,这是我的 YAML sn-p,它可以在下一个任务中成功传递完整的 JSON 内容。

    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $Configs= Get-Content -Path $(Build.SourcesDirectory)wit.json
          $Configs | Out-File Test.json
    
    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $Input = Get-Content Test.json
          Write-Host $Input
    

    这里有类似pass Json variable的票,供参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2020-07-15
      • 2018-08-04
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多