azure - 循环访问 Azure 管道中的变量

标签 azure powershell azure-devops devops

我有一个文本文件,其中有两个名称 client1client2

我有一个 Powershell 脚本来读取文本文件,我对它的理解是它已经创建了一个数组。

$clientvariable = Get-Content -Path {FilePath}/{File};
Write-Host "vso[task.setvariable variable=clientname]$clientvariable

现在 clientname 的值 $clientvariable 被设置为 client1 client2,如果需要,我可以为每个位置建立索引。

如何在 Azure 管道 YAML 中使用它,以便可以单独查看每个名称并循环遍历下一个名称?

目标是获取每个名称并使用文件中的名称与 ARM 模板结合创建一个资源,即 client1SQLserver client2SQLserver

我已经看到您可以使用带有参数的模板来创建 for 循环,那么这在这种情况下是否有效,或者是否有其他方法可以实现我正在寻找的功能?

最佳答案

How can I use this in an Azure pipeline YAML so that each name can be individually looked at and looped through one after the next?

我们可以指定一个作业根据前一个作业中设置的输出变量的值来运行,以单独循环每个名称。

由于我没有文本文件名,因此我在示例中使用自定义字符数组而不是文件名,例如 $FileNames = '"test1","test2","test3","test4"' :

我的 Azure 管道 yaml 文件:

trigger:
    branches:
      include:
        - master


    stages:
      - stage: LoopFileName
        jobs:
        - job: A
          pool:
            name: MyPrivateAgent
          steps:
          - task: PowerShell@2
            condition: succeeded()
            displayName: "Create a list"
            inputs:
              targetType: 'inline'
              script: |
                  $FileNames = '"test1","test2","test3","test4"'
                      Write-Host "##vso[task.setvariable variable=LoopFileName;isOutput=true]$FileNames"                
            name: fileoutput
    
        - job: B
          dependsOn: A
          pool:
            name: MyPrivateAgent
          variables: 
            AllFileNames: $[dependencies.A.outputs['fileoutput.LoopFileName']]
          steps:
          - template: loopTemplate.yml
            parameters: 
              files : $(AllFileNames)

然后是loopTemplate.yml文件:

parameters:
  files: []

steps :
- task: PowerShell@2
  displayName: 'Fetching ValueFiles'
  inputs:
    targetType: 'inline'
    script: >

      foreach ($i in ${{parameters.files}})
      {
        Write-Host "filenames=$i"
      }

测试结果:

enter image description here

在这种情况下,我们可以使用该名称创建一个资源。

您可以查看文档Conditions了解更多详细信息。

关于azure - 循环访问 Azure 管道中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63387037/

相关文章:

powershell - 禁止显示 Azure Stop-AzureRMVM cmdlet 警告消息框

tfs - 将文件从 Visual Studio Team Services 中的构建服务器提交回存储库

azure-devops - 有没有办法在 Azure DevOps 中创建组织仪表板?

Powershell 并排对象

azure - 通过DevOps API创建端点创建服务端点时设置 "Allow all pipelines"

azure - 设置 Azure VM 的静态 IP 地址

asp.net - 将 ASP.NET Core Razor 页面部署到 Azure 应用服务

azure - 无法使用 Az 模块或 Az/CLI 设置 unauthenticatedClientAction

azure - Azure 搜索基本中是否禁止 OPTIONS 请求?

c# - 将 httpwebresponse 写入文件——powershell——简短而甜美(管道)