如何使用模板引用 Azure DevOps Pipelines 中另一个存储库中的脚本?

Ben*_*min 17 azure azure-devops azure-pipelines

我正在尝试使用存储在 Azure DevOps 中另一个 Git 存储库中的模板,其中该模板引用了也包含在该存储库中的脚本。虽然我可以成功使用主管道中的模板,但它没有引用模板所需的脚本。

请问我有什么办法可以做到这一点吗?

HelloWorld 模板/脚本存储在 Azure DevOps Repo“HelloWorld”中名为“Templates”的子文件夹中。

HelloWorld.ps1 脚本与以下模板位于同一目录中。

param($Name)

Write-Host "Hello, $Name!"
Run Code Online (Sandbox Code Playgroud)

模板 #1 参考本地脚本

param($Name)

Write-Host "Hello, $Name!"
Run Code Online (Sandbox Code Playgroud)

模板#2

  parameters:
  - name: azureSubscription
    type: string
  - name: name
    type: string
  
  jobs:
  - job: HelloWorld
    displayName: Hello World
    variables:
      name: ${{ parameters.name }}
    steps:
    - task: AzurePowerShell@4
      name: HelloWorld
      displayName: Hello World
      inputs:
        azureSubscription: ${{ parameters.azureSubscription }}
        scriptType: filePath
        scriptPath: ./HelloWorld.ps1
        azurePowerShellVersion: latestVersion
        failOnStandardError: true
        scriptArguments:
          -Name "$(name)"
Run Code Online (Sandbox Code Playgroud)

Vit*_*Liu 16

如果您的管道在另一个存储库中具有模板,或者如果您想要对需要服务连接的存储库使用多存储库签出,则必须让系统知道该存储库。存储库关键字允许您指定外部存储库。

您可以参考另一个存储库中的存储库资源模板以了解更多详细信息。

例如在模板存储库中,我们希望在根目录中找到 test.yml。

resources:
  repositories:
  - repository: templates
    type: git
    name: templates
steps:
- template: test.yml@templates
Run Code Online (Sandbox Code Playgroud)

更新1

我更新了您的代码并且它有效,请检查。

存储库 HelloWord 结构和存储库包含模板文件和 PS1 文件

在此输入图像描述

模板 #1 参考本地脚本。注意:我添加了结帐步骤来结帐HelloWord和管道自我存储库

  parameters:
  - name: azureSubscription
    type: string
  - name: name
    type: string
  
  jobs:
  - job: HelloWorld
    displayName: Hello World
    variables:
      name: ${{ parameters.name }}
    steps:
    - checkout: self
    - checkout: helloworld
    - task: AzurePowerShell@4
      name: HelloWorld
      displayName: Hello World
      inputs:
        azureSubscription: ${{ parameters.azureSubscription }}
        scriptType: filePath
        scriptPath: $(build.sourcesdirectory)/Helloworld/Subfolder/HelloWorld.ps1
        azurePowerShellVersion: latestVersion
        failOnStandardError: true
        scriptArguments:
          -Name "$(name)"
Run Code Online (Sandbox Code Playgroud)

在另一个存储库中创建 yaml 构建定义。

resources:
  repositories:
    - repository: helloworld
      type: git
      name: HelloWorld
pool:
  vmImage: 'windows-latest'
 
stages:
 
- stage: Variables
  jobs:
  - template: hello-world.yml@helloworld
    parameters:
      azureSubscription: 'My Subscription'
      name: 'Billy'
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

  • 我们也是这样做的。不过,非常不幸的是,您被迫在根管道中为存储库资源使用特定名称(即与您在模板的签出步骤中使用的名称完全相同)。事实上,我遇到这个问题是因为我正在寻找一种方法来从模板中找出哪个存储库资源(或者至少是哪个分支引用)用于访问模板。 (3认同)